How to repeat my service using alarm manager?

2019-02-27 10:50发布

问题:

I have done a location based app. Now I need to run my location service once in 30 mins. For that I have tried using alarm manager but it is running my service only once. I need it to run every 30 mins?

My code:

gps_back_process.java:

public class gps_back_process extends Service
{
    private static final String TAG = "MyService";
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.d("Testing", "Service got created");
        Toast.makeText(this, "gps_back_process,onCreate();", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    @Override
    public void onStart(Intent intent, int startid)
    {
        Intent intents = new Intent(getBaseContext(),gps.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "gps_back_process.onCreate();", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}

gps.java:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        {
            Calendar cur_cal = Calendar.getInstance();
            cur_cal.setTimeInMillis(System.currentTimeMillis());
            cur_cal.add(Calendar.SECOND, 90);
            Log.d("Testing", "Calender Set time:" + cur_cal.getTime());
            Intent intent = new Intent(gps.this, gps_back_process.class);
            Log.d("Testing", "Intent created");
            PendingIntent pi = PendingIntent.getService(gps.this, 0, intent, 0);
            AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(), pi);
            Log.d("Testing", "alarm manager set");
            Toast.makeText(this, "gps_back_process.onCreate()",
                    Toast.LENGTH_LONG).show();
        }

回答1:

You need to call the method setRepeating() on the AlarmManager reference rather than set() method.

    AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm_manager.setRepeating(AlarmManager.RTC, cur_cal.getTimeInMillis(), 180000,  pi);