单击通知时更新活动

时间:2014-08-30 13:25:42

标签: android android-activity push-notification google-cloud-messaging

我在Android中使用推送通知。当我收到推送通知并点击它时,它会根据需要启动一个活动,但如果此活动已经打开,则没有任何事情发生,活动会保留旧数据。

的AndroidManifest.xml

 <activity
        android:name=".Detail"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_detail"
        android:launchMode="singleTop"
        android:parentActivityName=".Home"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="ma.via.marocagenda.Home" />
    </activity>

GCMIntentService.java

public class GCMIntentService extends GCMBaseIntentService {
...
private static void generateNotification(Context context, String message) {
    //int icon = R.drawable.abc_ic_go;
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, Detail.class);
    // put extra for details
    notificationIntent.putExtra("id", VAL_TAG_ID);
    notificationIntent.putExtra("titre", VAL_TAG_TITRE);

    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    notificationIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
    //PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}

什么可能是错的?

2 个答案:

答案 0 :(得分:1)

您可以在活动中覆盖onNewIntent(),以从通知中获取最新意图。

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.hasExtra("key")){
            //do your Stuff
        }
    }

答案 1 :(得分:0)

每当推送通知到达时,您都可以使用服务中的本地广播。

  

如何使用本地广播,请阅读https://stackoverflow.com/a/8875292/826657

让您的活动注册此广播操作,并在收到推送通知时,从onReceive()更新活动。

此外,使用ActivityManager更具体,您可以检查您是否活动在顶部,如果是,则发送广播,否则只显示通知。

  

请阅读此处了解如何查找当前的前台活动。   https://stackoverflow.com/a/4753333/826657

相关问题