前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >发送自定义广播

发送自定义广播

作者头像
Dream城堡
发布2018-12-17 10:52:22
6020
发布2018-12-17 10:52:22
举报
文章被收录于专栏:Spring相关

发送自定义广播

1.发送标准广播

新建一个MyBroadcastReceiver:

代码语言:javascript
复制
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) {
        
        String kl = intent.getStringExtra("kl");
        Toast.makeText(context,"接收到信息:"+kl,Toast.LENGTH_LONG).show();
    }
}

修改AndroidManifest.xml:

代码语言:javascript
复制
<?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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <!--监听<action android:name="com.example.broadcasttest.MY_BROADCAST" />-->
        <!--会接受到所有发往这里的信息-->
        <receiver
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

修改activity_main.xml:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.broadcasttest.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送消息"
        />

</android.support.constraint.ConstraintLayout>

修改MainActivity:

代码语言:javascript
复制
package com.example.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private IntentFilter  intentFilter;

    private NetworkChangeReceive networkChangeReceive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        "com.example.broadcasttest.MY_BROADCAST"
                );
                intent.putExtra("kl","发消息");
                sendBroadcast(intent);

            }
        });


        intentFilter = new IntentFilter();
        intentFilter.addAction("网络改变");
        networkChangeReceive = new NetworkChangeReceive();
        registerReceiver(networkChangeReceive,intentFilter);

        Toast.makeText(this.getBaseContext(),"开始了啊",
                Toast.LENGTH_SHORT
        ).show();

    }

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


    class  NetworkChangeReceive 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 可用",
                        Toast.LENGTH_SHORT
                ).show();
                Log.d(TAG, "onReceive:可用 ");
            }else {

                Toast.makeText(context,"network is 不能用",
                        Toast.LENGTH_SHORT
                ).show();

                Log.d(TAG, "onReceive:不能用 ");

            }
        }

            }

}
2.发送有序广播

首先我们先建立一个BroadcastTest2的项目,如下:

新建一个AnotherBroadcastReceiver:

代码语言:javascript
复制
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) {
        Toast.makeText(context,"another接收的信息:"+intent.getStringExtra("kl"),
                Toast.LENGTH_LONG).show();
    }

}

修改AndroidManifest.xml:

代码语言:javascript
复制
<?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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

</manifest>

这时候启动两个程序,都可以接收到按钮发出的消息,这时候还是标准广播,如果要改为有序广播需要在BroadcastTest项目点击事件中更改:

代码语言:javascript
复制
sendBroadcast(intent,null);
有序广播的截断

修改AndroidManifest.xml:

代码语言:javascript
复制
<?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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <!--监听<action android:name="com.example.broadcasttest.MY_BROADCAST" />-->
        <!--会接受到所有发往这里的信息-->
        <!--android:priority="100" 设置了优先级 会优先接收有序广播的消息-->
        <receiver
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">

            <intent-filter android:priority="100">
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>

        </receiver>
    </application>

</manifest>

在MyBroadcastReceiver中截断广播:

代码语言:javascript
复制
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) {
       
        Toast.makeText(context,"接收到信息:",Toast.LENGTH_LONG).show();

        //截断有序广播
        abortBroadcast();
    }
}
3.使用本地广播

修改 BroadcastTest的MainActivity:

代码语言:javascript
复制
package com.example.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private IntentFilter  intentFilter;

    private LocalReceiver localReceiver;

    private LocalBroadcastManager localBroadcastManager;



    private NetworkChangeReceive networkChangeReceive;

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

        //接收本地的广播
        localBroadcastManager = LocalBroadcastManager.getInstance(this);





        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(
//                        "com.example.broadcasttest.MY_BROADCAST"
//                );
                Intent intent = new Intent(
                        "com.example.broadcasttest.LOCAL_BROADCAST"
                );
//                intent.putExtra("kl","发消息");
//                sendBroadcast(intent,null);

                //发送本地广播
                localBroadcastManager.sendBroadcast(intent);
            }
        });


        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");

        localReceiver = new LocalReceiver();

        localBroadcastManager.registerReceiver(localReceiver,intentFilter);




        intentFilter.addAction("网络改变");
        networkChangeReceive = new NetworkChangeReceive();
        registerReceiver(networkChangeReceive,intentFilter);

        Toast.makeText(this.getBaseContext(),"开始了啊",
                Toast.LENGTH_SHORT
        ).show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
        unregisterReceiver(networkChangeReceive);
    }


    class  NetworkChangeReceive 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 可用",
                        Toast.LENGTH_SHORT
                ).show();
                Log.d(TAG, "onReceive:可用 ");
            }else {

                Toast.makeText(context,"network is 不能用",
                        Toast.LENGTH_SHORT
                ).show();

                Log.d(TAG, "onReceive:不能用 ");

            }
        }


            }


            class LocalReceiver extends  BroadcastReceiver{

                @Override
                public void onReceive(Context context, Intent intent) {
                    Toast.makeText(context,"收到本地的消息",
                            Toast.LENGTH_LONG
                            ).show();


                }
            }




}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.11.23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 发送自定义广播
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档