1.在Manifest里面声明服务
<service android:enabled="true" android:name=".MyService"/>
2.新建MyService类
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
//任务内容
}
},0,5000);
}
@Override
public void onDestroy() {
}
@Override
public void onStart(Intent intent, int startid) {
}
}
3.Activity
startService(new Intent(this, MyService.class));