Need code example on how to run an Android service forever in the background even when device sleeping, like Whatsapp?

后端 未结 5 1978
死守一世寂寞
死守一世寂寞 2020-11-30 19:51

I have tried various ways to achieve this, but my service eventually gets killed.

I want to use AlarmManager to trigger a class every one hour. Even if the device is

5条回答
  •  北海茫月
    2020-11-30 20:44

    It is very simple.
    steps:
    1.create a Service class.
    2.create a BroadcastReceiver class
    3.call BroadReceiver in onDestroy method of service
    4.In onReceive method of BroadReceiver class start service once again.

    Here's the code

    Manifest file:`

    
    
        
            
                
    
                
            
        
        
    
        
    
        
            
                
            
        
    
    

    `

    Service class

    public class NotificationService extends Service {
        public NotificationService() {
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
           super.onStartCommand(intent, flags, startId);
           return START_STICKY;
       }
    
       @Override
       public void onDestroy() {
           super.onDestroy();
           Intent restartService = new Intent("RestartService");
           sendBroadcast(restartService);
      }
    }
    

    BroadcastReceiver class

    public class RestartService extends BroadcastReceiver {
    
         @Override
         public void onReceive(Context context, Intent intent) {
    
             context.startService(new Intent(context,NotificationService.class));
         }
     }
    

提交回复
热议问题