1. Service
1>:Service服務是長期運行在后臺;
2>:它不是單獨的進程,因為它和應用程序在同一個進程;
3>:也不是單獨的線程,它跟線程沒有任何關系,所以不能進行耗時操作;
4>:如果直接把耗時操作放在Service中的onStartCommand()中,可能發(fā)生ANR,如果有耗時操作,就必須開啟一個單獨的線程來處理;
為了解決這樣的問題,就引入了IntentService;
2. IntentService
1>:啟動方式和Service一樣,都是startService();
2>:繼承于Service,包含Service所有特性,包括生命周期,是處理異步請求的一個類,;
3>:一般自定義一個InitializeService繼承Service,然后復寫onHandleIntent()方法,在這個方法中初始化這些第三方的,來執(zhí)行耗時操作;
4>:可以啟動多次IntentService,每一個耗時操作以工作隊列在onHandleIntent()方法中執(zhí)行,執(zhí)行完第一個再去執(zhí)行第二個,以此類推;
5>:所有的請求都在單線程中,不會阻塞主線程,同一個時間只處理同一個請求;
6>:不需要像在Service中一樣,手動開啟線程,任務執(zhí)行完成后不需要手動調(diào)用stopSelf()方法來停止服務,系統(tǒng)會自動關閉服務;
3. IntentService使用
1>:一般用于App啟動時在BaseApplication中初始化一些第三方的東西,比如騰訊Bugly、騰訊X5WebView、OkhttpUtils等,目的就是為了防止BaseApplication中加載東西過多,導致App啟動速度過慢,所以就自定義一個 InitializeService,繼承Service,然后重寫 onHandleIntent()方法,在這個方法中初始化這些第三方的;
BaseApplication代碼如下:
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//initLeakCanary(); //Square公司內(nèi)存泄漏檢測工具
//在子線程中初始化
InitializeService.start(this);
}
}
InitializeService代碼如下:
/**
* Email: 2185134304@qq.com
* Created by JackChen 2018/4/12 15:35
* Version 1.0
* Params:
* Description:
*/
public class InitializeService extends IntentService {
private static final String ACTION_INIT = "initApplication";
public static void start(Context context) {
Intent intent = new Intent(context, InitializeService.class);
intent.setAction(ACTION_INIT);
context.startService(intent);
}
public InitializeService(){
super("InitializeService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_INIT.equals(action)) {
initApplication();
}
}
}
private void initApplication() {
initBugly(); //初始化騰訊bug管理平臺
// BaseConfig.INSTANCE.initConfig(); //初始化配置信息
LogUtils.logDebug = true; //開啟日志
}
/**
* 初始化騰訊bug管理平臺
*/
private void initBugly() {
/* Bugly SDK初始化
* 參數(shù)1:上下文對象
* 參數(shù)2:APPID,平臺注冊時得到,注意替換成你的appId
* 參數(shù)3:是否開啟調(diào)試模式,調(diào)試模式下會輸出'CrashReport'tag的日志
* 注意:如果您之前使用過Bugly SDK,請將以下這句注釋掉。
*/
CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
strategy.setAppVersion(AppUtils.getAppVersionName());
strategy.setAppPackageName(AppUtils.getAppPackageName());
strategy.setAppReportDelay(20000); //Bugly會在啟動20s后聯(lián)網(wǎng)同步數(shù)據(jù)
/* 第三個參數(shù)為SDK調(diào)試模式開關,調(diào)試模式的行為特性如下:
輸出詳細的Bugly SDK的Log;
每一條Crash都會被立即上報;
自定義日志將會在Logcat中輸出。
建議在測試階段建議設置成true,發(fā)布時設置為false。*/
CrashReport.initCrashReport(getApplicationContext(), "126dde5e58", true ,strategy);
Log.e("TAG" , "初始化bugly111") ;
}
}