2012-07-16 97 views
0

需要一个将在后台运行的服务,它将在30-120秒后唤醒并找到设备所在的位置,然后将该位置发送到数据中心并进入睡眠状态。在30-120秒后服务清醒并确定位置并进入睡眠。我可以手动启动和停止服务。但是我需要启动(30到120秒之间)并自动停止服务。我不能保持服务生效,因为它会耗尽电池。将在后台自动运行和停止的服务

So,My question is how can i start and stop the service automatically? 

感谢提前任何建议。

我的代码是

public class Service extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button start = (Button)findViewById(R.id.startButton); 
     Button stop = (Button)findViewById(R.id.stopButton); 

     start.setOnClickListener(startListener); 
     stop.setOnClickListener(stopListener); 

    } 

private OnClickListener startListener = new OnClickListener() { 
public void onClick(View v){ 
    startService(new Intent(Service.this,SimpleService.class)); 
}    

};

private OnClickListener stopListener = new OnClickListener() { 
    public void onClick(View v){ 
     stopService(new Intent(Service.this,SimpleService.class)); 
    }    
}; 
} 

回答

3

您可以根据您的要求使用AlarmManager类。创建一个警报,在特定定时器间隔(在你的情况下30-120秒)唤醒Service。同时通过调用onDestroy()方法唤醒以前的运行服务。

+0

谢谢lucifer。我的代码是 – Kabir 2012-07-16 06:41:37

+0

欢迎你,高兴地帮助你:) – Lucifer 2012-07-16 06:45:17

+0

Mr.lucifer我是AlarmManager的新手。你能帮我解答一下吗?上面给出了我的代码来启动和停止服务。 – Kabir 2012-07-16 06:49:34