简体   繁体   中英

How to check whether the activity I am starting is the activity which is running?

I have 6 Buttons, for 1st 3 Buttons I want to start same activity and for other 3 Buttons separate new activities.

So problem arises when i click on 1st button and then the second Button which starts same activity because we can not start same activity from same activity.

So I just need to know weather the activity which i am going to start is the same activity which is running, based on that if same activity then I'll just update some UI contents else start new activity.

So anyone can help me to know this?

Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

Example here

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

Here's an example.

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);



     // get the info from the currently running task
     List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); 

     Log.d("topActivity", "CURRENT Activity ::"
             + taskInfo.get(0).topActivity.getClassName());

     ComponentName componentInfo = taskInfo.get(0).topActivity;
   componentInfo.getPackageName();

You will need the following permission on your manifest:

uses-permission android:name="android.permission.GET_TASKS"

You can check activity's class, for example (suppose 'this' is current activity):

if (this instanceof ActivityClassYouGoingToStart) {
    // update UI
} else {
    // start new activity
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM