Android studio中广播的用法

目录

1、动态方法:

2、静态注册广播

3、发送和接收自定义广播

4、跨程序接收广播


广播有两种,静态广播和动态广播。

1、动态方法:

重写广播接收器,用来接受广播,并根据接受到的广播进行操作。可以在上下文中重写,或者重写在一个新的文件中。

class NetworkChangeReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if(networkInfo!=null && networkInfo.isAvailable())
            {
                Toast.makeText(context,"Network is available",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context,"Network is unavailable!",Toast.LENGTH_SHORT).show();
            }

        }
    }

定义一些将要用到的参数:

private IntentFilter intentFilter;

private NetworkChangeReceiver networkChangeReceiver;

在onCreate中注册广播:

//新建一个IntentFilter实例,并添加一个action
//当网络发生变化时,系统发出的正是android.net.conn.CONNECTIVITY_CHANGE的一条广播,如果需要监听别的广播,就添加相应的action
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);

在AndroidManifest.xml文件中声明许可:

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

在OnDestroy中取消注册:

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
        //注意:动态注册的广播接收器一定要取消注册。
        unregisterReceiver(myBroadcastReceiver);
    }

2、静态注册广播

静态注册可以让程序在未启动的情况下就能接收到广播。通过如图所示的方法静态注册。

 之后会跳转到如图所示的界面,给广播接收器取一个名字,点击finish即可。这里取得名字是

BootCompleteReceiver

 修改相应代码即可实现接收到相应的广播后实现相应的功能。

package com.example.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
//        throw new UnsupportedOperationException("Not yet implemented");
        Toast.makeText(context,"Boot Complete",Toast.LENGTH_LONG).show();
    }
}

注意:静态的广播接收器一定要在AndroidManifest.xml文件中注册才可以使用:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcasttest">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <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/Theme.BroadcastTest">
        <receiver
            android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这样就可以接收开机广播了。

注意:如果您的应用以 API 级别 26 或更高级别的平台版本为目标,则不能使用清单为隐式广播(没有明确针对您的应用的广播)声明接收器,但一些不受此限制的隐式广播除外。在大多数情况下,您可以使用调度作业来代替。

3、发送和接收自定义广播

先定义一个广播接收器用来接收自定义的广播:

package com.example.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver 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(context,"Received in mybroadcastReceiver",Toast.LENGTH_LONG).show();
    }
}

在AndroidManifest.xml文件中注册该自定义广播

       <receiver
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>

创建一个按钮用于发送广播

    <Button
        android:id="@+id/send_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send Broadcast"
        tools:ignore="MissingConstraints" />

给按钮添加监听

    //button
        //点击按钮,发送广播
        Button button = (Button) findViewById(R.id.send_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
//                Toast.makeText(MainActivity.this,"the Broadcast has been sent",Toast.LENGTH_SHORT).show();

            }
        });

在OnCreate中接收广播:

        //监听自己发送的广播
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("com.example.broadcasttest.MY_BROADCAST");
        myBroadcastReceiver = new MyBroadcastReceiver();
        registerReceiver(myBroadcastReceiver,myIntentFilter);

4、跨程序接收广播

广播是一种可以跨进程的通讯方式,在一个应用程序发出的广播,其他的应用程序也是可以收到的。

在另一个项目中定义一个广播接收器并注册:

package com.example.broadcasttest2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AnotherBroadcastReceiver 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(context,"Received in AnotherbroadcastReceiver",Toast.LENGTH_LONG).show();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcasttest2">

    <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/Theme.BroadcastTest2">
        <receiver
            android:name=".AnotherBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

并在OnCreate中接收该广播

package com.example.broadcasttest2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private AnotherBroadcastReceiver anotherBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //监听自己发送的广播
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("com.example.broadcasttest.MY_BROADCAST");
        anotherBroadcastReceiver = new AnotherBroadcastReceiver();
        registerReceiver(anotherBroadcastReceiver,myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(anotherBroadcastReceiver);
    }
}

之后,我们打开第一个程序,点击按钮发送广播,屏幕上会先出现第一个程序接收到广播的提示,之后会弹出第二个程序接收到广播的提示。

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值