将通知中的参数发送到其他活动?

时间:2014-12-29 01:10:15

标签: android android-intent notifications bundle lifecycle

我对此处回答的问题有一个跟进问题:如何从通知点击向活动发送参数?

所以,我有3个活动,A,B和C.当用户进入活动C时,闹钟(计时器)开始。在X时间后,状态栏中会出现一个通知。以下是我发布通知的方式。 “MainActivity.class”是活动A.但是,以这种方式启动通知会在关闭它时在用户所处的任何活动中重新启动应用程序。因此,如果他们在应用程序关闭时进入活动C并且他们点击通知,则应用程序将恢复到活动C.

Intent notificationIntent = new Intent( this, MainActivity.class );
notificationIntent.setAction( Intent.ACTION_MAIN );
notificationIntent.addCategory( Intent.CATEGORY_LAUNCHER );
notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED );
notificationIntent.putExtra( NotifyService.NOTIFICATION_INTENT, true );

PendingIntent contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );

Notification notification = new Notification.Builder( this )
.setContentTitle( title )
.setContentText( text )
.setTicker( ticker )
.setSmallIcon( R.drawable.ic_launcher )
.setWhen( time )
.setContentIntent( contentIntent )
.setAutoCancel( true )
.setDefaults( Notification.DEFAULT_ALL )
.build();

我在活动A,B和C的清单中有这个:android:launchMode =“singleTop”。我还在每个活动中都有以下代码。

@Override
public void onNewIntent( Intent intent )
{
    super.onNewIntent( intent );

    Bundle extras = intent.getExtras();

    if( extras != null )
    {
        Boolean startedFromNotification = extras.getBoolean( NotifyService.NOTIFICATION_INTENT );

        if( startedFromNotification )
        {
            // Do something
        }
    }
}

现在,如果用户在关闭应用时处于活动A中,则当他们点击通知(按预期工作)时,会在该活动中调用onNewIntent。但是,如果它们处于活动B或C中,那么这些活动中的onNewIntent不仅不会被调用,而且我放在那里的额外内容(NotifyService.NOTIFICATION_INTENT)也会丢失。

当应用程序恢复到活动B或C时,是否仍然将通知意图附加内容传递给应用程序?

1 个答案:

答案 0 :(得分:0)

我通过这个问题得到了答案:FLAG_ACTIVITY_NEW_TASK在PendingIntent中使用时表现不正常

首先,我更改了这一行:

Intent notificationIntent = new Intent( this, MainActivity.class );

要:

Intent notificationIntent = new Intent( this, NotificationActivity.class );

我使NotificationActivity.class成为占位符活动,让其他活动知道应用程序何时从通知中恢复。删除了这些代码行:

notificationIntent.setAction( Intent.ACTION_MAIN );
notificationIntent.addCategory( Intent.CATEGORY_LAUNCHER );
notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED );
notificationIntent.putExtra( NotifyService.NOTIFICATION_INTENT, true );

而且,这一行:

PendingIntent contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );

更改为:

PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT );

在NotificationActivity的onCreate()方法中,我将这些行添加到底部:

STARTED_FROM_NOTIFICATION = true;
finish();

STARTED_FROM_NOTIFICATION位于公共源文件中。然后,在onStart()方法的每个活动中:

if( STARTED_FROM_NOTIFICATION == true )
{
    STARTED_FROM_NOTIFICATION = false;
    // Do something
}

我也删除了android:launchMode =" singleTop"来自所有活动。

使用此方法,NotificationActivity将放在现有活动堆栈之上,但会在显示之前完成。完成后,onStart()将调用它下面的活动,并且操作将按照需要运行。

相关问题