广播机制

标准广播

无法拦截

有序广播

可以拦截
在代码中注册动态注册和在xml中的金泰注册

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null&&networkInfo.isAvailable()){
Toast.makeText(MainActivity.this,"NetWork is available",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"NetWork is not available",Toast.LENGTH_SHORT).show();

}

动态注册

实现要求

实现动态注册,进行网络连接检测的广播
1 创建app 名称为DynamicNetworkTest
2 添加一个类 DynamicNetworkChecker 继承于BroadcastReceiver

package cn.democpp.www.dynamicnetworktest;

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

public class DynamicNetworkChecker extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}

3 重写onReceive方法


package cn.democpp.www.dynamicnetworktest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; public class DynamicNetworkChecker extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //实例话ConnectivityManager对象 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); // 获取网络连接的信息 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // 判断网络连接情况 if (networkInfo != null && networkInfo.isAvailable()) { Toast.makeText(context, "连接成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "连接失败", Toast.LENGTH_SHORT).show(); } } }

4 在AndroidManifest.xml中添加权限

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

5 在MainActivity中添加代码

package cn.democpp.www.dynamicnetworktest;

import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    // 定义全局变量
    private IntentFilter intentFilter;
    private DynamicNetworkChecker checker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化 checker
        checker = new DynamicNetworkChecker();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        //注册
        registerReceiver(checker, intentFilter);
    }

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

6 点击运行,更改网络连接状态就可以看出不同的显示

静态注册

  1. 在包中添加Broadcast new-> Other ->Broadcast Receiver

自定义注册

1 新建项目
2 在新建一个Broadcast广播器 file->new->Other->Broadcast 创建MyBroadcastReceiver


package cn.democpp.www.mybroadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("运行","运行"); Toast.makeText(context,"接受到自定义的广播",Toast.LENGTH_SHORT).show(); } }

修改AndroidManifst.xml配置文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.democpp.www.mybroadcast">
    <permission
        android:name="com.example.broadcast.permission"
        android:protectionLevel="normal" />
    <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:permission="com.example.broadcast.permission"
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <!--自定义广播名称-->
                <action android:name="cn.democpp.www.mybroadcast" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

3 修改界面 添加一个按钮
4 在主界面添加按钮响应广播事件

package cn.democpp.www.mybroadcast;

import android.content.ComponentName;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.send);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("发送广播", "cheng");
                Intent intent = new Intent("cn.democpp.www.mybroadcast");
                // Android8以上需要加入该语句
                // 第一个是自定义的名称 与配置文件的保一致,
                // 第二个是你创建的MyBroadcastReceiver路径
                intent.setComponent(new ComponentName("cn.democpp.www.mybroadcast", "cn.democpp.www.mybroadcast.MyBroadcastReceiver"));
                sendBroadcast(intent);
            }
        });
    }
}

张贴在未分类

发表评论