1.四大组件之广播

广播有发射塔,有收音机

比如说升级系统,先检测一下电量,电量够才能升级

BroadcastReceiver就相当于一个收音机 (广播接收者)

 

标准广播:广播发出后,所有的收音机(BroadcastReceiver)会在同一时刻接收到这条广播消息,效率高,无法被截断。

有序广播:链式传递消息,同一时刻只有一个收音机能收到消息,这个收音机收到后下一个收音机才能接着收到。

 

系统会自动发出很多广播,比如开机广播,电池电量变化广播 想要收到这些广播就需要BroadcastReceiver(收音机)

 

想用收音机就得去相关部门申请使用无线电,BroadcastReceiver需要注册,注册之后就能接收到广播了。

在代码中动态注册或者在AndroidMainfest.xml中静态注册。

 

如何创建一个收音机(BroadcastReceiver)? 让一个类继承BroadcastReceiver并重写onReceive()方法就行了,当有广播时onReceive()方法就会执行。

 

示例一:用动态注册的方法编写一个能够监听时间变化的程序

package com.example.chargelisten;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Calendar;
import java.util.TimeZone;

public class MainActivity extends AppCompatActivity {

    TimeChangeReceiver timeChangeReceiver;

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

        //新建一个收音机
        timeChangeReceiver = new TimeChangeReceiver();
        //新建一个意图过滤器
        //意图过滤器会过滤 动作 类别 数据
        //action category data
        IntentFilter intentFilter = new IntentFilter();
        //过滤出系统发出的值为android.intent.action.TIME_TICK的广播动作,相当于设置收音机频道
        //TICK就是每分钟收广播一次
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        //注册广播  这里的this就是 context  设置把收音机和频道注册一下
        this.registerReceiver(timeChangeReceiver,intentFilter);
        //取消注册,要不会内存泄漏
        //if (timeChangeReceiver != null){
        //    this.unregisterReceiver(timeChangeReceiver);
        //}
    }

    /*动态广播不作为内部类的话会报错*/
    class TimeChangeReceiver extends BroadcastReceiver {

        TextView textView;
        //获取时间
        Calendar calendar;

        @Override
        public void onReceive(Context context, Intent intent) {
            //获取实例
            calendar = Calendar.getInstance();
            //设置时区
            calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            textView = findViewById(R.id.textView1);
            textView.setText("收到了时间变化的广播   现在分钟是: "+calendar.get(calendar.MINUTE));
        }

    }

}

 

   静态注册广播:大量恶意应用程序利用这个机制在程序未启动的情况下监听系统广播,从而使任何应用都可以频繁地从后台被唤醒。

  写一个类继承BroadcastReceiver变成收音机,

package com.example.chargelisten;

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

public class MyBootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"收到广播:开机完成",Toast.LENGTH_SHORT);
    }

}

  去注册,

别忘了给他权限 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chargelisten">

    <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/Theme.ChargeListen">
        <receiver
            android:name=".MyBootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <!--跟动态注册一样,设置action-->
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

自定义广播

小栗子的效果图:

 

 

发送广播的塔

package com.example.chargelisten;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SendBroadcastActivity extends AppCompatActivity {

    EditText editText;
    Button button;

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

        editText = findViewById(R.id.inputTextView);
        button = findViewById(R.id.sendBrodCastBtn);
    }

    public void sendBroadcastMsg(View view){
        //被调用之后我们就发广播
        String text = editText.getText().toString();
        //组件的跳转需要intent
        Intent intent = new Intent();
        //设置action action相当于我们的频道
        intent.setAction("sendBroadcastMsg.HHH");
        intent.putExtra("myValue",text);
        //发送广播,这是人家自带的方法
        sendBroadcast(intent);
        //别忘了去注册
    }

}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chargelisten">

    <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/Theme.ChargeListen">
        <receiver
            android:name=".getBrodcastMessage"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="sendBroadcastMsg.HHH"/>   给收音机设置一下频道
            </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true" />

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

            <!-- 跟动态注册一样,设置action -->
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".SendBroadcastActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

收音机

package com.example.chargelisten;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class getBrodcastMessage extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //这个收音机注册完之后就能get到了
        String myValue = intent.getStringExtra("myValue");
        Log.e("现在的action: ","action is "+action);
        Log.e("上一个intent传来的信息: ",myValue);
    }
}

 

posted @ 2021-09-08 11:09  涂妖教  阅读(138)  评论(0)    收藏  举报