通知显示打开的应用程序正在后台运行

时间:2019-07-24 06:12:17

标签: android service notifications android-8.0-oreo android-9.0-pie

我可以从显示应用程序在后台运行的通知中打开应用程序吗?我尝试了以下代码

String NOTIFICATION_CHANNEL_ID = "xxx.xxxx.xxxx.myapplication";
        String NOTIFICATION_CHANNEL_NAME = "hhyydddddd";
        String NOTIFICATION_CHANNEL_DESC = "DDDDDDDDDDD";
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentTitle("App is running in background")
                .setContentText("HELLO")
                .setTicker("TICKER").setFullScreenIntent(pendingIntent,true)
                .setContentIntent(pendingIntent);
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        if(Build.VERSION.SDK_INT>=26) {
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(NOTIFICATION_CHANNEL_DESC);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);

        }
        startForeground(NOTIFICATION_ID, notification);

使用此代码,我可以在具有android pie的设备中打开应用程序,但是当我在具有oreo的设备上尝试相同的代码时,单击通知会转到应用程序信息页面。

1 个答案:

答案 0 :(得分:0)

您是否使用BroadcastReceiver类?当您关闭应用程序时,广播可以监听此操作。因此,如果您创建一个BroadcastReceiver类,就不会遇到这个问题。

public class ClosedBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, HomePage.class));
        } else {
            context.startService(new Intent(context, HomePage.class));
        }
    }
}