StartForeground()在终止应用程序后清除通知

时间:2018-09-21 09:17:03

标签: android push-notification notifications

我正在尝试使我的Service在前台运行。没关系,但是  我杀死应用程序时,通知已清除
还有一点需要注意的是,它在android 7.0的XIAOMI REDMI NOTE 4上不起作用。

示例代码

    final Intent notificationIntent = new Intent();
    final PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            0,
            notificationIntent,
            0
    );

    final Intent intent = new Intent(this, ForegroundService.class);
    intent.setAction(STOP_SERVICE_ACTION);
    final PendingIntent stopIntent = PendingIntent.getService(
            this,
            0,
            intent,
            PendingIntent.FLAG_CANCEL_CURRENT
    );

    final NotificationCompat.Action action = new NotificationCompat.Action(0, getString(R.string.stop), stopIntent);

    final Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANEL_ID)
            .addAction(action)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .setContentText(getString(R.string.searching_in_surrounding))
            .build();

    startForeground(FOREGROUND_NOTIFICATION_ID, notification);  


 public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && STOP_SERVICE_ACTION.equals(intent.getAction())) {
        stopSelf();
        return START_NOT_STICKY;
    }

    if (isRunning) {
        return START_STICKY;
    }
    return START_STICKY;
}

有什么问题?

1 个答案:

答案 0 :(得分:0)

请使用此方法来自动启动中文rom设备中的服务,因为当设备处于后台或从最近的任务管理器中消失时,这些设备会自动forcestop应用程序

public void auto_start_permission() {
    String manufacturer = "xiaomi";
    if (manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
        //this will open auto start screen where user can enable permission for your app
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
        startActivity(intent);
    }
}

更多参考信息refer