单击通知时更新活动

问题描述 投票:1回答:2

我在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>

G cm intent service.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);
}

什么可能是错的?

android android-activity push-notification google-cloud-messaging
2个回答
1
投票

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

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

0
投票

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

如何使用本地广播在这里阅读https://stackoverflow.com/a/8875292/826657

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.