【齊天的博客】轉載請註明出處(萬分感謝!):
https://blog.csdn.net/qijinglai/article/details/80747150
關聯文章:
Android多線程(Handler篇)
Android多線程(AsyncTask篇)
Android多線程(HandlerThread篇)
Android多線程(IntentService篇)
前言
例如上傳下載等操作原則上要儘可能的交給Service去做,原因就是上傳等過程中用戶可能會有將應用至於後臺,那這時候Activity很有可能就被殺死了。如果擔心Service被殺死還能通過startForeground提升優先級。
但在Service裏需要開啓線程才能進行耗時操作,自己管理Service與線程聽起來就不像一個優雅的做法,此時就可以用到Android提供的一個類,IntentService。上一篇說到了HandlerThread,而HandlerThread的一個實例就是今天寫到的IntentService。
使用
步驟
- 創建MyIntentService繼承IntentService,並在onHandlIntent()中實現耗時操作
- Activity註冊並啓動廣播監聽耗時操作完成事件,如更新UI
- Activity中啓動MyIntentService
示例代碼如下:
public class MyIntentService extends IntentService {
private static final String ACTION_UPLOAD_IMG = "com.qit.action.UPLOAD_IMAGE";
public static final String EXTRA_IMG_PATH = "com.qit.extra.IMG_PATH";
public static void startUploadImg(Context context, String path) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_UPLOAD_IMG);
intent.putExtra(EXTRA_IMG_PATH, path);
context.startService(intent);
}
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_UPLOAD_IMG.equals(action)) {
final String path = intent.getStringExtra(EXTRA_IMG_PATH);
handleUploadImg(path);
}
}
}
private void handleUploadImg(String path) {
try {
//模擬上傳耗時
Thread.sleep(((long) (Math.random() * 3000)));
Intent intent = new Intent(MainActivity.UPLOAD_RESULT);
intent.putExtra(EXTRA_IMG_PATH, path);
sendBroadcast(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class MainActivity extends AppCompatActivity {
public static final String UPLOAD_RESULT = "com.qit.UPLOAD_RESULT";
private LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.ll);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addTask();
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(UPLOAD_RESULT);
registerReceiver(uploadImgReceiver, filter);
}
private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == UPLOAD_RESULT) {
String path = intent.getStringExtra(MyIntentService.EXTRA_IMG_PATH);
handleResult(path);
}
}
};
private void handleResult(String path) {
TextView tv = (TextView) ll.findViewWithTag(path);
tv.setText(path + " upload success ~~~ ");
}
int i = 0;
public void addTask() {
//模擬路徑
String path = "/sdcard/imgs/" + (++i) + ".png";
MyIntentService.startUploadImg(this, path);
TextView tv = new TextView(this);
ll.addView(tv);
tv.setText(path + " is uploading ...");
tv.setTag(path);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(uploadImgReceiver);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="點" />
</LinearLayout>
記得IntentServic也是Service要註冊
原理分析
源碼不多全部拿過來看
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
* This may be null if the service is being restarted after
* its process has gone away; see
* {@link android.app.Service#onStartCommand}
* for details.
*/
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}
- onCreate:裏面初始化了一個HandlerThread,關於HandlerThread可以看我上一篇文章 Android多線程(HandlerThread篇)
- onStartCommand:中回調了onStart
- onStart中通過mServiceHandler發送消息到該handler的handleMessage中去。
- handleMessage():回調onHandleIntent(intent)後回調用 stopSelf(msg.arg1),注意這個msg.arg1是個int值,相當於一個請求的唯一標識。每發送一個請求,會生成一個唯一的標識,然後將請求放入隊列,當全部執行完成(最後一個請求也就相當於getLastStartId == startId),或者當前發送的標識是最近發出的那一個(getLastStartId == startId),則會銷燬我們的Service.如果傳入的是-1則直接銷燬。
- 當任務完成銷燬Service回調onDestory,可以看到在onDestroy中釋放了我們的Looper:mServiceLooper.quit()。
end。