由于近期需要实现在Notification点击把后台的App调起来,即最后显示的Activity在调起来后应该是在第一个界面,且整个App的task不改变,在网上查了以下几种方法都行不通
1.在Androidmanifest.xml的根Activity添加android:alwaysRetainTaskState="true"属性。
2.在Androidmanifest.xml给Activity添加android:launchMode="singleInstance"属性。
3.
Intent intent = new Intent();
intent.setComponent(new ComponentName(context, ActivityMain.class));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
4.
PackageManager packageManager = getPackageManager();
Intent baiduIntent = packageManager.getLaunchIntentForPackage("com.baidu.navi"); //传入相应的包名
最后发现在Launcher界面点击Icon启动后台的App就不会重复启动且task也不会改变,于是就去查看Launcher源码,启动App也只是把Intent传入而已,通过打印:
---startActivitySafely intent = Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
flg=0x10200000
cmp=com.ddd.fragmentgroup/.MainActivity }
于是就有了下面的代码
Intent intent = new Intent(this, MainActivity.class); //这里的MainActivity是根Activity
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
|是按位或的意思,由于flg=0x10200000所以就是以下两个值的或运算。
public static final int FLAG_ACTIVITY_NEW_TASK = 0x10000000;
public static final int FLAG_ACTIVITY_RESET_TASK_IF_NEEDED = 0x00200000;
完整显示Notification的函数
/**
* 显示Notification
*
* @param context
*/
private void showNotification(Context context) {
CharSequence title = getText(R.string.app_name);
CharSequence text = getText(R.string.app_back);
Notification.Builder builder = new Notification.Builder(this);
Intent intent = new Intent(this, ActivityMain.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
builder.setAutoCancel(true);
builder.setContentTitle(title);
builder.setContentText(text);
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
至此Android在Notification中不重复启动App的方法已经介绍完了,各位有更好的办法可以提出来一起学习下。