Android - 点击通知不会导致活动

时间:2014-02-15 22:39:34

标签: android

我有一个计时器,可在完成时创建通知。单击通知应该会导致名为TimerActivity的活动。我创建了这样的通知:

mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(completeNotificationIcon)
.setContentTitle(completeNotificationTitle)
.setContentText(completeNotificationText)
.setTicker(completeNotificationTicker)
.setAutoCancel(true);

Intent notificationIntent = new Intent(this, TimerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
mBuilder.setContentIntent(contentIntent);
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 

问题是活动未打开,通知只是自动取消。

在进一步调查中,只有TimerActivity不会像这样打开。如果我改变打开说明SttingsActivity.class的意图,它就可以正常工作。清单中的TimerActivity:

    <activity   
       android:name=".TimerActivity"
       android:parentActivityName=".MainActivity"
       android:label="@string/action_timer"
       android:theme="@style/AppTheme">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />           
    </activity>

但它的定义与任何其他可以通过点击通知

工作/可以打开的活动一样

2 个答案:

答案 0 :(得分:4)

解决方案是将标志FLAG_CANCEL_CURRENT添加到PendingIntent。

答案 1 :(得分:0)

您正在尝试在活动之外打开活动 你应该在意图上设置一些标志,使其正常工作。请试试这个代码并告诉我

 mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(completeNotificationIcon)
.setContentTitle(completeNotificationTitle)
.setContentText(completeNotificationText)
.setTicker(completeNotificationTicker)
.setAutoCancel(true);

Intent notificationIntent = new Intent(this, TimerActivity.class);
       notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//single top to avoid                //creating many activity stacks queue
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());