Android alarm is cancelled after closing the application

后端 未结 7 1019
遥遥无期
遥遥无期 2020-12-03 04:45

I have a problem with AlarmManager, I set the code for scheduling a repeating alarm and after I run the application, the alarm runs fine. Even if I click on Home button (and

7条回答
  •  臣服心动
    2020-12-03 05:10

    I have been able to do exactly what you need. Even if you stop the application through the running tab in the application manager tool, the service restarts itself. The only way to kill it is throught the force stop button next to the unistall option in application manager. Basically you call the Service directly. Here is My Code:

    public class TestService extends Service {
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            Toast.makeText(this, "Ejecutando Servicio ...", Toast.LENGTH_SHORT).show();
        return Service.START_NOT_STICKY;    
        }
    
    @Override
        public void onCreate() {
          super.onCreate();
          Toast.makeText(this, "Iniciando Servicio ...", Toast.LENGTH_SHORT).show();
    }
    
        @Override
        public void onDestroy() {
          super.onDestroy();
          Toast.makeText(this, "Deteniendo Servicio ...", Toast.LENGTH_SHORT).show();
    }   
    

    On client activity write the following code:

                Calendar cal = Calendar.getInstance();
            Intent intent = new Intent(this,TestService.class);
            PendingIntent pIntent = PendingIntent.getService(this.getApplicationContext(), 0, intent, 0);
            alarm=  (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 3*1000, pIntent);
    

    And declare the service in manifest:

            
                 
    

提交回复
热议问题