MainActivity如下:
package cc.testbroadcasta; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; /** * Demo描述: * 在代码中注册广播接收者 * 1 在onCreate()中注册广播接收者 * 2 在onDestroy()中取消注册广播接收者 */ public class MainActivity extends Activity { private BroadcastReceiverTest mBroadcastReceiverTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //注册一个广播接收者 registerAReceiver(); //发送一个广播 sendABroadcast(); } private void registerAReceiver(){ mBroadcastReceiverTest=new BroadcastReceiverTest(); //为广播接收者设置IntentFilter IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction("cc.test"); registerReceiver(mBroadcastReceiverTest, intentFilter); } private void sendABroadcast(){ Intent intent = new Intent(); // 设置Action intent.setAction("cc.test"); // 携带数据 intent.putExtra("name", "周星驰"); intent.putExtra("number", 9527); // 发送广播 sendBroadcast(intent); } @Override protected void onDestroy() { super.onDestroy(); //取消广播接收者的注册 if (mBroadcastReceiverTest!=null) { unregisterReceiver(mBroadcastReceiverTest); } } }
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="在代码中注册广播接收者" android:layout_centerInParent="true"/> </RelativeLayout>
时间: 2024-11-08 21:37:59