How to run service in background every 10 minute?

后端 未结 5 1008
独厮守ぢ
独厮守ぢ 2021-02-10 03:04

I want to use a service that run in background indefinitely and call a method every 10 minute and its running even app killed

How to create it?

5条回答
  •  孤城傲影
    2021-02-10 03:52

    You can use the Alarm manager which will be called after every 10 mins

            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Random random = new Random();
            int m = random.nextInt(9999 - 1000) + 1000;
    
            Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
            notificationIntent.setClass(this,AlarmReceiver_.class);
            notificationIntent.addCategory("android.intent.category.DEFAULT");
    
            PendingIntent broadcast = PendingIntent.getBroadcast(YourClass.this, m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + 300000L,
                    600000L, broadcast);
    

    ManiFest receiver Code where you will get a receiver response

    
            
                
                
                
                
                
    
            
        
    

    You will have to create Receiver where you will receive data as an above-specified name of AlarmReceiver_.class

提交回复
热议问题