特定时间android后启动服务

时间:2013-03-28 06:32:21

标签: android

我在我的项目中提供了服务,我希望每隔2分钟开始一次。我正在使用以下代码,但它无法正常工作。

public class ScheduleSync extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent i = new Intent(context, StartMyServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 60000*2, pending);

    }

}



public class StartMyServiceReceiver extends BroadcastReceiver
{    
    public void onReceive(Context context, Intent intent) 
    {
        Toast.makeText(context, "receive broadcast", Toast.LENGTH_LONG).show();
        Log.d("StartMyServiceReceiver", "receive broadcast");
        Intent service = new Intent(context, myservice.class);
        context.startService(service);
    }
}

请帮助我解决这个问题。当我看到taskmanager myservice正在后端运行时。

1 个答案:

答案 0 :(得分:0)

为什么要使用AlarmManager

只需使用Thread.sleep(xxxx)

public class ScheduleSync extends BroadcastReceiver{
    private Context context;
    private void startOtherService(){
        Intent i = new Intent(context, StartMyServiceReceiver.class);
        context.startService(i);
    }
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        this.context = context;
        new Thread(new Runnable(){
            public void run(){
                try{
                    Thread.sleep(2*60*1000);
                    startOtherService();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

}