Android中Broadcast
前一段时间,听说过android的广播,这段时间经过研究终于可以写出一个Demo
首先新建一个android工程项目

在BroadCastActivity.java中
package com.mypack; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class BroadCastActivity extends Activity { private Button sendbtn; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sendbtn=(Button)this.findViewById(R.id.button1); sendbtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub send(); } }); } public void send() { Intent intent=new Intent("android.intent.action.MY_BROADCAST"); //标记作用的,广播接收器通过匹配"android.intent.action.MY_BROADCAST"接收发送的消息,在AndroidMainfest.xml中进行过滤匹配 intent.putExtra("msg","chen liang");//发送的消息 this.sendBroadcast(intent);//发送广播 } }
MyReceiver.java相当于接收器里面写成
package com.mypack; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; public class MyReceiver extends BroadcastReceiver{ private static final String TAG="MyReciver"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String msg=intent.getStringExtra("msg");//接收信息 Log.i(TAG,msg); } }
另外还要对广播进行注册,要说到注册有静态注册和动态注册两种方式,在这里我说的是静态注册
静态注册是在AndroidMainfest.xml中进行的
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mypack"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".BroadCastActivity"
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="android.intent.action.MY_BROADCAST"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</application>
</manifest>
主要就是 <receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_BROADCAST"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
这样就OK了
运行程序后

点击按钮后

OK
浙公网安备 33010602011771号