Writing in the front
- Record the use of BroadCast learning
IDE: Android-Studio SDK version: API30
About the previous foundation:
- About what is
BroadCast
Please refer to this articleAndroid BroadcastReceiver - about
Service
Refer to this articleAndroid four components of the Service
This paper mainly uses Service and BroadCast to realize a stopwatch with start, pause, return to zero three functions
Without further ado, let’s start coding
activity_receive.xml
<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="Start">
</Button>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Pause">
</Button>
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Zero">
</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>
Copy the code
Preview the interface. It’s easy
1. Define BroadCastSender
package com.czie.service;
import android.content.Intent;
/** ** Broadcast transmitter */
public class BroadCastSender {
// Define constants
public static final String BROADACTION = "CZIE";
Intent intent = new Intent();
public void send(String name, String value) {
// Add a theme
intent.setAction(BROADACTION);
intent.putExtra(name, value);
// Send a broadcast
MyApplication.getContext().sendBroadcast(intent);
}
public void send(String name, int value) {
// Add a theme
intent.setAction(BROADACTION);
intent.putExtra(name, value);
MyApplication.getContext().sendBroadcast(intent);
}
public void send(String name, Long value) {
// Add a theme
intent.setAction(BROADACTION);
intent.putExtra(name, value);
MyApplication.getContext().sendBroadcast(intent);
}
public void send(String name, Byte value) {
// Add a themeintent.setAction(BROADACTION); intent.putExtra(name, value); MyApplication.getContext().sendBroadcast(intent); }}Copy the code
2. Define a Service to send messages
Keep sending messages through a while loop
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();
// The parent class constructor must be implemented
public TestService3(a) {
super("TestService3");
// TODO Auto-generated constructor stub
}
// Core methods that must be overridden
@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(); }}}}Copy the code
3. MyApplication
This class is used to get the context
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(a) {
super.onCreate();
context=this;
}
public static Context getContext(a) {
returncontext; }}Copy the code
4. ReceiveActivity on the home screen
- Set button listening events
- Radio reception
- Creating a Broadcast receiver
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);
// Broadcast acceptance
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; }}// Create a broadcast receiver
class MyBroadReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// Get parameters
int time = intent.getIntExtra("HelloWorld".0);
/ / minute
int min =time/60;
/ / second
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(newDate()); timeView.setText(clockTime); }}}Copy the code
Preview the results
Write in the last
- Master the basic knowledge of BroadCast and how to send and receive messages, and realize the functions 👍
- Continue exploring BroadCast’s other features 💪
- If you found this article useful, please like 👍
- If you have any questions about this article, please point to ❤️ in the comments section