zoukankan      html  css  js  c++  java
  • android中实现自定义广播

    自定义广播分两个步骤:1、发送广播 2、接收广播

    一、先看如何接收广播:

    我使用的是Android Studio,File->New->Other->Broadcast Receiver,先创建一个广播类,这个创建的类会自动帮我们继承BroadcastReceiver类,接收广播,需要继承这个类

    MyReceiver.java

    package com.example.chenrui.app1;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    import android.widget.Toast;
    
    public class MyReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "收到广播", Toast.LENGTH_SHORT).show();
        }
    }

    上面的代码,很简单,就是在接收到广播时,弹出一个toast提示框。

    创建这个类时,同时会在AndroidManifest.xml注册一个服务,注意红色内容是在自动注册的代码上手工添加的内容:

            <receiver
                android:name=".MyReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="com.example.chenrui.app1.broadcast1" />
                </intent-filter>
            </receiver>

    手工添加的内容,是指自定义广播的广播名称,这个广播名称可以随便定义,这个名称在后面发送广播的时候要用到。

    二、发送广播:

    添加一个Activity,在界面上添加一个Button按钮,然后编写按钮的onclick事件,注意红色内容为主要代码:

    MainActivity.java

    package com.example.chenrui.app1;
    
    import android.content.ComponentName;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    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 = findViewById(R.id.button1);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("com.example.chenrui.app1.broadcast1");
                    intent.setComponent(new ComponentName("com.example.chenrui.app1","com.example.chenrui.app1.MyReceiver"));
                    sendBroadcast(intent,null);
                }
            });
        }
    }

    红色代码第1行,指的是要发送一条广播,并且指定了广播的名称,这个跟我们之前注册的广播名称一一对应。

    红色代码第2行,在Android 7.0及以下版本不是必须的,但是Android 8.0或者更高版本,发送广播的条件更加严苛,必须添加这一行内容。创建的ComponentName实例化对象有两个参数,第1个参数是指接收广播类的包名,第2个参数是指接收广播类的完整类名。

    红色代码第3行,指的是发送广播。

    经过上面的步骤,完整的发送接收自定义广播的例子就完成了。

    实现效果(点击按钮时,会弹出一个toast提示信息):

  • 相关阅读:
    Nginx部署部分https与部分http【转】
    MySQL指定使用某个索引查询语句
    MySQL创建相同表和数据命令
    Apache+jboss群集部署
    运维小知识之nginx---nginx配置Jboss集群负载均衡
    SSL证书生成方法【转】
    Nginx搭建https服务器
    基于OpenSSL实现C/S架构中的https会话
    OnlineJudgeServer运行
    百科知识 isz文件如何打开
  • 原文地址:https://www.cnblogs.com/modou/p/10266320.html
Copyright © 2011-2022 走看看