如何使用报警管理器重复我的服务?

时间:2013-05-03 05:16:00

标签: android alarmmanager

我已经完成了基于位置的应用。现在我需要在30分钟内运行我的位置服务一次。为此,我尝试使用警报管理器,但它只运行我的服务一次。我需要每30分钟运行一次吗?

我的代码:

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 个答案:

答案 0 :(得分:2)

您需要在setRepeating()引用而不是set()方法上调用方法AlarmManager

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