我想按fcm通知时调用onNewIntent()方法。
我读了一些有关此问题的问答,我认为我的代码很简单。
但它不起作用。我不知道出了什么问题:(
这是我的代码。
FCM:
private void sendPushNotification(String message) {
System.out.println("received message :" + message);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.untitled)
.setContentTitle("This is title")
.setContentText(message)
.setPriority(Notification.PRIORITY_MAX)
.setVibrate(new long[]{0,500})
.setContentIntent(pendingIntent);
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakelock.acquire(5000);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
onNewIntent():
@Override
public void onNewIntent(Intent intent){
super.onNewIntent(intent);
setIntent(intent);
Bundle extras = intent.getExtras();
if(extras != null){
Toast.makeText(getApplicationContext(),"Hello!",Toast.LENGTH_LONG).show();
}
}
AND MANIFEST:
<activity android:name=".MainActivity"
android:launchMode="singleTop">
logcat中只有两个错误:
07-25 18:38:18.216 25648-25648 /? E / Zygote:v2
07-25 18:38:18.221 25648-25648 /? E / Zygote:accessInfo:0
答案 0 :(得分:1)
重新发布我在此处找到的解决方案: click on notification to go current activity
添加以下行:
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
我不知道为什么必须设置它们,但是如果你没有设置它们onNewIntent就不会被调用。