首页 > 其他分享 >Android 详解广播机制

Android 详解广播机制

时间:2022-11-20 14:00:47浏览次数:49  
标签:void intentFilter 广播 详解 Intent new Android intent

Android 详解广播机制

广播的种类

静态广播和动态广播

接受系统广播

extends BroadcastReceiver{}
onReceive(Context context, Intent intent)
onReceive方法中用来处理接收到广播后,处理的逻辑

动态注册监听网络变化

intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeRecever = new NetworkChangeRecever();
registerReceiver(networkChangeRecever, intentFilter);

静态注册

findViewById(R.id.button).setOnClickListener(view -> {
    Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
    intent.setPackage(getPackageName());
    sendBroadcast(intent);
});
<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>

动态注册

intentFilter = new IntentFilter("MY_ACTION");
bootCompleteReceiver = new BootCompleteReceiver();
registerReceiver(bootCompleteReceiver, intentFilter);
findViewById(R.id.button1).setOnClickListener(view -> {
    sendBroadcast(new Intent("MY_ACTION"));
});

注意点:

// 记得加上setPackage,否则新版本安卓广播可能用不了
intent.setPackage(getPackageName());

有序广播 (带优先级)

findViewById(R.id.button).setOnClickListener(view -> {
    Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
    intent.setPackage(getPackageName());
   sendOrderedBroadcast(intent,null);// sendOrderedBroadcast这里多传一个null 参数
});

AndroidManifest.xml,在增加android:priority优先级

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

abortBroadcast();表示这条广播截断,后面的广播接收器无法再收到这条广播。

本地广播

//发送
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);

//接收
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
LocalReceiver localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver,intentFilter);

//销毁
localBroadcastManager.unregisterReceiver(localReceiver);

//继承BroadcastReceiver
class LocalReceiver extends BroadcastReceiver{
   //在onReceive复写方法中写逻辑
}

广播的实践---强制下线

public class MainActivity extends BaseActivity {
    private static final String wAccount = "admin";
    private static final String wPassword = "123";


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findViewById(R.id.login_button).setOnClickListener(v -> {
            EditText accountView = findViewById(R.id.account);
            EditText passwordView = findViewById(R.id.password);
            String account = accountView.getText().toString();
            String password = passwordView.getText().toString();
            if (wAccount.equals(account) && wPassword.equals(password)) {
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            } else {
                Toast.makeText(MainActivity.this, "account or password is wrong", Toast.LENGTH_SHORT).show();
            }
        });


    }
}
public class MainActivity2 extends BaseActivity {


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout2);
        findViewById(R.id.force_offline).setOnClickListener(v -> {
            sendBroadcast(new Intent("FORCE_OFFLINE"));
        });
    }
}
public class BaseActivity extends AppCompatActivity {


    private OfflinReceiver receive;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityController.addActivity(this);
    }




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


    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receive);
    }


    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("FORCE_OFFLINE");
        receive = new OfflinReceiver();
        registerReceiver(receive, intentFilter);


    }


    class OfflinReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Warning");
            builder.setMessage("you will be forced offline,please try login again");
            builder.setCancelable(false);
            builder.setPositiveButton("OK", (dialog, which) -> {
                ActivityController.finishAll();
                Intent intent1 = new Intent(context, MainActivity.class);
                context.startActivity(intent1);
            });
            builder.show();


        }
    }
}
public class ActivityController {


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


}

标签:void,intentFilter,广播,详解,Intent,new,Android,intent
From: https://www.cnblogs.com/zybao/p/16908356.html

相关文章

  • java -Xms -Xmx -XX:PermSize -XX:MaxPermSize-详解
         在做java开发时尤其是大型软件开发时经常会遇到内存溢出的问题,比如说OutOfMemoryError等。这是个让开发人员很痛苦、也很纠结的问题,因为我们有时不知道什么样的......
  • Android 内容提供器
    内容提供器(ContentProvider)简介内容提供器(ContentProvider)主要用于在不同的应用程序之间实现数据共享的功能,它提供了一套完整的机制,允许一个程序访问另一个程序中的数......
  • Android 数据存储方案
    Android数据存储方案利用文件进行存取数据写入文件数据openFileOutput是Context中提供的一个方法,用于将数据存储到指定的文件中,第一个参数是文件名,第二个参数是文件......
  • Java中的泛型详解
    ......
  • springboot整合redis详解
    springboot整合redis1.首先创建springboot工程2.配置pom.xml文件<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns......
  • Build failed due to use of deprecated Android v1 embedding.
    原文:https://blog.51cto.com/u_15639793/5340424 问题:Warning────────────────────────────────────────────────......
  • Android 使用网络技术
    Android使用网络技术使用<!--在布局文件中增加--><WebViewandroid:id="@+id/web_view"android:layout_width="match_parent"android:layout_height="......
  • 性能监控命令vmstat详解【杭州多测师】【杭州多测师_王sir】
    vmstat命令:用来获得有关进程、虚存、页面交换空间及CPU活动的信息。这些信息反映了系统的负载情况。vmstat 命令的输出vmstat 1 10  实例解读一:​​​​​CPU状态的监......
  • 性能监控命令top详解【杭州多测师】【杭州多测师_王sir】
     一、top命令介绍top命令是Linux系统中常用的性能分析工具,可以实时地查看系统的运行情况,比如内存、CPU、负载以及各个进程的资源占用情况二、top命令详解第一行:top-14:39......
  • Android 利用和风天气API显示实时天气
    最近开发遇到了这样的需求,需要在APP中显示出实时天气等信息,可以利用和风天气提供的API,免费订阅可以使用一定数量的查询额度,不过也差不多够用了。进入和风天气官网,注册。......