GVKun编程网logo

Android移动应用开发之广播接收者(android移动应用开发之广播接收者是什么)

12

针对Android移动应用开发之广播接收者和android移动应用开发之广播接收者是什么这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展android–C2DM广播接收器、android–从

针对Android移动应用开发之广播接收者android移动应用开发之广播接收者是什么这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展android – C2DM广播接收器、android – 从广播接收器关闭应用程序、android – 将广播接收器限制为应用程序、android – 广播接收器中接收呼叫的优先级等相关知识,希望可以帮助到你。

本文目录一览:

Android移动应用开发之广播接收者(android移动应用开发之广播接收者是什么)

Android移动应用开发之广播接收者(android移动应用开发之广播接收者是什么)

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

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


一、广播接收者简介

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

二、广播接收者入门

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);
    }
}

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>

在这里插入图片描述

三、自定义广播

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

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

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>

点击按钮可以看到:

在这里插入图片描述

在这里插入图片描述

四、广播的类型

1、有序广播和无序广播

(1)有序广播

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

(2)无序广播

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

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 – C2DM广播接收器

android – C2DM广播接收器

我有一个有效的C2DM应用程序.
我在创建新的C2DM应用程序时重用了相同的包名称.

它的工作原理除外,当应用程序未运行时,不会调用broadcastReceiver.也就是说,如果我运行应用程序并向其发送C2DM消息,则一切正常.但是在强制退出后,不再调用broadcastReceiver.

我查看了很多例子,并将旧清单中的所有内容与新清单进行了比较.特别注意类别中使用的包名,意图服务等.

问题:是否存在常见的C2DM编码/配置错误导致应用程序强制退出后未调用broadcastReceiver?

强制退出应用程序后,当我发送C2DM消息时,我确实得到了这个日志:

01-11 00:54:43.580:WARN / GTalkService(286):[DataMsgMgr]广播意图回调:result = CANCELED forIntent {act = com.google.android.c2dm.intent.RECEIVE cat = [com.aawwpcd.pcd3] (有额外的)}

我强制退出应用程序后,为每个发送到设备的C2DM消息获取其中一个消息.

它似乎意图进入,但没有传递给我的broadcastReceiver.

编辑:

以下是Manifest和broadcastReceiver的相关位:

broadcastReciever

package com.aawwpcd.pcd3.c2dm;

import ...

public class C2DMbroadcastReceiver extends broadcastReceiver {

    @Override
    public IBinder peekService(Context myContext,Intent service) {
        return super.peekService(myContext,service);
    }

    public C2DMbroadcastReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context,Intent intent) {

    ...

    }

}

表现

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.aawwpcd.pcd3"
      android:versionCode="250"
      android:versionName="ICSPCD3">

<uses-sdk android:minSdkVersion="13"
          android:targetSdkVersion="14"/>

<permission android:name="com.aawwpcd.pcd3.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
<uses-permission android:name="com.aawwpcd.pcd3.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application android:name=".PCD3Application"
             android:label="@string/app_name"
             android:icon="@drawable/pcdlauncher"
             android:theme="@android:style/Theme.Holo">

    <activity android:name=".honeycombpcd3.FullScheduleActivity"
              android:label="@string/app_namefull"
            >

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>

    </activity>

    <!-- Only C2DM servers can send messages for the app. If permission is not
    set - any other app can generate it -->
    <receiver android:name=".c2dm.C2DMbroadcastReceiver"
              android:permission="com.google.android.c2dm.permission.SEND">

        <!-- Receive the actual message -->
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            <category android:name="com.aawwpcd.pcd3"/>
        </intent-filter>

        <!-- Receive the registration id -->
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
            <category android:name="com.aawwpcd.pcd3"/>
        </intent-filter>

    </receiver>

</application>

</manifest>

编辑:这可能是3.x中的新功能吗?如上所述,我的问题始于这个新的应用程序 – 为3.x编写.我想要的是C2DM甚至在应用程序没有运行时调用broadcastReceiver.我没有看到.这可能是3.x的变化吗?它之前在2.3.x手机上工作过,我找不到任何我正在做的事情.编写测试代码来证明这一点将是一件麻烦事,但我认为这是下一步.

编辑:
似乎与Force Quit有关.当我重新安装.apk然后向设备发送c2dm消息时,我没有任何问题;广播接收器拿起它.在这种情况下,当C2DM进入时,应用程序尚未运行,但一切都按预期工作.我唯一的问题是在我强制退出应用程序之后.之后的C2DM消息不被broadcastReceiver拾取.

解决方法

看一下
https://stackoverflow.com/a/7108611

并在Android 3.1发行说明http://developer.android.com/about/versions/android-3.1.html#launchcontrols

截至3.1,默认情况下,强制停止的应用程序不再由C2DM重新启动.在强制关闭后请求重新启动有一个新标志.

android – 从广播接收器关闭应用程序

android – 从广播接收器关闭应用程序

我是 android编程的新手.
我已经尝试在活动中注册广播接收器,但我的接收器在应用程序onPause时无法正常工作.
所以我发现我需要在清单中注册我的接收器.

我的目标是在用户关闭Wifi后关闭我的应用程序一段时间.

这是我的代码但不起作用.

public class ReceiverWifi extends broadcastReceiver {

    @Override
    public void onReceive(Context context,Intent intent) {

        Handler handler = new Handler();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                MainActivity m = new MainActivity();
                m.finish();

            }
        };

        if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {

            int newWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.WIFI_STATE_UNKNowN);

            switch (newWifiState) {

            case WifiManager.WIFI_STATE_disABLED:

                Toast.makeText(context,"Wi-fi disconnected ",Toast.LENGTH_SHORT).show();

                handler.postDelayed(runnable,15 * 1000);
                break;

            }
        }

    }
}

我的清单:

<receiver android:name="com.example.wifimonitor.ReceiverWifi" >
    <intent-filter>
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

我如何实现目标?

解决方法

您的广播接收器是否在主要活动类中?如果是这样,您可以保存应用程序的全局上下文,稍后在广播接收器中关闭它.

如果它位于服务或提供商上,只需在启动/注册时向其发送应用实例.然后从该实例调用finish().

编辑:

试试这个:

在您的主要活动中创建此公共方法:

public static void closeActivity(){
        finish();
   }

然后在你的广播接收器中调用这个方法,如:

MainActivity.closeActivity();

希望能帮助到你

总结

以上是小编为你收集整理的android – 从广播接收器关闭应用程序全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

android – 将广播接收器限制为应用程序

android – 将广播接收器限制为应用程序

我正在研究广播接收器并遇到问题.

我在Manifest文件中收到一个广播接收器.

<receiverandroid:name=".MyClass">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
    </receiver>

这工作正常,只要连接发生变化,它就会调用MyClass.

现在问题是每当我的应用程序没有运行时,这个类将接收广播接收器.我希望它在应用程序运行时接收.

我尝试通过扩展broadcastReceiver在该类文件中注册和取消注册广播来实现它.但我想通过Manifest文件实现相同的目标.

如果在没有打开应用程序时没有收到任何内容,我的问题就会解决.

解决方法:

你在说什么是不可能的.在清单中使用intent过滤器的整个目的是能够接收您的应用程序是否正在运行的意图.通过从代码[registerReceiver]注册/取消注册接收器来实现您想要的唯一方法

android – 广播接收器中接收呼叫的优先级

android – 广播接收器中接收呼叫的优先级

我的目的是制作一个广播接收器,在接收呼叫时执行动作.是否有可能比自动呼叫接收SO?更优先.

我已经尝试分配2147483647的优先级,我认为这是最好的,但仍然会跳到我接收器结束前尝试呼叫.

<!-- Receiver de llamadas -->
<receiver android:name=".PhoneCall">
    <intent-filter android:priority="2147483647">
        <action android:name="android.intent.action.PHONE_STATE"/>   
    </intent-filter>
</receiver>

解决方法:

这个链接回答我:

http://developer.android.com/reference/android/content/BroadcastReceiver.html

可以接收两种主要类型的广播:

  • normal broadcasts (sent with Context.sendbroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined
    order, often at the same time. This is more efficient, but means that
    receivers cannot use the result or abort APIs included here.

  • Ordered broadcasts (sent with Context.sendOrderedbroadcast) are delivered to one receiver at a time. As each receiver executes in
    turn, it can propagate a result to the next receiver, or it can
    completely abort the broadcast so that it won’t be passed to other
    receivers. The order receivers run in can be controlled with the
    android:priority attribute of the matching intent-filter; receivers
    with the same priority will be run in an arbitrary order.

像PHONE_STATE这样的广播是“普通广播”.据我所知,不可能优先考虑我的广播.有没有人想到任何方式?

关于Android移动应用开发之广播接收者android移动应用开发之广播接收者是什么的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android – C2DM广播接收器、android – 从广播接收器关闭应用程序、android – 将广播接收器限制为应用程序、android – 广播接收器中接收呼叫的优先级等相关知识的信息别忘了在本站进行查找喔。

本文标签: