打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用IntentService与BroadcastReceiver实现后台服务(Android7.0可用)

IntentService的优点

IntentService会创建单独的线程处理所有的Intent请求,会处理onHandleIntent方法实现的代码,隐藏开发者无须处理多线程问题,当所有请求处理完成后,IntentService会自动停止

Action的使用

Action其实就是一个字符串,可以起到一个标识的作用

BroadcastReceiver的使用

BroadcastReceiver本质是一个监听器,有自己的进程重写onReceive方法即可,但是在该方法里面不要执行耗时的操作,否则会ANR发送    创建Intent    设置Action    putExtra    send发送接收    实现onReceive方法在AndroidManifest内增加配置BroadcastReceiver其他    开机自动运行的Service

第一步

动态注册广播broadcastReceiver = new MyReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction("com.example.space.text2.action.MSGTEXT");//这个Action的作用是当发送为该Action的广播时,该MyReceiver类的onReceive方法将会接收到并处理    registerReceiver(broadcastReceiver,intentFilter);

第二步

在Activity中添加一个UI组件,比如按钮为按钮添加监听器在该监听器内启动IntentServiceIntent  intent = new Intent(FinsihActivity.this,TextIntentService.class);               intent.setAction("com.example.space.text2.action.MSGFINSIH");//设置该Action以便IntentService接收到Intent,判断是哪个Action,如果是这个Action话,就进行相应处理intent.putExtra("finish","这是finishactivity发送的消息");FinsihActivity.this.startService(intent);

第三步

添加一个IntentService.java类,可以使用Android Studio的自动生成注释掉没有用的代码但是一定要保留protected void onHandleIntent(Intent intent) 和    public TextIntentService() {        super("TextIntentService");    }方法在protected void onHandleIntent(Intent intent) 方法中进行后台任务的处理即可    protected void onHandleIntent(Intent intent) {        if (intent != null) {            final String action = intent.getAction();            if (ACTION_MSGFINSIH.equals(action)) {                String param1 = intent.getStringExtra("finish");                Intent intent1 = new Intent(ACTION_MSGTEXT);        //此处ACTION_MSGTEXT等于"com.example.space.text2.action.MSGTEXT",         生成包含该Action的Intent后,就可以使用sendBroadcast发送广播了,         之后自己定义的MyReceiver类的onReceive方法将会接收到并处理                intent1.putExtra("msg",param1+",IntentService收到并且广播了出去");                sendBroadcast(intent1);            }        }    }

第四步

在自己定义的MyReceiver类的onReceive方法将会接收到并处理收到的intent 这个自己定义的MyReceiver类最好以内部类的形式写在使用该广播的Activity中, 这样就可以使用该Activity的UI组件了,     即可实现把后台服务进程中的数据更新在UI线程中的UI组件中    //内部类    public class MyReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {         // TODO: This method is called when the BroadcastReceiver is receiving            // an Intent broadcast.         Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"),                 Toast.LENGTH_SHORT).show();            //throw new UnsupportedOperationException("Not yet implemented");            //注意,该句是自动生成的,                 一定要注释掉,否则程序会崩溃重启,                    无法显示出后台服务通过广播改变前台UI的效果        }    }

完整代码

第一个是Activity

public class FinsihActivity extends AppCompatActivity {BroadcastReceiver broadcastReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_finsih);    //第一步:注册广播,绑定广播和action    try    {        broadcastReceiver = new MyReceiver();        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction("com.example.space.text2.action.MSGTEXT");        registerReceiver(broadcastReceiver,intentFilter);        Log.i("mss","registerReceiver(broadcastReceiver,intentFilter);");    }    catch (ParcelFormatException e)    {        Log.i("mss","catch");    }    Button button = (Button)super.findViewById(R.id.button2);    button.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            //第二步:开始IntentService            try            {                Intent  intent = new Intent(FinsihActivity.this,TextIntentService.class);                Log.i("mss","Intent  intent = new Intent(FinsihActivity.this,TextIntentService.class)");                intent.setAction("com.example.space.text2.action.MSGFINSIH");                intent.putExtra("finish","这是finishactivity发送的消息");                FinsihActivity.this.startService(intent);                Log.i("mss","FinsihActivity.this.startService(intent);");                Toast.makeText(getApplicationContext(), "startService(intent)", Toast.LENGTH_SHORT).show();            }            catch(ParcelFormatException e)            {                Log.i("mss","catch");            }        }    });}//内部类public class MyReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        // TODO: This method is called when the BroadcastReceiver is receiving        // an Intent broadcast.                //        Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();//                    TextView textView = (TextView)FinsihActivity.super.findViewById(R.id.textView13);//                    textView.setText(""+intent.getStringExtra("msg"));        //throw new UnsupportedOperationException("Not yet implemented");    }}}

第二个是IntentService

public class TextIntentService extends IntentService {// TODO: Rename actions, choose action names that describe tasks that this// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMSprivate static final String ACTION_MSGTEXT = "com.example.space.text2.action.MSGTEXT";private static final String ACTION_MSGFINSIH = "com.example.space.text2.action.MSGFINSIH";private static final String ACTION_BAZ = "com.example.space.text2.action.BAZ";// TODO: Rename parameterspublic TextIntentService() {    super("TextIntentService");}//    /**//     * Starts this service to perform action Foo with the given parameters. If//     * the service is already performing a task this action will be queued.//     *//     * @see IntentService//     *///    // TODO: Customize helper method//    public static void startActionFoo(Context context, String param1, String param2) {//        Intent intent = new Intent(context, TextIntentService.class);//        intent.setAction(ACTION_MSGTEXT);//        intent.putExtra(EXTRA_PARAM1, param1);//        intent.putExtra(EXTRA_PARAM2, param2);//        context.startService(intent);//    }////    /**//     * Starts this service to perform action Baz with the given parameters. If//     * the service is already performing a task this action will be queued.//     *//     * @see IntentService//     *///    // TODO: Customize helper method//    public static void startActionBaz(Context context, String param1, String param2) {//        Intent intent = new Intent(context, TextIntentService.class);//        intent.setAction(ACTION_BAZ);//        intent.putExtra(EXTRA_PARAM1, param1);//        intent.putExtra(EXTRA_PARAM2, param2);//        context.startService(intent);//    }@Overrideprotected void onHandleIntent(Intent intent) {    Log.i("mss","onHandleIntent");    if (intent != null) {        final String action = intent.getAction();        if (ACTION_MSGFINSIH.equals(action)) {            Log.i("mss","ACTION_MSGFINSIH.equals(action)");            String param1 = intent.getStringExtra("finish");            Log.i("mss","intent.getStringExtra(\"finish\") = "+param1);            Intent intent1 = new Intent(ACTION_MSGTEXT);            Log.i("mss","Intent intent1 = new Intent(ACTION_MSGTEXT);");            Log.i("mss",ACTION_MSGTEXT);            intent1.putExtra("msg",param1+",IntentService收到并且广播了出去");            Log.i("mss","intent1.putExtra(\"msg\",param1+\",IntentService收到并且广播了出去\");");            sendBroadcast(intent1);            Log.i("mss","super.sendBroadcast(intent1);");        }    }}//    /**//     * Handle action Foo in the provided background thread with the provided//     * parameters.//     *///    private void handleActionFoo(String param1, String param2) {//        // TODO: Handle action Foo//        throw new UnsupportedOperationException("Not yet implemented");//    }//    private void handleActionFinish(String param1, String param2) {//        // TODO: Handle action Foo//        throw new UnsupportedOperationException("Not yet implemented");//    }//    /**//     * Handle action Baz in the provided background thread with the provided//     * parameters.//     *///    private void handleActionBaz(String param1, String param2) {//        // TODO: Handle action Baz//        throw new UnsupportedOperationException("Not yet implemented");//    }}

第三个是AndroidManifest

<service            android:name=".TextIntentService"            android:exported="false"></service>其中exported="false"的意思是防止其他应用访问该Service
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android提高第十二篇之蓝牙传感应用
Android软件的自动更新
什么是intent?
Android BroadcastReceiver 简介 - 蔚蓝天空 探索无限 - Ja...
关于android语言切换后通知栏显示的问题
android蓝牙开发 蓝牙设备的查找和连接
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服