召回Android服务

时间:2014-05-13 09:12:42

标签: android service background-process

如何在每10秒后回忆起我的Android服务。 这是我的服务类。

package com.example.vaccinationsystem;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class BackgroundServices extends Service{

     private static final String TAG = "MyService";

     @Override
     public IBinder onBind(Intent arg0) {
        return null;
      }

  @Override
   public void onCreate() {
    Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");
  }

  @Override
  public void onStart(Intent intent, int startId) {
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
   }

   @Override
  public void onDestroy() {
    Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
  }
 }

我通过以下方式在其他课程中称呼它:

        startService(new Intent(this, BackgroundServices.class));       

如何在每10秒后运行一次。

1 个答案:

答案 0 :(得分:0)

试试这个AlarmManager

   public void startTimer()
    {
        Log.i("timer Striii" , "timer is ");
        Intent Service1 = new Intent(MainActivity.this , BackgroundServices.class);
        PendingIntent piService1 = PendingIntent.getService(MainActivity.this , 0 , Service1 , PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager1 = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
        alarmManager1.cancel(piService1);
        alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP , System.currentTimeMillis() , 16500 , piService1);
    }