android中对broadcast广播的利用

    xiaoxiao2021-12-10  18

    开发中大家常常忽略对广播的应用开发,如果在app中合适的地方使用会让我们的app更加高效方便,下面介绍自己调试的案例

    1、种类:按照使用方式和应用特性可以把其分成两种(1)动态注册方式(2)xml静态注册方式,这两者的区别是前者消息的传播范围仅仅局限于线程内即本app内部,后者则能和外部交流。

    2、使用方法:

    动态方法:可以设计三个按钮,注册按钮、发送按钮、取消广播按钮

             注册按钮:@Override public void onClick(View arg0) { re=new ReceiceBroadCast();//下面有定义方法继承了broadcastreceive这个系统方法 IntentFilter filert=new IntentFilter(); filert.addAction("dhj");//自定义action名字但是要和发送时用到的action名字保持一致才行 registerReceiver(re, filert); }

                 这个是上面用到的接收类

                public class ReceiveBroadCast extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { // 一旦执行接收就执行这个方法 String st=arg1.getStringExtra("data"); Toast.makeText(MainActivity.this, st, Toast.LENGTH_LONG).show();           }           }

                     发送按钮内的事件:

                                    Intent fi=new Intent(); fi.setAction("dhj"); fi.putExtra("msg", "dhjddddd"); sendBroadcast(fi);

                  取消按钮的事件:

                                   unregisterReceiver(re);

                 完成上面就能实现发送广播了

    静态注册方法:实现启动另一个app利用广播

                     定义一个接收广播类,跟上一个区别是这个必须单独出来不能像上面的是在类内定义的

                public class ReceiceBroadCastByXml extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { String st=arg1.getStringExtra("msg"); Toast.makeText(arg0, st, Toast.LENGTH_LONG).show(); Intent intent=new Intent(); intent.setClass(arg0, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//没有这个设置启动本app会报错闪退 arg0.startActivity(intent); } }

    那么本app的配置文件怎么写呢:

     <receiver android:name="com.example.broadcast1.ReceiceBroadCastByXml">            <intent-filter>                <action android:name="com.example.broadcast1.dhj"/>            </intent-filter>        </receiver>

    需要解释一下,receive的android:name是上面接收方法的路径,action android:name是自定义的,只要发送广播时也用同样内容即可

    另一个app要启动本app,就要发送广播了

    Intent fi=new Intent(); fi.setAction("com.example.broadcast1.dhj"); fi.putExtra("msg", "dhjddddd"); sendBroadcast(fi);

    就这么多,也花了一段时间才弄清这些

    转载请注明原文地址: https://ju.6miu.com/read-700399.html

    最新回复(0)