如何确定发生了什么类型的onResume

时间:2015-09-27 15:47:30

标签: android push-notification

当用户来自push notification时,我需要创建一个新对象。

当用户点击通知时,会{触发onResume(故意)。在onResume方法中,我需要根据响应调用服务器并创建一个对象。但是,我无法确定如何确定onResume是由通知触发还是由其他内容触发,例如打开屏幕。

我对Intent flags了解不多,但也许解决方案可能就在那里。

这是配置和触发push notification

的代码
private void sendNotification(String message, String topic) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("resumeType", "BattleNotification");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String contentTitle = "Message from Maguss";
    switch (topic){
        case "battle":
            contentTitle = "Your battle was accepted";
            break;
    }
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setContentTitle(contentTitle)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

3 个答案:

答案 0 :(得分:0)

在您的活动中,您可以获得启动它的意图,然后检查它以确定它是否来自通知。

可能有些什么

if (getIntent().getStringExtra("resumeType") != null) { /* from notification */ }

适合你。

答案 1 :(得分:0)

onResume方法中,您可以检查是来自推送通知还是来自其他活动。请参阅以下代码

@Override
protected void onResume() {
    super.onResume();
    String resumeType = getIntent().getStringExtra("resumeType");
    if (resumeType!=null && resumeType.equalsIgnoreCase("BattleNotification")){
            // from push notification
    }else{

    }
}

答案 2 :(得分:0)

这两个答案都很好,但是他们没有成功。我还是要加上这个:

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

如此处所述:Getting old intent extras in onResume() after startActivity(newIntent)

相关问题