Android Broadcast Receiver
注册广播的方式有两种:在代码中动态注册,或是在AndroidManifest.xml
中进行静态注册。
如果想要创建一个广播接收器,新建一个类,继承自BroadcastReceiver
,并且继承父类的onReceive()
方法。
package com.broadcasttest.lightless.broadcasttest;
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.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "network changes", Toast.LENGTH_SHORT).show();
}
}
}
如果使用内部类,必须将自己的Receiver定义为static。
在AS中,如果要使用本地广播(LocalBroadcastManager),必须要在File->Project Structure中的Dependencies中引入support-v4这个东西。