这是服务类的简单代码
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "MSG onCreate SERVICE", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "MSG onStartCommand SERVICE", Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "MSG STOP SERVICE", Toast.LENGTH_LONG).show();
super.onDestroy();
}
}
这是测试此服务的代码
startService(new Intent(this, MyService.class));
new Timer().schedule(new TimerTask() {
@Override
public void run() {
startService(new Intent(getApplicationContext(), MyService.class));
}
}, 5000);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
stopService(new Intent(getApplicationContext(), MyService.class));
}
}, 10000);
这工作得很好。还要在清单中添加此代码
<service android:name=".MyService" />