Android Studio 学习笔记(2)

原创
2021/06/21 15:18
阅读数 75

广播 

标准广播(Normal Broadcasts) 完全异步执行的广播,广播效率较高,但无法截断。

有序广播(Ordered Broadcasts)同步执行广播,根据接收器优先级高低由高到低按序接收。可截断!

注册广播的的两种方式:在代码中注册(动态注册)和在AndroidManifest.xml(静态注册)中注册。

private 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,"网络已连接",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context,"网络断开",Toast.LENGTH_SHORT).show();
        }
    }
}

若需要程序在未启动的情况下就接收广播,就需要对广播进行静态注册,修改AndroidManifest.xml文件。 右击包名->NEW->Other->Broadcast Receiver,在弹出的界面上,Exported 表示是否允许这个广播接收器接收本程序之外的广播。Enabled表示是否启用这个广播接收器。

<receiver
    android:name=".BootCompleteReceiver"
    android:enabled="true"
    android:exported="true"></receiver>

 用这种方式创建的接收器,AndroidManife.xml已经自动注册完毕。  

广播是跨进程的通信方式,因此我们App中发出的广播,其他App也可以收到

有序广播 

Intent intent=new Intent("com.impulse.broadcasttest.MY_BROADCAST");
intent.putExtra("name","Tom");
sendOrderedBroadcast(intent,null);//有序广播 //sendBroadcast(intent) 标准广播
<receiver
    android:name=".MyBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter android:priority="100">
        <action android:name="com.impulse.broadcasttest.MY_BROADCAST" />
    </intent-filter>
</receiver>

广播优先级设定。

abortBroadcast();//截断广播方法

本地广播 (仅在APP内部发送和接收)无法进行静态注册。此方式比全局广播更加高效。

private LocalBroadcastManager localBroadcastManager;
Intent intent1=new Intent("com.impulse.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent1);
private class LocalReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"received from local broadcast",Toast.LENGTH_SHORT).show();
    }
}

实例1:利用广播强制下线

public class BaseActivity extends AppCompatActivity {
    private ForceOfflineReceiver receiver;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("com.impulse.broadcastbestpractice.FORCE_OFFLINE");
        receiver=new ForceOfflineReceiver();
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(receiver!=null){
            unregisterReceiver(receiver);
            receiver=null;
        }
    }

    private class ForceOfflineReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            AlertDialog.Builder builder=new AlertDialog.Builder(context);
            builder.setTitle("Warning");
            builder.setMessage("强制下线,请重新登录");
            builder.setCancelable(false);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    ActivityCollector.finishAll();
                    Intent intent=new Intent(context,LoginActivity.class);
                    context.startActivity(intent);
                }
            });
            builder.show();
        }
    }
}
public class MainActivity extends BaseActivity {

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

        Button forceoffline=findViewById(R.id.force_offline);
        forceoffline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent("com.impulse.broadcastbestpractice.FORCE_OFFLINE");
                sendBroadcast(intent);
            }
        });
    }
}
public class ActivityCollector {
    public static List<Activity> activityList=new ArrayList<>();

    public static void addActivity(Activity activity){
        activityList.add(activity);
    }

    public static  void  removeActivity(Activity activity){
        activityList.remove(activity);
    }

    public static void finishAll(){
        for(Activity activity :activityList){
            if(!activity.isFinishing()){
                activity.finish();
            }
        }
    }
}
展开阅读全文
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部