aus*_*len 28
您应该创建一个粘性服务.在这里阅读更多相关信息.
您可以通过在onStartCommand中返回START_STICKY来完成此操作.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)
另请阅读应用程序:持久性,即"应用程序是否应始终保持运行".这更麻烦 - 系统会尽量不杀死你的应用程序,这将影响系统中的其他人,你应该小心使用它.
我从我以前做过的应用程序中使用的服务中复制了这个.
它不重要任何UI的重要性.因为您在服务中没有用户界面.这也适用于Toasts.
祝好运
public class nasserservice extends Service {
private static long UPDATE_INTERVAL = 1*5*1000; //default
private static Timer timer = new Timer();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
_startService();
}
private void _startService()
{
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
doServiceWork();
}
}, 1000,UPDATE_INTERVAL);
Log.i(getClass().getSimpleName(), "FileScannerService Timer started....");
}
private void doServiceWork()
{
//do something wotever you want
//like reading file or getting data from network
try {
}
catch (Exception e) {
}
}
private void _shutdownService()
{
if (timer != null) timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped...");
}
@Override
public void onDestroy()
{
super.onDestroy();
_shutdownService();
// if (MAIN_ACTIVITY != null) Log.d(getClass().getSimpleName(), "FileScannerService stopped");
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29669 次 |
最近记录: |