Service简介:Android四大组件之一,运行在后台,没有界面,因为运行在主线程中,所以不能在其中做耗时操作,回阻塞UI,解决办法是新起Thread线程,处理耗时操作
IntentService简介:继承至Service用来处理异步请求,并且在所有任务完成后会主动关闭服务
测试:
service:
package com.example.administrator.intentservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
* Created by Administrator on 2015/10/20.
*/
public class MyService extends Service {
@Override
public void onStart(Intent intent, int startId) {
// new Thread(new Runnable() {
// @Override
// public void run() {
//
// Thread.sleep(3 * 1000);
// System.out.println("Service ok");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }).start();
try {
Thread.sleep(3 * 1000);
System.out.println("Service ok");
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
IntentService:
package com.example.administrator.intentservice;
import android.app.IntentService;
import android.content.Intent;
/**
* Created by Administrator on 2015/10/20.
*/
public class MyIntentService extends IntentService {
public MyIntentService(){
super("");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
try {
Thread.sleep(3*1000);
System.out.println("IntentService ok");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Manifest:
<service android:name=".MyService"></service>
<service android:name=".MyIntentService"></service>
测试:
package com.example.administrator.intentservice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// startService(new Intent(this, MyIntentService.class));
// startService(new Intent(this, MyIntentService.class));
// startService(new Intent(this, MyIntentService.class));
startService(new Intent(this, MyService.class));
startService(new Intent(this, MyService.class));
startService(new Intent(this, MyService.class));
}
}
分别开启三个任务,结果如下:
IntentService:
Service:
可见IntentService会主动创建线程去一次执行任务,而Service不开启新线程的情况下会阻塞UI线程!
参考:http://blog.csdn.net/lmj623565791/article/details/47143563