Continually Running Background Service

后端 未结 6 1484
挽巷
挽巷 2020-11-29 04:01

I\'m targeting sdk version 27 with a minimum version of 19 and trying to get a service that runs continuously in the background. I tried different service start options but

6条回答
  •  我在风中等你
    2020-11-29 04:54

    Using BroadcastReciever we can run backgrouund service continuously, but if it will get killed , destroy automatically re-instance the old service instance When service stops forcefully it will call onDestroy() method, in this case use one receiver and send one broadcast when ever service destroy and restart service again. in thee following method com.android.app is custom action of reciever class which extends BroadcastReciever

    public void onDestroy() {
        try {
            myTimer.cancel();
            timerTask.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent intent = new Intent("com.android.app");
        intent.putExtra("valueone", "tostoreagain");
        sendBroadcast(intent);
    }
    

    and in onReceive Method

     @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stoped", "call service again");
        context.startService(new Intent(context, ServiceCheckWork.class));
    }
    

    In case device is restarted then we have onBootCompleted action for receiver to catch

    When you are targeting SdkVersion "O"

    In MainActivity.java define getPendingIntent()

    private PendingIntent getPendingIntent() {
      Intent intent = new Intent(this, YourBroadcastReceiver.class);
     intent.setAction(YourBroadcastReceiver.ACTION_PROCESS_UPDATES);
     return PendingIntent.getBroadcast(this, 0, intent, 
      PendingIntent.FLAG_UPDATE_CURRENT);
     }
    

    here we use PendingIntent with BroadcastReceiver and This BroadcastReceiver has already been defined in AndroidManifest.xml. Now in YourBroadcastReceiver.java class which contains an onReceive() method:

     Override
    public void onReceive(Context context, Intent intent) {
    if (intent != null) {
       final String action = intent.getAction();
       if (ACTION_PROCESS_UPDATES.equals(action)) {
           NotificationResult result = NotificationResult.extractResult(intent);
           if (result != null) {
               List notifications = result.getNotification();
               NotificationResultHelper notificationResultHelper = new 
       NotificationResultHelper(
                       context, notifications);
               // Save the notification data to SharedPreferences.
               notificationResultHelper.saveResults();
               // Show notification with the notification data.
               notificationResultHelper.showNotification();
               Log.i(TAG, 
    NotificationResultHelper.getSavedNotificationResult(context));
           }
       }
     }
    }
    

提交回复
热议问题