IntentService 作用
IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作,当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,依次去执行,执行完自动结束
(简而言之,启动后台服务,调用官方写的的方法,不需要自己新开辟线程)
使用方法
new ->service(IntentService)
MyIntentService .java
package com.example.intentservice;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class MyIntentService extends IntentService {
private static final String ACTION_FOO = "com.example.intentservice.action.FOO";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.example.intentservice.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.example.intentservice.extra.PARAM2";
public MyIntentService() {
super("MyIntentService");
}
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
System.out.println("第一步");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二步");
handleActionFoo("结束","结束");
}
}
}
private void handleActionFoo(String param1, String param2) {
// TODO: Handle action Foo
System.out.println("第三步");
Log.v("myTag",param1+param2);
}
}
MainActivity.java
MyIntentService.startActionFoo(MainActivity.this, "1", "2");
个人理解:
自定义自己想要的服务,填入即可,传入的参数可传,可不传。
注 (官方说大多数情况下,最奥使用 JobIntentService)