广播学习Demo

本文详细介绍了Android应用内广播的使用方法,包括如何发送广播、动态注册与注销广播,以及广播接收器的实现。通过实例代码展示了广播机制在Android开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

广播简单学习Demo

package com.amaker.broadcast;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* 1,点击按钮发送一个广播
* 2,注册广播时有两种注册:一,在配置文件中静态注册 二、在代码中动态注册
* 注意:注册方法写在:onResume里面,注销方法写在:onPause里面
*
*/
public class MainActivity extends Activity {
private Button btn_send;
public static final String MY_ACTION = "com.amaker.broadcast.MY_ACTION";
MyReceiver r = new MyReceiver();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btn_send = (Button) findViewById(R.id.button1);

btn_send.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
send();
}
});
}
//发送一个广播
void send(){
Intent intent = new Intent(MY_ACTION);
String msg = "我给你发了一个广播,是否收到?";
intent.putExtra("msg", msg);
sendBroadcast(intent);
}
//动态注册广播
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(MY_ACTION);
registerReceiver(r, filter);
}
//注销广播
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(r);
}
}


package com.amaker.broadcast;

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

public class MyReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("msg");
//收到广播,简单Toast显示一下
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}

}


AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.amaker.broadcast"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 先把这个静态的注册注释掉 -->
<!--<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.amaker.broadcast.MY_ACTION"/>
</intent-filter>
</receiver> -->


</application>
</manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值