activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="24dip" android:gravity="center" android:text="BroadcastReceiver演示"/> <Button android:id="@+id/send_static" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="发送自定义静态注册广播" /> </LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.my.broaccast" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <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=".StaticReceiver"> <intent-filter> <action android:name="com.my.staticreceiver" /> </intent-filter> </receiver> </application> </manifest>
MainActivity.java
package com.my.broaccast; 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 MainActivity extends Activity { private Button sendStaticButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendStaticButton = (Button) findViewById(R.id.send_static); sendStaticButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setAction("com.my.staticreceiver"); intent.putExtra("msg", "接收静态注册广播成功!"); sendBroadcast(intent); } }); } }
StaticReceiver.java
package com.my.broaccast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class StaticReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if ("com.my.staticreceiver".equalsIgnoreCase(intent.getAction())) { String msg = intent.getStringExtra("msg"); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } } }
时间: 2024-10-09 11:36:21