發送自定義廣播

發送自定義廣播

1.發送標準廣播

新建一個MyBroadcastReceiver:

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:

<?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:

<?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:

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:

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:

<?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項目點擊事件中更改:

sendBroadcast(intent,null);
有序廣播的截斷

修改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/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中截斷廣播:

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:

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


                }
            }




}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章