【发布时间】:2020-02-23 01:18:50
【问题描述】:
从通知启动 Activity 后,可以说当用户使用 backpress 时,activity2(result) 完成或销毁,它会进入主屏幕而不是 Main Activity。如何防止这种情况并打开 mainactivity。
到目前为止,方法实现是检查 activity2 是直接从 mainactivity(使用 extras)启动还是从通知启动,以便根据 bundle 值控制 onDestory,但这是一个明显的时间差是纠正这个或启动通知时创建堆栈历史记录
当前代码
notificationservice.java
Intent resultIntent = new Intent(this, videonotifications.class);
Intent parentIntent=new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
//stackBuilder.addNextIntentWithParentStack(resultIntent);
stackBuilder.addParentStack(videonotifications.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
createNotificationChannel(mNotificationManager);
Notification notification = new NotificationCompat.Builder(this,DEFAULT_CHANNEL_ID)
.setContentTitle("Fall Detected")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("A Fall Has Been Detected By Smart Video Surveillance At Old Age Home's Common Room"))//Set the title of Notification
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.build();
mNotificationManager.notify(1, notification);
final Intent i=new Intent(this,notificationsservice.class);
//stopService(i);
videonotification.java
public void onDestroy() {
//to be optimized as the roundabout procedure
super.onDestroy();
Bundle extras;
extras=getIntent().getExtras();
if(extras==null){
Intent i=new Intent(this,MainActivity.class);
i.putExtra("activity","notification is already called");
startActivity(i);
}
}
MainActivity.java
Bundle extras=null;
extras=getIntent().getExtras();
if(extras==null){
final Intent i=new Intent(this, notificationsservice.class);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
startService(i);
}
},5000);}
AndroidManifest.xml
<activity
android:name=".videonotifications"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
【问题讨论】:
-
参考this
标签: android android-studio android-intent android-notifications