关于广播注册方式的一点补充
前面在介绍广播时,都是在AndroidManifest里面进行注册的,这种注册方式具有常驻性,即使程序关闭,如果有广播信息来,程序也会被系统调用自动运行。还有一种方式是在代码里进行注册,这种注册方式不具有常驻性,也就是说广播跟随程序的生命周期。请看下面这个简单示例:
Activity:
package com.home.activity; 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; import com.home.R; import com.home.receiver.MyBroadCastReceiver; public class MainActivity extends Activity { public static final String ACTION = "com.home.receiver"; private IntentFilter filter = new IntentFilter(ACTION); private MyBroadCastReceiver receiver = new MyBroadCastReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button sendBtn = (Button) findViewById(R.id.main_btn_send); sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(ACTION); intent.putExtra("msg", "简单广播消息"); sendBroadcast(intent); } }); } @Override protected void onResume() { super.onResume(); // 注册Receiver registerReceiver(receiver, filter); } @Override protected void onPause() { super.onPause(); // 注销Receiver unregisterReceiver(receiver); } }
MyBroadCastReceiver:
package com.home.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("com.home.receiver".equals(intent.getAction())) { String msg = intent.getStringExtra("msg"); Toast.makeText(context, "收到" + msg, Toast.LENGTH_LONG).show(); } } }