android后台任务(二):IntentService

来源:互联网 发布:网站源码盗取工具 编辑:程序博客网 时间:2024/06/05 18:26

大多数情况下,IntentService是简单后台任务的理想选择,Asynctask使用容易出现内存泄漏。
首先,新建一个IntentService的类:

package com.example.asus.practise;public class MyIntentService extends IntentService{    //固定写法    public MyIntentService()    {        super("MyIntentService");    }    @Override    protected void onHandleIntent(Intent intent)    {        if (intent != null)        {            //这里处理Intent            String action = intent.getAction();            if ("自定义动作".equals(action))            {                Intent localIntent = new Intent("自定义动作");                //处理完成发送广播                LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);            }        }    }}

因为是Service,所以要在manifests中注册,在application标签中:

        <service            android:name=".MyIntentService"            android:exported="false" >        </service>

可以在UI界面向IntentService发送任务:

        Intent action1 = new Intent(MainActivity.this,MyIntentService.class);        action1.setAction("自定义动作");        startService(action1);

在UI界面接收IntentService处理任务完成后返回的结果,需要注册一个广播接收器:

package com.example.asus.practise;public class MainActivity extends AppCompatActivity{    private TextView mTextView;    private class MyReceiver extends BroadcastReceiver    {        private MyReceiver(){}        @Override        public void onReceive(Context context, Intent intent)        {            if(intent != null)            {                //这里处理Intent                String action = intent.getAction();                if("自定义动作".equals(action))                    mTextView.setText("收到Broadcast");            }        }    }    private BroadcastReceiver myReceiver;    private IntentFilter myIntentFilter;    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTextView = (TextView) findViewById(R.id.textView);        myReceiver = new MyReceiver();    }    @Override    protected void onResume()    {        super.onResume();        //实例化一个过滤器        myIntentFilter = new IntentFilter("自定义动作");        //注册监听器        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, myIntentFilter);        //发送任务        Intent action1 = new Intent(MainActivity.this,MyIntentService.class);        action1.setAction("自定义动作");        startService(action1);    }    //需要在activity退出的时候解绑Receiver    @Override    protected void onPause()    {        super.onPause();        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);    }}

整个后台任务处理的过程分为三步:
一、UI线程发送Intent到IntentService
二、IntentService接收到Intent,处理完任务,发送广播
三、UI线程中注册的监听器监听到IntentService发送的广播,更新UI

0 0