Android学习笔记

Android广播机制

2017-12-10  本文已影响0人  Mason_Xu

广播机制

简介

接收系统广播

开机,电量,时间等系统广播

动态祖册监听网络变换

  1. 动态注册 ----- 在代码中注册
  2. 静态注册 ----- 在AndroidManifest.xml中注册
public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;

    private NetworkChangeReceiver networkChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver, intentFilter);
    }

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

    class NetworkChangeReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "network changes" , Toast.LENGTH_SHORT).show();
        }
    }
}
public class MainActivity extends AppCompatActivity {

    ...

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

            }
        }
    }
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mason.broadcasttest">
    // 访问网络状态权限
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    ...
</manifest>

静态注册实现开机启动

  1. 新建BootCompleteReceiver
  1. Toast提示
  2. 新建button,用于点击事件
  3. 静态的广播接收器一定要在AndroidManifest.xml文件中注册才可以使用 --- 由于我们使用快捷方式创建的,IDE已经自动完成注册 -- 属性和name
  4. 对AndroidManifest.xml进行修改,使它能够收到开机广播
  5. <intent-filter>标签中添加相应的action,开机的action是android.intent.action.BOOT_COMPLETED,同时声明监听开机广播权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Boot Complete", Toast.LENGTH_SHORT).show();
    }
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mason.broadcasttest">

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

    <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=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true"></receiver>
    </application>

</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mason.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">
        ...
        // 注册静态广播接收器
        <receiver
            android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            // 注册监听系统开机广播
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

发送自定义广播

发送标准广播

public class MyBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"received in MyBroadReceiver",Toast.LENGTH_SHORT).show();
    }
}
<receiver
    // 注意name
    android:name=".MyBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    // 注册监听
    <intent-filter>
        <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
    </intent-filter>
</receiver>

添加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.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });
        ...
    }
    ...
}

请注意,在Android8.0上,静态注册已经很多不能使用!

发送有序广播

其他程序接收到

public class AnoBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"received in AnoBroadcastReceiver",Toast.LENGTH_SHORT).show();
    }
}
<receiver
            android:name=".AnoBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>

有序广播

sendOrderedBroadcast(intent,null);

<receiver
            android:name=".BroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            // 设置优先级
            <intent-filter android:priority="100">
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
public class BroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"received in AnoBroadcastReceiver",Toast.LENGTH_SHORT).show();
        //设置截断
        abortBroadcast();
    }
}

本地广播

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;

    private LocalReceiver localReceiver;

    private LocalBroadcastManager localBroadcastManager;

    @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.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);  // 发送本地广播
            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);  // 注册本地广播监听器
    }

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

    ...

    class LocalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"received LocalBroadcast",Toast.LENGTH_SHORT).show();
        }
    }
}

这是我学习Android的笔记,参考书<<第一行代码-第二版>>,感谢郭霖大神
如有不足之处,可以一起讨论
附上郭霖的blog http://blog.csdn.net/guolin_blog

上一篇下一篇

猜你喜欢

热点阅读