首页 > 代码库 > android使用两种方式注册receiver
android使用两种方式注册receiver
1、
package com.example.myreceiver; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { private MyBroadcastReceiver receiver = new MyBroadcastReceiver(); private IntentFilter filter = new IntentFilter("com.feng.intent"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void start(View view){ Intent intent = new Intent("com.feng.intent"); intent.putExtra("name", "wang"); sendBroadcast(intent); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); } @Override protected void onResume() { super.onResume(); registerReceiver(receiver, filter); } }
package com.example.myreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class MyBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { System.out.println("good!i've recevied u!"); Log.e("MyBroadcastReceiver", "good!i've recevied u!"); } }这种方式的好处是,使用灵活,可控性高。
另外一种是在mainfest.xml中注册。这种好处是只要应用程序安装后,就会一直处于监听状态。
<receiver android:name="com.example.myreceiver.MyBroadcastReceiver"> <intent-filter > <action android:name="com.feng.intent"/> </intent-filter> </receiver>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。