MainActivity如下:
package cc.testbroadcasta; import android.os.Bundle; import android.app.Activity; import android.content.Intent; /** * Demo描述: * 利用AndroidManifest.xml注册广播接收者 */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = new Intent(); // 设置Action intent.setAction("cc.test"); // 携带数据 intent.putExtra("name", "周星驰"); intent.putExtra("number", 9527); // 发送广播 sendBroadcast(intent); } }
BroadcastReceiverTest如下:
package cc.testbroadcasta; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BroadcastReceiverTest extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String name=intent.getStringExtra("name"); int number=intent.getIntExtra("number", 0); System.out.println("接收到广播 name="+name+",number="+number); } public static void main(String[] args) { } }
main.xml如下:
<RelativeLayout 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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="利用AndroidManifest.xml注册广播接收者" android:layout_centerInParent="true"/> </RelativeLayout>
AndroidManifest.xml如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cc.testbroadcasta" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="cc.testbroadcasta.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="cc.testbroadcasta.BroadcastReceiverTest"> <intent-filter > <action android:name="cc.test"/> </intent-filter> </receiver> </application> </manifest>
时间: 2024-10-01 01:34:30