android activity给服务发送广播 service接受广播打印log
时间: 2023-07-29 20:14:53 浏览: 56
好的,我来给您讲一下如何在 Android Activity 中发送广播并在 Service 中接收广播并打印 log。
首先在 Activity 中发送广播,可以使用 Intent 来实现。示例代码如下:
```
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_BROADCAST");
intent.putExtra("data", "Hello, Service!");
sendBroadcast(intent);
```
这里我们指定了广播的 Action 为 "com.example.broadcast.MY_BROADCAST",并且传递了一个字符串数据 "Hello, Service!"。
接下来在 Service 中接收广播,可以通过注册 BroadcastReceiver 来实现。示例代码如下:
```
public class MyService extends Service {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("com.example.broadcast.MY_BROADCAST".equals(action)) {
String data = intent.getStringExtra("data");
Log.d("MyService", "Received broadcast: " + data);
}
}
};
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.broadcast.MY_BROADCAST");
registerReceiver(receiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
```
这里我们创建了一个 BroadcastReceiver,并在 onCreate() 方法中注册了它,指定了要接收的广播 Action 为 "com.example.broadcast.MY_BROADCAST"。当接收到广播时,我们从 Intent 中获取传递的数据,并打印 log。
最后别忘了在 Service 销毁时取消注册 BroadcastReceiver。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)