2

我做了一个基于位置的应用程序。现在我需要在 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();
        }
4

1 回答 1

2

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

    AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm_manager.setRepeating(AlarmManager.RTC, cur_cal.getTimeInMillis(), 180000,  pi);
于 2013-05-03T05:38:26.717 回答