IntentService执行后台服务

来源:互联网 发布:ga遗传算法c 实现 编辑:程序博客网 时间:2024/05/21 17:14

一、在Android的应用中,往往需要在执行主界面的操作时,如果要执行耗时的操作,那么应该是另外开线程的,或者是用async或者handler;除非你特别指定,否则大部分在前台UI界面上的操作都执行在一个叫做UI Thread的特殊线程中;那么其实android framework层还提供了另一种API就是Intentservice;


二、也可以自己在android training学习,有详细的demo讲解,地址:

       英文:http://developer.android.com/training/run-background-service/index.html

       中文:http://hukai.me/android-training-course-in-chinese/background-jobs/run-background-service/index.html


三、实现原理图(来自网络)


四、使用注意点:

不可以直接更新UI;
工作任务队列是顺序执行的,如果一个任务正在IntentService中执行,此时你再发送一个任务请求,这个任务会一直等待直到前面一个任务执行完毕;
正在执行的任务无法打断;


五、代码实现
demo代码地址:https://github.com/hefengs/IntentServiceDemo

package com.hf.main;import android.app.IntentService;import android.content.Intent;import android.support.v4.content.LocalBroadcastManager;import android.util.Log;public class MyIntentService extends IntentService{    public static final String BROADCAST_ACTION = "com.hf.main.toast";        public MyIntentService() {        // TODO Auto-generated constructor stub        super("MyIntentService");        Log.e("hefeng", "MyIntentService");    }        public MyIntentService(String name) {        super(name);        // TODO Auto-generated constructor stub        Log.e("hefeng", "MyIntentService");    }        @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // TODO Auto-generated method stub        Log.e("hefeng", "onStartCommand");        return super.onStartCommand(intent, flags, startId);    }    @Override    protected void onHandleIntent(Intent intent) {        // TODO Auto-generated method stub                Log.e("hefeng", "onHandleIntent");                // 从传入的intent获取数据//        String dataString = intent.getDataString();                // IntentService里面是可以进行耗时的操作的            try {            Thread.sleep(3000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                Log.i("hefeng", "休眠3s结束,通知主程序");                //推荐的方式是使用LocalBroadcastManager,这个组件可以限制broadcast只在自己的App中进行传递。        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_ACTION));    }}

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.hf.main"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.hf.main.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <!--因为android:exported 被设置为false,该服务只能在本应用中使用-->        <service android:name="com.hf.main.MyIntentService" android:exported="false"/>            </application></manifest>

package com.hf.main;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.support.v4.content.LocalBroadcastManager;import android.util.Log;public class MainActivity extends Activity {    private ResponseReceiver mResponseReceiver;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                     startService(new Intent(this, MyIntentService.class));        IntentFilter filter = new IntentFilter(MyIntentService.BROADCAST_ACTION);//        添加数据过滤器,只允许http类型的数据//        filter.addDataScheme("http");        mResponseReceiver = new ResponseReceiver();        //推荐的方式是使用LocalBroadcastManager,这个组件可以限制broadcast只在自己的App中进行传递。        LocalBroadcastManager.getInstance(this).registerReceiver(mResponseReceiver, filter);    }    // 广播接收器,用于接受I ntentService更新的状态    private class ResponseReceiver extends BroadcastReceiver {        //防止实例化        private ResponseReceiver() {            // TODO Auto-generated constructor stub        }        @Override        public void onReceive(Context context, Intent intent) {            // TODO Auto-generated method stub            String action = intent.getAction();            if (MyIntentService.BROADCAST_ACTION.equals(action)) {                Log.e("hefeng", "接收到MyIntentService数据");            }        }    }    @Override    protected void onDestroy() {        // TODO Auto-generated method stub        super.onDestroy();        LocalBroadcastManager.getInstance(this).unregisterReceiver(mResponseReceiver);    }}

0 0
原创粉丝点击