【安卓笔记】作为内部类的广播接收者
package com.example.brocastdemo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button but = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); but = (Button) findViewById(R.id.but); but.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.aaa"); MainActivity.this.sendBroadcast(intent); } }); } public static class MyReceiver extends BroadcastReceiver//作为内部类的广播接收者 { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("com.aaa")) { Log.i("MainActivity","成功收到广播"); } } } }2.清单文件:
<receiver android:name="com.example.brocastdemo.MainActivity$MyReceiver" > <intent-filter > <action android:name="com.aaa"/> </intent-filter> </receiver>
android:name="com.example.brocastdemo.MainActivity$MyReceiver"2.内部类在声明时一定要写成静态内部类(class关键字前加上static)。否则会抛出类似这样的异常:
02-19 09:11:14.650: E/AndroidRuntime(1771): java.lang.RuntimeException: Unable to instantiate receiver com.example.brocastdemo.MainActivity$MyReceiver: java.lang.InstantiationException: can‘t instantiate class com.example.brocastdemo.MainActivity$MyReceiver; no empty constructor
package com.example.brocastdemo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; //采用动态方式注册一个作为内部类的广播接收者 public class MainActivity extends Activity { private Button but = null; private MyReceiver receiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); but = (Button) findViewById(R.id.but); /*动态方式注册广播接收者*/ receiver = new MyReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("com.aaa"); this.registerReceiver(receiver, filter); but.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.aaa"); MainActivity.this.sendBroadcast(intent); } }); } public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("com.aaa")) { Log.i("MainActivity","成功收到广播"); } } } @Override protected void onDestroy() { if(receiver!=null) this.unregisterReceiver(receiver); } }此时,清单文件中不用加receiver节点了。测试当然也是通过的,这样做就方便多了!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。