我在Android开发方面做得很少,我想知道是否有人有关于服务的好教程。 我正在寻找一个应用程序,即使在后台也会启动并继续循环。
答案 0 :(得分:11)
如果您进行简单的谷歌搜索,那么服务上有大量资源,因此我不打算解释服务的运作方式。下面的代码段使用未绑定到Activity的服务。
我的方法使用Timer和Task,请注意我使用的是重复的任务,但这不是必需的。还有其他方法可以解决这个问题。
public class MyService extends Service {
private Task retryTask;
Timer myTimer;
private boolean timerRunning = false;
private long RETRY_TIME = 200000;
private long START_TIME = 5000;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
myTimer = new Timer();
myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
timerRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!timerRunning) {
myTimer = new Timer();
myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
timerRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}
public class Task extends TimerTask {
@Override
public void run() {
// DO WHAT YOU NEED TO DO HERE
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (myTimer != null) {
myTimer.cancel();
}
timerRunning = false;
}
}
然后,您将使用Intent
从Activity启动服务Intent intent = new Intent(WorkSelectionActivity.this,MyService.class);
startService(intent);
希望这有帮助
答案 1 :(得分:1)
谷歌的official introduction很漂亮。看看吧。
答案 2 :(得分:1)
如果您正在寻找视频教程,请使用标记 Android开发教程在youtube上进行搜索。所以有四个部分。每个人都很棒。其中一个人同意服务教程。