Android四大组件之BroadCast

Posted 康小庄

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android四大组件之BroadCast相关的知识,希望对你有一定的参考价值。

写在前面

  • 记录学习BroadCast的使用
  • IDE:android-Studio SDK版本:API30

本文主要用ServiceBroadCast来实现一个秒表具有开始暂停归零三个功能

话不多说开始上代码

activity_receive.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ReceiveActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="35sp">
    </TextView>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="200dp"
        android:layout_marginTop="100dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="开始">
        </Button>

        <Button
            android:id="@+id/btn2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="暂停">
        </Button>

        <Button
            android:id="@+id/btn3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="归零">
        </Button>
    </LinearLayout>
    <TextView
        android:id="@+id/timeView"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="">
    </TextView>
</LinearLayout>

预览下界面,比较简单

1.定义广播发送器BroadCastSender

package com.czie.service;

import android.content.Intent;

/**
 * 广播发送器
 */
public class BroadCastSender {
    //定义常量
    public static final String BROADACTION = "CZIE";
    Intent intent = new Intent();

    public void send(String name, String value) {
        //添加主题
        intent.setAction(BROADACTION);
        intent.putExtra(name, value);
        //发送广播
        MyApplication.getContext().sendBroadcast(intent);
    }

    public void send(String name, int value) {
        //添加主题
        intent.setAction(BROADACTION);
        intent.putExtra(name, value);
        MyApplication.getContext().sendBroadcast(intent);
    }

    public void send(String name, Long value) {
        //添加主题
        intent.setAction(BROADACTION);
        intent.putExtra(name, value);
        MyApplication.getContext().sendBroadcast(intent);
    }

    public void send(String name, Byte value) {
        //添加主题
        intent.setAction(BROADACTION);
        intent.putExtra(name, value);
        MyApplication.getContext().sendBroadcast(intent);
    }
}

2.定义Service发送消息

通过while循环来不停的发送消息

TestService3

package com.czie.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import static com.czie.service.ReceiveActivity.istime;

public class TestService3 extends IntentService {
    BroadCastSender sender = new BroadCastSender();
    //必须实现父类的构造方法
    public TestService3() {
        super("TestService3");
        // TODO Auto-generated constructor stub
    }

    //必须重写的核心方法
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
      
        int i = 0;
        while (true) {
            if (istime == 0) {
                i++;
            } else if (istime == 1) {
                i = 0;
            }
            sender.send("HelloWorld",i);
            try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }
}

3.应用类MyApplication

该类用来获取上下文

MyApplication

package com.czie.service;

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context=this;
    }

    public static Context getContext() {
        return context;
    }
}

4.主界面ReceiveActivity

  • 设置按钮监听事件
  • 广播接收
  • 创建广播接收器

ReceiveActivity

package com.czie.service;

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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressWarnings({"all"})
public class ReceiveActivity extends AppCompatActivity implements View.OnClickListener {
    public static int istime;
    MyBroadReceiver myBroadReceiver;
    private TextView textView;
    private TextView timeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive);
        Button btn1 = findViewById(R.id.btn1);
        Button btn2 = findViewById(R.id.btn2);
        Button btn3 = findViewById(R.id.btn3);
        textView = findViewById(R.id.text1);
        timeView=findViewById(R.id.timeView);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);

        //广播接受
        myBroadReceiver=new MyBroadReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadCastSender.BROADACTION);
        registerReceiver(myBroadReceiver,intentFilter);
      //  startService(new Intent(ReceiveActivity.this,TestService3.class));
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
                istime=0;
                startService(new Intent(ReceiveActivity.this,TestService3.class));
              //  startService(Intent.makeMainActivity(startService(new Intent(ReceiveActivity.this, TestService3.class))));
            break;
            case R.id.btn2:
                istime=2;
                break;
            case R.id.btn3:
                istime=1;
                break;

        }
    }

    //创建广播接收器
    class MyBroadReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取参数
            int time = intent.getIntExtra("HelloWorld",0);
            //分钟
            int min =time/60;
            //秒钟
            int second=time%60;
            String times=String.format("%02d",min)+":"+String.format("%02d",second);

            textView.setText(String.valueOf(times));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String clockTime = simpleDateFormat.format(new Date());
            timeView.setText(clockTime);
        }
    }
}

预览下成果

写在最后

  • 掌握BroadCast基本知识点和如何发送和接收消息,并实现功能👍
  • 继续探索BroadCast其他功能💪
  • 本篇文章对你有用的话,记得点个赞👍
  • 对本篇文章有任何问题,欢迎评论区指出❤️

以上是关于Android四大组件之BroadCast的主要内容,如果未能解决你的问题,请参考以下文章

Android四大组件之BroadcastReceiver

Android面试四大组件之广播BroadCast

Android四大组件之BroadcastReceiver详细解析

Android安卓四大组件之广播

Android四大组件-Broadcast Receiver

Android 四大组件 BroadcastReceiver 介绍