Service stop's whenever app is killed

后端 未结 3 610
渐次进展
渐次进展 2020-12-17 03:13

START_STICKY don\'t work in my device whenever i kill my app then service don\'t start again, My device name is Redmi Note 3 Pro, but whenever i run same app in android emul

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 03:57

    You need to add "android:process=:any_name" in the manifest under the inside the service attributes.

    For example,

          
    

    Below is the code of my Service class.

    public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("onCreate", "onCreate");
        Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("servicedestroy", "servicedestroy");
        Toast.makeText(AppController.getInstance(),"service destroy",Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
    
                                      new Handler(Looper.getMainLooper()).post(new Runnable() {
                                          @Override
                                          public void run() {
                                              Toast.makeText(AppController.getInstance(),"Running",Toast.LENGTH_SHORT).show();
                                          }
                                      });
    
    
                                  }
    
                              },
                0,
                5000);
    
        return START_STICKY;
    }
    
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());
    
        PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);
    
        super.onTaskRemoved(rootIntent);
    }
    

    }

提交回复
热议问题