Android Studio 如何启动主活动(活动1)后,从通知(活动2)启动的活动在backpress上被破坏

5m1hhzi4  于 12个月前  发布在  Android
关注(0)|答案(2)|浏览(156)

当一个活动从通知中启动后,让我们说activity2(结果)完成或被破坏,当用户使用backpress时,它将进入主屏幕而不是主活动。如何防止这种情况并打开主活动。
到目前为止,方法实现是检查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);

字符串
videnotification.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>

kzmpq1sx

kzmpq1sx1#

TL; DR -OnBackPressed()[当用户按下后退按钮时调用的方法],如果用户从通知进入Activity,则使用Intent启动MainActivity。
我的理解是,只有当通过单击通知启动FromNotificationActivity时,您才希望从Activity 2(让我们称之为FromNotificationActivity)移动到Activity 1(让我们称之为MainActivity),即:
用户单击通知-> FromNotificationActivity启动->按下后退按钮并销毁FromNotificationActivity->您不想返回主屏幕,而是想启动MainActivity。
我相信最快的方法是重写onBackPressed(),并直接转到MainActivity,只有当FromNotificationActivity从通知启动时。
所以,当你创建通知时,添加这一行-

intent.putExtra("origin_from_notification", true);

字符串
因此,您的通知生成器将如下所示-

Intent intent = new Intent(context, FromNotificationActivity.class);
intent.putExtra("origin_from_notification", true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

// TODO: Replace with .Build() for api >= 16
Notification notification = new Notification.Builder(context)
    .setContentTitle("Notification Title"
    .setContentText("Notification text")
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(pendingIntent)
    .// Whatever more you want to add


然后,在您的FromNotificationActivity中,在onCreate()之后添加以下行-

@Override
public void onBackPressed() {
    // Check if the user came here from a notification
    if (getIntent().getBooleanExtra("origin_from_notification", false)) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    } else {
        // Do whatever you want, the user came here from another screen
    }
}


如果您的Activity在标题栏中有后退按钮,请使用此选项-

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            break;
    }
}


希望这对你有帮助!

w3nuxt5m

w3nuxt5m2#

首先在Manifest处添加activity2的android:parentActivityName属性

<activity
    android:name=".Activity2"
    android:parentActivityName=".MainActivity" />

字符串
然后,要启动包含Activity返回堆栈的Activity,您需要创建TaskStackBuilder的示例并调用addNextIntentWithParentStack(),将您要启动的Activity的Intent传递给它。您可以调用getPendingIntent()以接收包含整个返回堆栈的PendingIntent

// Create an Intent for the activity you want to start
Intent resultIntent = new Intent(this, Activity2.class);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
// Get the PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


然后,您可以像往常一样将PendingIntent传递给通知:

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setContentIntent(resultPendingIntent);
...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());

相关问题