Srevice不是在子线程,在Srevice中做耗时操作一样ANR,然后我们就会用到IntentService,IntentSrevice不但擅长做耗时操作,还有一个特点,用完即走;
在Srevice中做耗时轮询操作,使用Handler:
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
private Handler mHandler = new Handler(){
@Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
switch (msg.what){
case HANDLERSIGN:
Log.i(TAG, "dispatchMessage: "+args+(++num));
mHandler.sendEmptyMessageDelayed(HANDLERSIGN,HANDLERTIME);
if (num == 5){
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MyService.this.stopSelf();
}
});
AlertDialog dialog = builder.create();
dialog.setMessage("我的计数"+num);
dialog.setTitle("提示");
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
break;
}
}
};
private final String TAG = "ccb";
private String args;
private int num;
private final int HANDLERSIGN = 10;
private final int HANDLERTIME = 2010;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
args = intent.getStringExtra("args");
initData();
return super.onStartCommand(intent, flags, startId);
}
private void initData() {
mHandler.sendEmptyMessageDelayed(HANDLERSIGN,HANDLERTIME);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: 啊,ByKill");
mHandler.removeCallbacksAndMessages(null);
}
}
在IntentSrevice中做耗时轮询操作,可以任性到这种程度:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
public void onCreate() {
super.onCreate();
}
private final String TAG = "ccb";
private String args;
private int num;
@Override
protected void onHandleIntent(Intent intent) {
args = intent.getStringExtra("args");
initData();
}
private void initData() {
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(3000);
Log.i(TAG, "dispatchMessage: "+args+(++num));
if (num == 5) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyIntentService.this);
AlertDialog dialog = builder.setPositiveButton("确定", null).create();
dialog.setMessage("我的计数" + num);
dialog.setTitle("我是服务");
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
return;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: MyIntentService");
}
}
IntentSrevice中的onHandlerIntent()方法走完就会销毁掉自己,立马走onDestroy()方法;