android 动态注册 广播
引用:http://hi.baidu.com/duanxzf/item/39061b0e7d6bd184a2df434c
在动态注册中,不需要再AndroidManifest.xml中配置receiver了。
在onResume函数中,通过registerReceiver()注册,在onPause()中,通过unregisterReceiver()来取消注册。
package com.dxz.broadcasttest.dynamic;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BroadcastTest extends Activity {
public static final String NEW_LIFEFORM_DETECTED = "com.dxz.broadcasttest.NEW_LIFEFORM";
protected MyBroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Button btn0 = (Button) findViewById(R.id.btn0);
btn0.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent it = new Intent(NEW_LIFEFORM_DETECTED);
sendBroadcast(it);
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("in dynamic onResume register");
IntentFilter counterActionFilter = new IntentFilter(
NEW_LIFEFORM_DETECTED);
receiver = new MyBroadcastReceiver();
registerReceiver(receiver, counterActionFilter);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
System.out.println("in dynamic onPause unregister");
unregisterReceiver(receiver);
}
}
receiver代码:
package com.dxz.broadcasttest.dynamic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver () {
Log.v("BROADCAST_TAG", "myBroadCast");
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("dynamic");
Toast.makeText(context, "成功接收广播dynamic:", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml文件:(没有receiver节点了)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dxz.broadcasttest.dynamic"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".BroadcastTest"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>