目录
一、案例演示——发送与接收广播
1、创建安卓应用
- 选择模板
- 完善项目信息
2、添加背景图片
3、定义字符串资源文件变量
<resources>
<string name="app_name">发送与接收广播</string>
<string name="input_message">请输入要广播的消息</string>
<string name="send_broadcast">发送广播的消息</string>
</resources>
4、编写主布局资源文件
- 源代码
<?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"
android:background="@drawable/background"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edtMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/input_message"
android:singleLine="true"
android:textSize="20sp" />
<Button
android:id="@+id/btnSendBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="doSendBroadcast"
android:text="@string/send_broadcast"
android:textSize="20sp" />
</LinearLayout>
5、创建自定义广播接收者
- 源代码
package net.zs.send_receive_broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class CustomReceiver extends BroadcastReceiver {
private final String TAG = "send_receive_broadcast"; // 标记
private final String INTENT_ACTION_SEND_MESSAGE = "net.zs.intent.action.SEND_MESSAGE"; // 广播频道
@Override
public void onReceive(Context context, Intent intent) {
// 按照频道获取广播信息
if (intent.getAction().equals(INTENT_ACTION_SEND_MESSAGE)) {
// 获取广播信息
String message = intent.getStringExtra("message");
// 输出广播信息
Log.d(TAG, message);
}
}
}
6、在项目清单文件里注册广播接收者
- 采用静态方式注册自定义广播接收者
7、编写主界面类
- 源代码
package net.zs.send_receive_broadcast;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private final String TAG = "send_receive_broadcast"; // 标记
private final String INTENT_ACTION_SEND_MESSAGE = "net.zs.intent.action.SEND_MESSAGE"; // 广播频道
private EditText edtMessage; // 消息编辑框
private int broadcastCount; // 发送广播次数
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 利用布局资源文件设置用户界面
setContentView(R.layout.activity_main);
// 通过资源标识符获取控件实例
edtMessage = findViewById(R.id.edtMessage);
}
/**
* 发送广播
*/
public void doSendBroadcast(View view) {
// 统计发送广播次数
broadcastCount++;
// 获取用户输入要广播的信息
String message = edtMessage.getText().toString();
// 创建意图
Intent intent = new Intent();
// 设置意图动作(广播频道)
intent.setAction(INTENT_ACTION_SEND_MESSAGE);
// 设置意图携带的附加内容
intent.putExtra("message", "第" + broadcastCount + "次广播信息:" + message);
// 按照意图发送广播
sendBroadcast(intent);
}
}
8、运行程序,查看效果
9、采用动态方式注册广播接收者
- 修改项目清单文件对广播接收者的注册
- 在主界面类动态注册广播接收者
- 运行程序,查看效果
二、案例演示——显示播放进度
1、创建安卓应用
- 选择模板
- 完善项目信息
2、添加背景图片
3、定义字符串资源文件变量
<resources>
<string name="app_name">显示播放进度</string>
<string name="start">开始</string>
<string name="stop">停止</string>
</resources>
4、编写主布局资源文件代码
<?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"
android:background="@drawable/background"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0%"
android:textColor="#0000ff"
android:textSize="50sp" />
<ProgressBar
android:id="@+id/pbPlay"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btnStart"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:onClick="doStart"
android:text="@string/start"
android:textSize="20sp" />
<Button
android:id="@+id/btnStop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:onClick="doStop"
android:text="@string/stop"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
5、创建应用程序常量接口
- 源代码
package net.zs.display_progress;
/**
* 功能:应用程序常量接口
* 作者:zs
* 日期:2022年7月8日
*/
public interface AppConstants {
String TAG = "net.hw.display_progress"; // 应用程序标记
String INTENT_ACTION_START = "net.hw.display_progress.intent.action.START"; // 开始进度广播频道
String INTENT_ACTION_STOP = "net.hw.display_progress.intent.action.STOP"; // 停止进度广播频道
String INTENT_ACTION_UPDATE_PROGRESS = "net.hw.display_progress.intent.action.UPDATE_PROGRESS"; // 更新进度广播频道
}
6、创建进度服务类
- 源代码
package net.zs.display_progress;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.icu.text.PluralRules;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
/**
* 功能:进度服务类
* 作者:zs
* 日期:2022年7月8日
*/
public class ProgressService extends Service implements AppConstants {
private InnerBroadcastReceiver receiver; // 内部广播接收者
private IntentFilter filter; // 意图过滤器
private Thread thread; // 线程
private boolean isRunning; // 线程循环控制变量
private int progressValue; // 进度值
/**
* 创建回调方法
*/
@Override
public void onCreate() {
super.onCreate();
// 创建内部广播接收者
receiver = new InnerBroadcastReceiver();
// 创建意图过滤器
filter = new IntentFilter();
// 添加意图动作(广播频道)
filter.addAction(INTENT_ACTION_START);
filter.addAction(INTENT_ACTION_STOP);
// 动态注册内部广播接收者
registerReceiver(receiver, filter);
}
/**
* 启动更新线程
*/
private void starUpdateThread() {
// 设置线程循环控制变量为真
isRunning = true;
// 创建更新进度值得线程
thread = new Thread(new Runnable() {
@Override
public void run() {
// 线程循环
while (isRunning) {
// 更新进度值
progressValue = ++progressValue % 101;
// 输出调试信息
Log.d(TAG, "当前进度值:" + progressValue + "%");
// 创建意图
Intent intent = new Intent();
// 设置意图动作(广播频道)
intent.setAction(INTENT_ACTION_UPDATE_PROGRESS);
// 设置意图携带的附加数据
intent.putExtra("progressValue", progressValue);
// 按意图发送广播
sendBroadcast(intent);
try {
// 让线程睡眠500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
// 启动线程
thread.start();
}
/**
* 销毁更新线程
*/
private void destroyUpdateThread() {
// 设置线程循环控制变量为假
isRunning = false;
// 销毁更新进度的线程
thread = null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
/**
* 销毁回调方法
*/
@Override
public void onDestroy() {
super.onDestroy();
// 注销内部广播接收者
unregisterReceiver(receiver);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 内部广播接收者
*/
private class InnerBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
// 根据广播频道进行不同操作
switch (intent.getAction()) {
case INTENT_ACTION_START:
// 启动更新线程
starUpdateThread();
Log.d(TAG, "收到启动进度的广播!");
break;
case INTENT_ACTION_STOP:
// 销毁更新线程
destroyUpdateThread();
Log.d(TAG, "收到停止进度的广播!");
break;
}
}
}
}
}
7、在项目清单文件里注册进度服务类
8、编写主界面类
package net.zs.display_progress;
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.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AppConstants{
private TextView tvProgress; // 显示进度值的标签
private ProgressBar pbPlay; // 播放进度条
private Intent intent; // 意图
private IntentFilter filter; // 意图过滤器
private InnerBroadcastReceiver receiver; // 内部广播接收者
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 利用布局资源文件设置用户界面
setContentView(R.layout.activity_main);
// 通过资源标识符获取控件实例
tvProgress = findViewById(R.id.tvProgress);
pbPlay = findViewById(R.id.pbPlay);
// 创建启动服务的意图
intent = new Intent(this, ProgressService.class);
// 启动进度服务
startService(intent);
// 创建内部广播接收者
receiver = new InnerBroadcastReceiver();
// 创建意图过滤器
filter = new IntentFilter();
// 添加意图动作(广播频道)
filter.addAction(INTENT_ACTION_UPDATE_PROGRESS);
// 动态注册内部广播接收者
registerReceiver(receiver, filter);
}
/**
* 内部广播接受者
*/
private class InnerBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
// 收到来自进度服务所发送的广播
if (INTENT_ACTION_UPDATE_PROGRESS.equals(intent.getAction())) {
// 获取广播传递过来的进度值
int progressValue = intent.getIntExtra("progressValue", 0);
// 用更新后的进度值去设置进度标签
tvProgress.setText(progressValue + "%");
// 用更新后的进度值去设置进度条
pbPlay.setProgress(progressValue);
}
}
}
}
/**
* 开始按钮单击事件处理方法
*/
public void doStart(View view) {
// 创建意图
Intent intent = new Intent();
// 设置动作(广播频道)
intent.setAction(INTENT_ACTION_START);
// 按意图发生广播
sendBroadcast(intent);
}
/**
* 停止按钮单击事件处理方法
*/
public void doStop(View view) {
// 创建意图
Intent intent = new Intent();
// 设置动作(广播频道)
intent.setAction(INTENT_ACTION_STOP);
// 按意图发送广播
sendBroadcast(intent);
}
/**
* 销毁回调方法
*/
@Override
protected void onDestroy() {
super.onDestroy();
// 停止服务
stopService(intent);
// 注销广播接收者
unregisterReceiver(receiver);
}
}