How can I list all opened activities on Xamarin.Android? - android

I'm new to mobile development and I'm learning Xamarin. I already have some experience with C#.
I'm currently studying hierarchical navigation with Xamarin.Android.
In my project, I have the main activity, second and third activities where I navigate between them. I would like to know how can I list all opened activities?
For example, if I'm in the main activity and I request the list of opened activities, the function should return me a list with the name of the main activity only, but if I'm in the third activity, the function should return me a list containing the name of the main, second and third activities, more or less like this:
MainActivity
SecondActivity
ThirdActivity
How can I get this information?
I am working with Xamarin.Android and not Xamarin.Forms.

You could use ActivityManager to get the details of the Activities.
The GetRunningTasks would return a list of the tasks that are currently running. But this method was deprecated in API level 21. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.
For now, we only could use the BaseActivity to get the first activity and use the TopActivity to get the current one.
ActivityManager m = (ActivityManager)this.GetSystemService(ActivityService);
var runningTaskInfoList = m.GetRunningTasks(10);
foreach (var item in runningTaskInfoList)
{
string first = item.BaseActivity.ShortClassName;
string current = item.TopActivity.ShortClassName;
}

thanks for your help.
I think that's almost it. I made a small modification to your code, looking like this:
public string ListAllActivities()
{
string result = "";
ActivityManager activityManager = (ActivityManager)this.GetSystemService(ActivityService);
var runningTaskInfoList = activityManager.GetRunningTasks(10);
foreach (var item in runningTaskInfoList)
{
string first = item.BaseActivity.ShortClassName.Substring((item.BaseActivity.ShortClassName.LastIndexOf('.') + 1), item.BaseActivity.ShortClassName.Length - (item.BaseActivity.ShortClassName.LastIndexOf('.') + 1));
string current = item.TopActivity.ShortClassName.Substring((item.TopActivity.ShortClassName.LastIndexOf('.') + 1), item.TopActivity.ShortClassName.Length - (item.TopActivity.ShortClassName.LastIndexOf('.') + 1));
result += first + " - " + current + "\n";
}
return result;
}
And the result is this:Activities Stack
When I'm in the third activity, I don't get the list for the second activity. If I, being in the third activity, could list the second and main activities, the issue would be resolved.

Related

Is there better way to navigate in Android based on source fragment?

I have fragments S1, S2, P, D1, and D2.
Both S1 and S2 have action leading to P. When I am in fragment P I can navigate to D1 or D2.
When I came from S1 I want to navigate to D1, but when I came from S2 I want to go to D2.
What is the best way to do navigate based on the source fragment?.
I know I can use arguments for this, but it seems like a much more basic operation. I would expect some more clear and quicker solution (for example some method getNameOfSource()).
You can do this via getting the entry from your Fragment Backstack, although you need to ensure you are providing some sort of TAG to them in the first place. You can simply use something like this then. Using arguments is still better I would say, but that is out of scope for this question
private fun getNameOfSource(): String? {
val fm = supportFragmentManager
val count = fm.backStackEntryCount
return fm.getBackStackEntryAt(count - 2).name
}
You can get the fragment tag using this code:
public Fragment getSourceFragmentName() {
// you need to check this because you need at least 2 fragments at the backstack
if (getSupportFragmentManager().getBackStackEntryCount() < 2) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 2).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}

i can't make a contact between the activities in Kotlin

Hello this is my first app with kotlin i am trying to make annual rate calculation app the problem is i have 4 activities every activity own button and edit's texts
i wan't when The User click the button, the program get the numbers from Edit's texts and only make the calculation and save it somewhere and same work for the activity 2 and 3.
but when he click the last button of the last activity i want to call all the results and show it in ViewText
The Question is:How to save data Every time somewhere and call when i need it?
First Activity
class st {
var int_P: Double? = null
var ctl_P: Double? = null
public constructor(int_P: Any, ctl_P: Any) {
this.int_P = int_P.toString().toDouble() //Physique
this.ctl_P = ctl_P.toString().toDouble()
public fun GetMP(): Double {
return (this.int_P!! + (this.ctl_P!! * 2)) / 3
}
}
Btn_Next1.setOnClickListener ({
var int_P = java.lang.Double.parseDouble(edit_IP.text.toString()) //Physique
var ctl_P = java.lang.Double.parseDouble(edit_CP.text.toString())
var ss = st(int_P,ctl_P)
val ic = Intent(this, Sec_Act::class.java)
startActivity(ic)
})
(Secend and Third Activity Same)
Activity 4
btn1.setOnClickListener ({
var act1 = MainActivity.st().GetMC()
Textv.text = act1.toString()
})
With this method i got problem (no value passed for parameter int_P , ctl_P)
There are many different ways to send information back to an Activity:
onActivityResult(),
having a singleton class,
use Shared Preferences,
headless fragments,
sqlite database,
store the information in a file.
Intents
receivers
You need to determine which will be the best solution for you. Whether it's kotlin or java, the methodology will be the same.

Android simple Hashmap not maintaining values?

I've recently tried to simplify some data structures by posting them into a simple key, value map. I push a log to verify the value has been associated to the key during the .put method.
When I later call a .get, the value is no longer available. Important code snippets:
MainActivity.class
public final HashMap<String, Integer> resumeMap = new HashMap<String, Integer>();
if (resumeMap.containsKey(url)) {
Log.i("Value is there!", url);
resumeTime = resumeMap.get(url);
Log.i("Value set to:", "" + resumeTime);
} else {
resumeTime = 0;
Log.i("Value is not found!", "" + url);
}
public void setHashmap(String url, Integer time) {
resumeMap.put(url, time);
int newTime = resumeMap.get(url);
Log.i("Setting:", "URL: " + url);
Log.i("Setting:", "TIME:" + newTime);
}
VideoPlayer.class
MainActivity setter = new MainActivity();
setter.setHashmap(urlString, player.getCurrentPosition());
In the setHashmap method, the log is correctly outputting both url and time as expected. However resumeMap.containsKey(url) is remaining false, even while the debugger is confirming an expected matching key via "Value is not found!" output.
To make clear, during first pass in MainActivity, I expect a not found result, the VideoPlayer class is then called with the resumeTime of 0 with proper results. I verify the setting of the key and value, and when I open the same link I am still receiving a 0.
I originally built the Hashmap in it's own class, with the same results. I moved the map to the MainActivity just to debug. Thank you for any assistance you may be able to provide.
Activity instances are quickly destroyed and re-created all the time, for example, when you rotate the screen (but for other reasons as well). It often appears that the Activity is "still there", but the actual underlying object instance has been destroyed and recreated.
A quick way to verify that that is really the problem before going down the instance state bundle path is to make the HashMap static to prevent instance destruction from destroying it.
Sometimes, static maps like this are OK, but proceed with caution, as structures like this open up avenues for leaking memory all over the place. A better approach is to use some sort of persistence, or if you only need the information while the Activity is being used, pass the information around using onSaveInstanceState and onRestoreInstanceState (see http://developer.android.com/training/basics/activity-lifecycle/recreating.html)

Basics ---> Checking strings using if else to set value of an int, possible wrong use of onResume

So I'm still working on my first little app here, new to Android and Java, so I'm stuck on a basic little problem here. Answers to my first questions were really helpful, so after researching and not coming up with anything, I thought I'd ask for some more help!
The idea is that on another screen the user makes a choice A, B, C, or D, and that choices is passed as a string through the intent. OnResume checks if the choice is not null and sets an integer that corresponds to that string. Later when the user pushes another button, some if else logic checks that int and performs and action based on which was chosen. The problem is that the App crashed at onResume.
I learned that I have to use equals(string) to compare string reference, but maybe the problem is that I am trying to compare a string in reference to a literal string? Any help would be greatly appreciated.
Thanks!
protected void onResume() {
super.onResume();
// Get the message from the intent
Intent intent = getIntent();
String choice = intent
.getStringExtra(ExtensionSetupSlector.TORQUE_SETUP);
// Create the text view
TextView displayChoice = (TextView) findViewById(R.id.displayChoice);
if (!choice.equals("")){
displayChoice.setText(choice);
if (choice.equals("A")) {
myChoice = 1;
}
if (choice.equals("B")) {
myChoice = 2;
}
if (choice.equals("C")) {
myChoice = 3;
}
if (choice.equals("D")) {
myChoice = 4;
}
}
}
myChoice is declare right after ...extends Activity{ Also I'm not quite sure If this should really be in onResume, but it was working before I started try to set myChoice in the onResume (when I was just displaying the choice). Thanks again!
Change if (!choice.equals("")) to check for null instead. Otherwise your app attempts to access an empty reference and crashes.

Get Android category information of a running task

In Android, I can get the running tasks and activities using code like tis:
(ActivityManager.RunningTaskInfo) this.mActivityManager.getRunningTasks()
Then I can get the package name, class name etc.
My question is that whether there is a way to get the "category" information from it? Or anyone can suggest an alternative solution? for example, when I launch an app, the category is
cat=[android.intent.category.LAUNCHER]
I am not really sure what you mean, but maybe the following is what you want: retrieve the intent in your activity by calling getIntent(), and on the Intent object call the method getCategories(). This method will return a set with category strings.
I am not really sure, whether this would solve your problem, but you may use ActivityManager's getRecentTasks(int, int) API to get information about the recent tasks. It returns a list of ActivityManager.RecentTaskInfo objects, which have information about the intent used to launch the task. You can also use RecentTaskInfo.id field to map the task with the running tasks.
I found no direct way of doing it, but this may help:
Intent ApplicationIntent = new Intent(Intent.ACTION_MAIN);
ApplicationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> LauncherResolves = packageManager.queryIntentActivities(ApplicationIntent, 0);
List<String> AppsList = new ArrayList<String>();
for (int i = 0; i < LauncherResolves.size(); i++)
AppsList.add(LauncherResolves.get(i).activityInfo.name);
List<RunningTaskInfo> runningAppInfo = activityManager.getRunningTasks(10);
for (int i = 0; i < runningAppInfo.size(); i++)
{
if (AppsList.contains(runningAppInfo.get(i).topActivity.getClassName()))
{
// Do what ever you want
}
}

Categories

Resources