Android移动应用开发之广播接收者

Android移动应用开发之广播接收者,第1张

概述Android移动应用开发广播接收者一、广播接收者简介二、广播接收者入门1、广播接收者的创建2、实战演练:电话拦截三、自定义广播1、自定义广播的发送与接收2、实战演练:自定义广播四、广播的类型1、有序广播和无序广播(1)有序广播(2)无序广播2、实战演练:拦截有序广播一

AndroID移动应用开发之广播接收者一、广播接收者简介二、广播接收者入门1、广播接收者的创建2、实战演练:电话拦截三、自定义广播1、自定义广播的发送与接收2、实战演练:自定义广播四、广播的类型1、有序广播和无序广播(1)有序广播(2)无序广播2、实战演练:拦截有序广播


一、广播接收者简介

在AndroID中内置了很多广播,例如手机开机后会发送一条广播,电量不足时会发送一条广播,AndroID提供了一个broadcastReceiver组件,该组件可以监听来自系统或者应用程序的广播,只需要创建一个类继承自broadcastReceiver类,重写onReceive方法并在方法中处理广播事件即可。

二、广播接收者入门@H_502_59@1、广播接收者的创建

点击包,右键



创建完成后,AndroIDManifest.xml如下:

package edu.hzuapps.myapplication;import androIDx.appcompat.app.AppCompatActivity;import androID.content.IntentFilter;import androID.os.Bundle;public class MainActivity extends AppCompatActivity {    MyReceiver myReceiver;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //实例化广播接收者                myReceiver = new MyReceiver();        //实例化过滤器并设置要过滤的广播        String action = "androID.provIDer.Telephony.SMS_RECEIVED";        IntentFilter intentFilter = new IntentFilter(action);        //注册广播        registerReceiver(myReceiver, intentFilter);    }    protected voID OnDestroy() {        super.onDestroy();        //当Activit销毁时取消注册broadcastReceiver        unregisterReceiver(myReceiver);    }}
@H_502_59@2、实战演练:电话拦截

用户界面activity_main.xml:

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:tools="http://schemas.androID.com/tools"    androID:background="@drawable/bg"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    tools:context=".MainActivity">    <EditText        androID:ID="@+ID/et_phone"        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:paddingtop="200dp"        androID:textSize="20sp"        androID:hint="请输入拦截号码" />    <button        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_below="@ID/et_phone"        androID:layout_centerHorizontal="true"        androID:background="#ACD6FF"        androID:onClick="click"        androID:paddingleft="5dp"        androID:paddingRight="5dp"        androID:text="保存拦截号码"        androID:textSize="16sp" /></relativeLayout>


交互界面MainActivity.java:

package edu.hzuapps.interceptcall;import androIDx.appcompat.app.AppCompatActivity;import androID.content.SharedPreferences;import androID.os.Bundle;import androID.vIEw.VIEw;import androID.Widget.EditText;import androID.Widget.Toast;public class MainActivity extends AppCompatActivity {    private EditText editText;    private SharedPreferences sharedPreferences;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        editText = (EditText) findVIEwByID(R.ID.et_phone);        //创建SharedPreferences对象来将要拦截的号码保存        sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);    }    public voID click(VIEw vIEw) {        //获取用户输入的拦截号码        String phone = editText.getText().toString().trim();        //创建Editor对象保存号码        SharedPreferences.Editor editor = sharedPreferences.edit();        editor.putString("phone", phone);        editor.commit();        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();    }}

监听广播界面Outcallreceiver.java:

package edu.hzuapps.interceptcall;import androID.content.broadcastReceiver;import androID.content.Context;import androID.content.Intent;import androID.content.SharedPreferences;public class Outcallreceiver extends broadcastReceiver {    @OverrIDe    public voID onReceive(Context context, Intent intent) {        //获取当前电话号码        String outcalphone = getResultData();        //创建SharedPreferences对象获取拦截号码        SharedPreferences sharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);        String phone = sharedPreferences.getString("phone", "");        if (outcalphone.equals(phone)) {            //拦截电话            setResultData(null);        }    }}

由于外拨电话涉及权限问题,因此AndroIDManifest.xml:

<?xml version="1.0" enCoding="utf-8"?><manifest xmlns:androID="http://schemas.androID.com/apk/res/androID"    package="edu.hzuapps.interceptcall">    <application        androID:allowBackup="true"        androID:icon="@mipmap/ic_launcher"        androID:label="@string/app_name"        androID:roundIcon="@mipmap/ic_launcher_round"        androID:supportsRtl="true"        androID:theme="@style/Apptheme">        <!--注册广播接收者-->        <receiver androID:name=".Outcallreceiver">            <intent-filter>                <action androID:name="androID.intent.action.NEW_OUTGOING_CALL"/>            </intent-filter>        </receiver>        <activity androID:name=".MainActivity">            <intent-filter>                <action androID:name="androID.intent.action.MAIN" />                <category androID:name="androID.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <!--设置权限-->    <uses-permission androID:name="androID.permission.PROCESS_OUTGOING_CALLS"/></manifest>

三、自定义广播@H_502_59@1、自定义广播的发送与接收

当自定义广播发送消息时,会存储到公共消息区中,而公共消息区中如果存在对应的广播接收者就会及时接收到这条信息。

@H_502_59@2、实战演练:自定义广播

activity_main.xml:

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:app="http://schemas.androID.com/apk/res-auto"    xmlns:tools="http://schemas.androID.com/tools"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    tools:context=".MainActivity">    <button        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_centerHorizontal="true"        androID:onClick="send"        androID:layout_margintop="50dp"        androID:text="发送求救广播"        androID:paddingleft="5dp"        androID:paddingRight="5dp"        androID:background="#FFD2D2"        androID:textSize="20sp" /></relativeLayout>

MainActivity.java:

package edu.hzuapps.forhelp;import androIDx.appcompat.app.AppCompatActivity;import androID.content.Intent;import androID.os.Bundle;import androID.vIEw.VIEw;public class MainActivity extends AppCompatActivity {    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);    }    public voID send(VIEw vIEw) {        Intent intent = new Intent();        //定义广播类型        intent.setAction("Custom_broadcast");        //发送广播        sendbroadcast(intent);    }}

MybroadcastReceiver.java:

package edu.hzuapps.forhelp;import androID.content.broadcastReceiver;import androID.content.Context;import androID.content.Intent;import androID.util.Log;public class MybroadcastReceiver extends broadcastReceiver {    @OverrIDe    public voID onReceive(Context context, Intent intent) {        Log.i("MybroadcastReceiver", "自定义的广播接收者,接收到了广播事件");        Log.i("MybroadcastReceiver", intent.getAction());    }}

AndroIDMainfest.xml:

<receiver androID:name=".MybroadcastReceiver">	<intent-filter>		<action androID:name="Custom_broadcast" />	</intent-filter></receiver>

点击按钮可以看到:

四、广播的类型@H_502_59@1、有序广播和无序广播(1)有序广播

无序广播是完全异步执行的,所有监听该广播的广播接收者都会受到该消息,但顺序不确定,效率较高,但无法拦截。

(2)无序广播

有序广播按照优先级被依次接受,且每次只有一个接收者几首,可被拦截。

@H_502_59@2、实战演练:拦截有序广播

activity_main.xml:

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:tools="http://schemas.androID.com/tools"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    tools:context=".MainActivity">    <button        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_centerHorizontal="true"        androID:layout_margintop="80dp"        androID:onClick="send"        androID:text="发送有序广播"        androID:paddingleft="5dp"        androID:paddingRight="5dp"        androID:background="#FBFBFF"        androID:textSize="20sp" /></relativeLayout>

MainActivity.java:

package edu.hzuapps.orderedbroadcast;import androIDx.appcompat.app.AppCompatActivity;import androID.content.Intent;import androID.os.Bundle;import androID.vIEw.VIEw;public class MainActivity extends AppCompatActivity {    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);    }    public voID send(VIEw vIEw) {        Intent intent = new Intent();        //定义广播事件类型        intent.setAction("Intercept_broadcast");        //发送广播,null表示不指明权限        sendOrderedbroadcast(intent, null);    }}

MybroadcastReceiverOne.java:

package edu.hzuapps.orderedbroadcast;import androID.content.broadcastReceiver;import androID.content.Context;import androID.content.Intent;import androID.util.Log;public class MybroadcastReceiverOne extends broadcastReceiver {    @OverrIDe    public voID onReceive(Context context, Intent intent) {        Log.i("MybroadcastReceiverOne", "有序广播接收者One,接收到了广播事件");    }}

MybroadcastReceiverTwo.java:

package edu.hzuapps.orderedbroadcast;import androID.content.broadcastReceiver;import androID.content.Context;import androID.content.Intent;import androID.util.Log;public class MybroadcastReceiverTwo extends broadcastReceiver {    @OverrIDe    public voID onReceive(Context context, Intent intent) {        Log.i("MybroadcastReceiverTwo", "有序广播接收者Two,接收到了广播事件");    }}

MybroadcastReceiverThree.java:

package edu.hzuapps.orderedbroadcast;import androID.content.broadcastReceiver;import androID.content.Context;import androID.content.Intent;import androID.util.Log;public class MybroadcastReceiverThree extends broadcastReceiver {    @OverrIDe    public voID onReceive(Context context, Intent intent) {        Log.i("MybroadcastReceiverThr", "有序广播接收者Three,接收到了广播事件");    }}

AndroIDMainfest.xml:

<receiver androID:name=".MybroadcastReceiverOne">    <intent-filter androID:priority="1000">        <action androID:name="Intercept_broadcast" />    </intent-filter></receiver><receiver androID:name=".MybroadcastReceiverTwo">    <intent-filter androID:priority="200">        <action androID:name="Intercept_broadcast" />    </intent-filter></receiver><receiver androID:name=".MybroadcastReceiverThree">    <intent-filter androID:priority="600">        <action androID:name="Intercept_broadcast" />    </intent-filter></receiver>



假设要保证有一个接收者必须接收到广播(无论优先级高低),可使用sendOrderedbroadcast
在MybroadcastReceiverOne中添加拦截者:

        abortbroadcast();        Log.i("MybroadcastReceiverOne", "广播已在此处被拦截");


在MainActivity.java中要求Two必须收到广播:

MybroadcastReceiverTwo receiverTwo = new MybroadcastReceiverTwo();sendOrderedbroadcast(intent, null, receiverTwo, null, 0 ,null, null);

总结

以上是内存溢出为你收集整理的Android移动应用开发之广播接收者全部内容,希望文章能够帮你解决Android移动应用开发之广播接收者所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1054538.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存