mengyun 2017-01-06
Android广播分为两个方面:广播发送者和广播接收者BroadcastReceiver。
BroadcastReceiver可以分为两种注册类型:静态注册和动态注册。
静态注册:直接在AndroidManifest.xml文件中进行注册。
动态注册:直接在代码中调用Context的registerReceiver函数。
动态注册:
Activity类代码:
public class MainActivity extends Activity { private static final String SERVICE_NAME = "com.seasy.android.MyRemoteService"; private static final String BROADCAST_ACTION = "com.seasy.android.MyBroadcastReceiver"; private MyBroadcastReceiver broadcastReceiver; private TextView txtMessage = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMessage = (TextView)findViewById(R.id.txtMessage); doRegisterReceiver(); //启动Service Intent serviceIntent = new Intent(MainActivity.this, MyRemoteService.class); startService(serviceIntent); } @Override protected void onDestroy() { super.onDestroy(); doUnregisterReceiver(); } /** * 注册广播接收者 */ private void doRegisterReceiver(){ broadcastReceiver = new MyBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(BROADCAST_ACTION); registerReceiver(broadcastReceiver, intentFilter); } /** * 注销广播接收者 */ private void doUnregisterReceiver(){ unregisterReceiver(broadcastReceiver); } public TextView getTxtMessage() { return txtMessage; } //广播接收器类:收到广播消息后,将消息显示在界面的文本框中 class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String messageData = intent.getStringExtra("messageData"); getTxtMessage().setText(messageData); } } }
Service类代码:
public class MyRemoteService extends Service { private static final String BROADCAST_ACTION = "com.seasy.android.MyBroadcastReceiver"; @Override public void onCreate() { super.onCreate(); sendBroadcastMessage("Start Thrift Server"); } @Override public IBinder onBind(Intent intent) { return null; } /** * 发送广播 */ private void sendBroadcastMessage(String messageData){ Intent intent = new Intent(); intent.setAction(BROADCAST_ACTION); intent.putExtra("messageData", messageData); sendBroadcast(intent); } }
在AndroidManifest.xml文件中添加如下配置信息:
<service android:name="com.seasy.android.MyRemoteService" android:exported="false"></service>