首页 > 解决方案 > 当应用程序关闭时继续在后台运行,就像通知中的whatapps消息一样

问题描述

“当我打开应用程序并startService发送通知但如果我关闭我的应用程序然后永远不要停止应用程序并继续运行我的应用程序就像电话消息如果你关闭消息应用程序但继续运行

public class MainActivity extends AppCompatActivity {

    private Intent service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        service = new Intent(this, CallService.class);
        Log.i("JobServiceCall","beforeServiceCall");
        startService(service);
        Log.i("JobServiceCall","afterServiceCall");
    }

    @Override
    public void onStop(){
        super.onStop();
    }

    @Override
    public void onDestroy(){
        Log.i("JobServiceCall","beforeServiceCallOnDestroyed");
        startService(service);
        Log.i("JobServiceCall","AfterServiceCallOnDestroyed");
        super.onDestroy();
    }
}

public class CallService extends Service {

    public static int waitTime=10*1000;  //seconds

    //public static int defaultTime=15*60*1000; // default Minutes

    @Override
    public void onCreate(){
        super.onCreate();
        Log.i("JobServiceCall","onCreate Service");
        backgroundProcess();
    }

    public void backgroundProcess(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                int i=0;
                for(;;){
                   Log.i("JobServiceCall","run : "+i++);
                    OneTimeWorkRequest request=new OneTimeWorkRequest.Builder(WorkJob.class).build();
                    WorkManager.getInstance().enqueue(request);
                   try {
                       Thread.sleep(waitTime);
                   }
                   catch (InterruptedException ie){
                       ie.printStackTrace();
                   }
                }
            }
        }).start();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.i("JobServiceCall","service keep running on destroy");
        Intent broadcastIntent = new Intent();
       // broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this,  RestartServiceOnBroadcastReceiver.class);
        this.sendBroadcast(broadcastIntent);
        Log.i("JobServiceCall","send Broadcast Receiver");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

“输出是当我打开应用程序时继续运行,如果我的应用程序关闭,则服务会自行停止”

“我想继续运行我的应用程序”

标签: android

解决方案


**You need to use a Foreground Service to keep alive background service**

public class ForegroundService extends Service {
    public static final String CHANNEL_ID = "ForegroundServiceChannel";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);

        //do heavy work on a background thread


        //stopSelf();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

}

------------------------------Start and Stop Forground Service----------------

public void startService() {
        Intent serviceIntent = new Intent(this, ForegroundService.class);
        serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");

        ContextCompat.startForegroundService(this, serviceIntent);
    }

    public void stopService() {
        Intent serviceIntent = new Intent(this, ForegroundService.class);
        stopService(serviceIntent);
    }


 -----------------------------------Add Service in Manifest-------------------


 <service
            android:name=".ForegroundService"
            android:enabled="true"
            android:exported="true"></service>

推荐阅读