首页 > 解决方案 > 在 Android 7 上终止应用程序前台服务后停止但在 Android 6 和 8 设备上工作

问题描述

我在我的应用程序中使用前台服务,在 Android M 和 Oreo 上它运行良好,但在 Android 7 设备上,如果我们从内存中删除应用程序,该服务会停止(清除最近的活动)。以下是我的活动

start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startService(start);
        }
    });

public void startService(View view) {
    Intent serviceIntent = new Intent(getApplicationContext(),ExampleService.class);
    serviceIntent.putStringArrayListExtra("appList",appList);
    ContextCompat.startForegroundService(this,serviceIntent);
}

在服务中我正在使用:

@Override
public int onStartCommand(Intent intent,int flag,int startid) {
    Intent notificationIntent = new Intent(this,MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
    scannedApp = intent.getStringArrayListExtra("appList");

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            getAPKFilePath();
        }
    });
    t.start();

    Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("Working in Background")
            .setSmallIcon(R.drawable.noti)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1,notification);
    return START_STICKY;
}

getAPKFilePath();方法上,我正在做一些繁重的任务。在 Android 7 中,如果应用程序存在于内存中,那么它可以正常工作(如果只是按下后退按钮),但如果从内存中删除,那么它就无法正常工作。既不显示通知图标。

任何建议将不胜感激。谢谢

标签: androidservice

解决方案


推荐阅读