IntentService简单使用与总结

来源:互联网 发布:淘宝专业版免费的模板 编辑:程序博客网 时间:2024/06/05 12:02

参考:点击打开链接


IntentService的官方介绍:

IntentService is a base class for {@link Service}s that handle asynchronous 
requests (expressed as {@link Intent}s) on demand. Clients send requests 
through {@link android.content.Context#startService(Intent)} calls; the 
service is started as needed, handles each Intent in turn using a worker 
thread, and stops itself when it runs out of work.

意思是说IntentService是一个基于Service的一个类,用来处理异步的请求。你可以通过startService(Intent)来提交请求,该Service会在需要的时候创建,当完成所有的任务以后自己关闭,且请求是在工作线程处理的。

这么说,我们使用了IntentService最起码有两个好处,一方面不需要自己去new Thread了;另一方面不需要考虑在什么时候关闭该Service了。

看例子:

这是一个模拟耗时的例子,可以把耗时改写成需要的任务,比如:上传图片,录音等等,先看效果图:


每当我们点击一次按钮,会将一个任务交给后台的Service去处理,后台的Service每处理完成一个请求就会反馈给Activity,然后Activity去更新UI。当所有的任务完成的时候,后台的Service会退出,不会占据任何内存。

onHandleIntent中是处理耗时任务的,从log中可以看出,每次做耗时任务都会新建一个线程,当这个线程中的任务未完成时,往里加任务,会走onStartCommand,但不会onCreate,当线程中的任务都完成了,会走onDestroy,再次启动服务,还是先走onCreate


源码:

package com.example.byc.testasynchronousprocess;import android.app.IntentService;import android.content.Intent;import android.content.Context;import android.os.StrictMode;import android.support.annotation.Nullable;import android.support.v4.content.LocalBroadcastManager;import android.util.Log;/** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * 

* TODO: Customize class - update intent actions, extra parameters and static * helper methods. */public class UploadImgService extends IntentService { // TODO: Rename actions, choose action names that describe tasks that this // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS private static final String ACTION_UPLOAD_IMG = "com.example.byc.testasynchronousprocess.action.UPLOAD_IMAGE"; // TODO: Rename parameters public static final String EXTRA_IMG_PATH = "com.example.byc.testasynchronousprocess.extra.IMG_PATH"; private final static String TAG = "UploadImgService--"; public static void startUploadImg(Context context, String path) { Intent intent = new Intent(context, UploadImgService.class); intent.setAction(ACTION_UPLOAD_IMG); intent.putExtra(EXTRA_IMG_PATH, path); context.startService(intent); } public UploadImgService() { super("UploadImgService"); } @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); handleActionUploadImg(path); } } } /** * Handle action Foo in the provided background thread with the provided * parameters. */ private void handleActionUploadImg(String param1) { Log.e(TAG, "handleActionUploadImg-" + Thread.currentThread().getName() + "--" + param1); try { Thread.sleep(3000); Intent intent = new Intent(IntentServiceActivity.UPLOAD_RESULT); intent.putExtra(EXTRA_IMG_PATH, param1); //直接用sendBroadcast,在IntentServiceActivity中接收不到,因为IntentServiceActivity中是用LocalBroadcastManager注册的广播 LocalBroadcastManager.getInstance(UploadImgService.this).sendBroadcast(intent); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void onCreate() { Log.e(TAG, "onCreate"); super.onCreate(); } @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); super.onDestroy(); }}

package com.example.byc.testasynchronousprocess;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.support.v4.content.LocalBroadcastManager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;public class IntentServiceActivity extends AppCompatActivity {    public static final String UPLOAD_RESULT = "UPLOAD_RESULT";    private Button btn_add_task;    private LinearLayout cur_linearlayout;    private int i = 0;    private LocalBroadcastManager lbm;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_intent_service);        initView();    }    private BroadcastReceiver br = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            if(intent.getAction() == UPLOAD_RESULT){                handlePath(intent.getStringExtra(UploadImgService.EXTRA_IMG_PATH));            }        }    };    private void initView(){        cur_linearlayout = (LinearLayout)findViewById(R.id.cur_linearlayout);        btn_add_task = (Button)findViewById(R.id.add_task);        btn_add_task.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View view) {                addTask();            }        });        lbm  = LocalBroadcastManager.getInstance(this);        lbm.registerReceiver(br,new IntentFilter(UPLOAD_RESULT));    }    private void handlePath(String path){        TextView tv = (TextView)cur_linearlayout.findViewWithTag(path);        tv.setText(path + " upload success ~~~~ ");    }    public void addTask(){        //模拟路径        String path = "/sdcard/imgs/"+(++i)+".png";        UploadImgService.startUploadImg(this,path);        TextView tv = new TextView(this);        cur_linearlayout.addView(tv);        tv.setText(path + " is uploading...");        tv.setTag(path);    }    @Override    protected void onDestroy() {        super.onDestroy();        lbm.unregisterReceiver(br);    }}
    

Service与Activity通信,我们用的LocalBroadcastManager  ,



原创粉丝点击