Create a Scheduled service in android

前端 未结 1 1095
礼貌的吻别
礼貌的吻别 2021-01-01 04:49

I need to create a schedule service in android with java. I have tried some codes , but all time after build the application it doesn\'t run. My logic is simple , I want to

1条回答
  •  囚心锁ツ
    2021-01-01 05:20

    There are two ways to achieve your requirement.

    • TimerTask
    • Alarm Manager Class

      TimerTask has a method that repeats the activity on the given particular time interval. look at the following sample example.

      Timer timer; 
      MyTimerTask timerTask; 
      
      timer = new Timer(); 
      timerTask = new MyTimerTask();
      timer.schedule ( timerTask, startingInterval, repeatingInterval );
      
      private class MyTimerTask extends TimerTask 
      {
           public void run()
           { 
              ...
              // Repetitive Activity goes here
           } 
      }
      

      AlarmManager does same thing like TimerTask but as it occupies lesser memory to execute tasks.

      public class AlarmReceiver extends BroadcastReceiver 
      {
          @Override
          public void onReceive(Context context, Intent intent) 
          {
              try 
              {
                  Bundle bundle = intent.getExtras();
                  String message = bundle.getString("alarm_message");
                  Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
              } 
              catch (Exception e) 
              {
                   Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
       e.printStackTrace();
              }
         }
      }
      

    AlarmClass,

    private static Intent alarmIntent = null;
    private static PendingIntent pendingIntent = null;
    private static AlarmManager alarmManager = null;
    
        // OnCreate()
        alarmIntent = new Intent ( null, AlarmReceiver.class );
        pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, alarmIntent, 0 );
    alarmManager = ( AlarmManager ) getSystemService( ALARM_SERVICE );
        alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, ( uploadInterval * 1000 ),( uploadInterval * 1000 ), pendingIntent );
    

    0 讨论(0)
提交回复
热议问题