需求:(1)沉浸式状态栏;(2)使用广播监听网络状态;(3)动态申请用户权限;(4)ActivityManager管理器的添加和删除。以上几种需求,基本上每个Activity都需要。这样的话,一个一个加,想想都麻烦。
方案:创建一个自定义的Activity的抽象父类,让新加的Activity继承这个父类即可。
功能代码如下:
public abstract class BaseActivity extends AppCompatActivity {
private Context mContext;
private ActivityManager activityManager;
private NetWorkChangeReceiver netWorkChangeReceiver;
private RxPermissions rxPermissions;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//给系统状态栏设置颜色
if (Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
//需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//设置状态栏颜色
window.setStatusBarColor(getResources().getColor(R.color.colorDeepOrange));
}
//隐藏标题栏
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
mContext = this;
//活动管理器
activityManager = ActivityManager.getAppManager();
activityManager.addActivity(this);
//注册监听网络状态的广播
registerNetWorkChangeBroadcast();
//检查并申请用户权限
rxPermissions = new RxPermissions(this);
checkUserAllPermissions();
}
@Override
protected void onDestroy() {
//管理器中移除当前活动
activityManager.finishActivity(this);
//取消注册监听网络的广播
unregisterReceiver(netWorkChangeReceiver);
super.onDestroy();
}
/**
* 动态注册监听网络状态的广播
*/
private void registerNetWorkChangeBroadcast() {
netWorkChangeReceiver = new NetWorkChangeReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(netWorkChangeReceiver, intentFilter);
}
/**
* 申请用户权限
*/
private void checkUserAllPermissions() {
rxPermissions
.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.CAMERA)
.subscribe(permission -> {
if (permission.granted) {
} else if (permission.shouldShowRequestPermissionRationale) {
} else {
Toast.makeText(mContext, "部分权限已被禁用,您可以在手机设置中进行权限设置。", Toast.LENGTH_SHORT).show();
}
});
}
/**
* 基本数据初始化
*/
protected abstract void baseDataInit();
/**
* 绑定View
*/
protected abstract void bindView();
/**
* View添加监听事件
*/
protected abstract void viewsAddListener();
/**
* View基本数据初始化
*/
protected abstract void viewsDataInit();
}
PS:可根据自己需求,自行拓展。