Android广播入门,单个手机上App之间的发送接收
来源:互联网 发布:通州梨园淘宝城 编辑:程序博客网 时间:2024/06/11 16:49
在这里给大家分享安卓四大组件之一Broadcastreceiver(广播)的学习,在这里今天做一个同一部手机上APP之间的广播发送和接收.
首先第一个App用于发送广播出去给其余的App,布局采用一个文本域和一个button按钮,当我点击按钮时进行发送,代码如下:
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="请输入问候的语句" android:id="@+id/main_text_edit"/> <Button android:layout_width="wrap_content" android:layout_gravity="center" android:layout_height="wrap_content" android:text="发送" android:onClick="send" />当我点击发送的时候调用当前布局Activity的send方法进行广播的发送,代码如下:
private Intent intent; private EditText main_text_edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取文本域控件 main_text_edit = (EditText) findViewById(R.id.main_text_edit); //实力化 intent = new Intent(); //给Intent设置一个特定的广播名字(专业术语是给Activity设置一个行为); intent.setAction("com.example.android_broadcastreceiver.01"); } public void send(View view){ //获取文本域控件的值 String data=main_text_edit.getText().toString(); //使用Intent携带 intent.putExtra("data",data); //发送广播 sendBroadcast(intent); }那么发送广播就是这样,现在来写一个接收广播的App,由于写一个简单点的接收App布局和MainActivity都是创建的那样不做改动,只是增加一个类继承BroadcastReceiver类,然后重写它的一个onReceive方法,这个方法就是接收广播,代码如下:
public void onReceive(Context context, Intent intent) { if("com.example.android_broadcastreceiver.01".equals(intent.getAction())){ String data=intent.getStringExtra("data"); Log.i("text",data); } }在这里的判断中字符串的值是在第一个发送广播App中Intent行为的值也就是广播的名字,当你名字等于我接收广播的名字时那么就会进入判断。
在这里要注意一下Android清单文件中要增加几行代码,如下:
<receiver android:name=".MyReceiver"> <intent-filter> <action android:name="com.example.android_broadcastreceiver.01"></action> </intent-filter> </receiver>这代码加在application标签中,android:name=我们自己定义继承BroadcastReceiver的类名。
今天分享的广播就是这样了,注意只能在同部手机上App之间的广播传递。
3 0
- Android广播入门,单个手机上App之间的发送接收
- 【记录】Android 广播的发送与接收
- Android动态广播的发送和接收
- Android 广播的发送与接收
- Android广播的发送与接收
- android的广播发送与接收
- Android Activity接收Service发送的广播
- Android Activity接收Service发送的广播
- Android 广播代码的发送与接收
- Android广播的发送与接收
- Android静态广播接收不到(app之间数据传递)
- android接收adb发送的系统广播及自定义广播
- android静态注册的广播在某些手机上无法正常接收
- android 广播发送和接收
- android发送和接收广播
- android 发送广播 接收广播 动态广播接收
- Android发送广播与接收广播
- 广播的发送和接收
- UVA506 System Dependencies(模拟)
- 趣味面试题(1)
- Cogs 1500. 误差曲线(三分)
- python读取csv----python根据IP列表生成百度IP热点图tilemap
- [BZOJ3668][Noi2014]起床困难综合症(贪心)
- Android广播入门,单个手机上App之间的发送接收
- php中static关键字的用法(未完)
- TabLayout自己踩过的一些坑
- Lucene初探
- IT项目管理总结
- C++容器适配器
- maven项目引入findbugs检查
- PHP中的会话控制(一):cookie
- java集合中list集合基本用法及List集合特有的迭代器ListIterator