问题描述
我是android中远程消息的新手,当从服务器接收消息时执行此代码。这个想法是在消息到达应用程序时启动应用程序,直到sdk 26都可以正常工作,但是在新的sdk版本中,消息不会启动应用程序。我还需要什么呢?一些权限,其他标志?
public void onMessageReceived(RemoteMessage message) {
try {
Uri uriBeep = Uri.parse("someExample" + R.raw.win);
notificationmanager manager = (notificationmanager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,"Notification",notificationmanager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.setLightColor(Color.GRAY);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(uriBeep,audioAttributes);
channel.enableVibration(true);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(uriBeep)
.setContentTitle(getString(R.string.app_name))
.setContentText(message.getData().get("message"))
.setAutoCancel(true)
.setPriority(1)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setVibrate(VIBRATE_PATTERN)
.setContentIntent(pendingIntent);
if (manager != null) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
manager.notify(0,builder.build());
}
} catch (Exception e) {
e.printstacktrace();
}
}
解决方法
从Android 10(API级别29)开始,存在一些限制,这些限制会阻止后台代码启动活动。参见https://developer.android.com/guide/components/activities/background-starts
这个想法是,推送通知和其他异步事件不应干扰用户当前正在执行的操作。可接受的方法是显示Notification
,然后用户可以在需要时打开应用程序。这会将控制权交给用户。