I have a navigation drawer, and if a user clicks on the navigation drawer item he will return to the home screen.
However, if the home screen is already active, I do not want to create a duplicate activity with an intent. I am essentially trying to check if the activity is already active / in the backstack, as I do not want to utilize resources inefficiently.
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
Toast.makeText(getApplicationContext(),"CLICKED 0",Toast.LENGTH_SHORT).show();
Log.v("DRAWER", "THE DRAWER HAS BEEN CLICKED");
if (getCallingActivity() == HomeActivity){
onBackPressed();
} else {
Intent I = new Intent();
}
break;
Try this.
get current Activity
// get current activity
public static Activity getCurrentActivity() {
try {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(
null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map activities = (Map) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
Then
change your code to this
if (getCurrentActivity() instanceof HomeActivity) {
onBackPressed();
} else {
Intent I = new Intent();
}
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.