对《第一行代码——android》的读书笔记
广播的类型:
1.标准广播:一种完全异步的广播,在广播发出后,所有的广播接收器几乎都会在同一时刻接收到这条广播消息,因此他们之间没有任何前后顺序可言。这种广播效率高,但
是同时也意味着他是无法被截断的。
2.有序广播:一种同步执行的广播,同一时刻只有一个广播接收器能够收到这条广播。优先级高的会先收到这条广播,并且前面的广播接收器可以截断这条广播。
接收系统广播:
Android系统内置了许多系统级别的广播,比如电量的广播,位置信息变更的广播。接受这些广播就需要广播接收器。
注册广播的形式一般有两种:动态在代码中注册或者在AndroidManifest.xml中注册。
广播接收器创建:
新建一个类继承BroadcastReceiver,并重写父类的onReceive()方法。当有广播到来,onReceive()方法就会得到执行,具体的逻辑就在这个方法中处理。
我们的广播接收器想要监听什么广播,就相应的添加action
动态注册监听网络变化
调用registerReceiver()进行注册
intentFilter=new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
net=new NetworkChangeReceiver();
registerReceiver(net, intentFilter);
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ConnectivityManager connectionManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo=connectionManager.getActiveNetworkInfo();
if(networkinfo!=null&&networkinfo.isAvailable()){
Toast.makeText(context, "有网络", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "mei有网络", Toast.LENGTH_LONG).show();
}
}
通过getSystemService得到ConnectivityManager的实例,这是一个系统服务类,专门用来管理网络连接。然后调用getActiveNetworkInfo得到networkinof实例,接着调用isAvailable就可以判断当前是否有网络
动态注册的广播接收器一定要取消注册才行
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(net);
}
静态注册实现了开机启动
动态注册的滚广播接收器可以自由的控制注册与注销,但有一个缺点,即必须在程序启动后才能接受到广播,所以需要静态注册。
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Boot Complete", Toast.LENGTH_LONG).show();
}
}
<receiver android:name=".BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
所有静态注册的广播都在receiver中进行注册,通过android:name=".BootCompleteReceiver" 指定具体注册哪一个广播接收器,然后在《intent-filter>标签里加入想要接受的广播就行了。由于Android系统启动后会发出android.intent.action.BOOT_COMPLETED的广播,因此在这添加了相应的action
发送自定义广播
发送标准广播
Intent inten t=new intent("antion");
sendBroadcast(intent);
发送有序广播
intent intent =new intent("action");
sendOrderedBroadcast(intent,null);
截断广播 abortBroadcast();
使用本地广播
使用这种机制的广播只能在应用程序的内部进行传递,并且广播接收器只能接受来自本应用程序发出的广播。
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
"com.example.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);
}
});
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received local broadcast",
Toast.LENGTH_SHORT).show();
}
}
}
这是添加了LocalBroadcastManager对发送,注册 销毁进行了管理
需要注意的是:本地广播无法通过静态注册的方法来接受。
广播的最佳实践----实现强制下线功能
创建ActivityCollector类用于管理所有的活动
public class ActivityCollector {
private static List<Activity> activities = new ArrayList<Activity>();
public static void addActivity(Activity activity) {
activities.add(activity);
}
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
public static void finishAll() {
for (Activity activity : activities) {
if (!activity.isFinishing()) {
activity.finish();
}
}
}
}
创建BaseActivity类作为所有活动的父类
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
登录页面
public class LoginActivity extends BaseActivity {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
pref = PreferenceManager.getDefaultSharedPreferences(this);
accountEdit = (EditText) findViewById(R.id.account);
passwordEdit = (EditText) findViewById(R.id.password);
rememberPass = (CheckBox) findViewById(R.id.remember_pass);
login = (Button) findViewById(R.id.login);
boolean isRemember = pref.getBoolean("remember_password", false);
if (isRemember) {
String account = pref.getString("account", "");
String password = pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (account.equals("admin") && password.equals("123456")) {
editor = pref.edit();
if (rememberPass.isChecked()) {
editor.putBoolean("remember_password", true);
editor.putString("account", account);
editor.putString("password", password);
} else {
editor.clear();
}
editor.commit();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginActivity.this,
"account or password is invalid",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
发送广播
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button forceOffline = (Button) findViewById(R.id.force_offline);
forceOffline.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
"com.example.broadcastbestpractice.FORCE_OFFLINE");
sendBroadcast(intent);
}
});
}
}
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button forceOffline = (Button) findViewById(R.id.force_offline);
forceOffline.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
"com.example.broadcastbestpractice.FORCE_OFFLINE");
sendBroadcast(intent);
}
});
}
}
广播接收器类
public class ForceOfflineReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle("Warning");
dialogBuilder
.setMessage("You are forced to be offline. Please try to login again.");
dialogBuilder.setCancelable(false);//对话框设置为不可取消
dialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCollector.finishAll();
Intent intent = new Intent(context, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//在广播接收其中必须加入加入一个标志
context.startActivity(intent);
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//设置类型 保证在接受器中可以弹出
alertDialog.show();
}
}
进行权限设置和注册
弹出一个系统级别的对话框,必须声明 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
并制定接受
<receiver android:name=".ForceOfflineReceiver" >
<intent-filter>
<action android:name="com.example.broadcastbestpractice.FORCE_OFFLINE" />
</intent-filter>
</receiver>