IntentService继承Service,并在其创建了工作现场,用来处理耗时操作。
启动时与正常service一样,可以调用startservice来启动IntentService。
注意无参数构造方法的定义。
startService(new Intent(MainActivity1.this, CoreService.class));
package com.e.uu;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
public class CoreService extends IntentService {
String ex = "";
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Toast.makeText(CoreService.this, "-e " + ex, Toast.LENGTH_LONG)
.show();
}
};
public CoreService() {
// 必须定义一个无参数的构造方法,并调用super(name)进行初始化,否则出错。
super("CoreService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ex = intent.getStringExtra("start");
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.sendEmptyMessage(0);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}