import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.epuxun.drink.http.HttpUpdateService;
import java.io.File;
import java.util.Objects;
public abstract class BaseActivity extends AppCompatActivity {
private LoadDialog loadDialog;
private ConnectivityManager mConnectivityManager;
private NetworkCallbackImpl networkCallback;
private OnMeasureSizeCallback onMeasureSizeCallback;
private View[] views;
private BroadcastReceiver receiver;
//下载的apk的文件名
private final String apkName = "drink.apk";
/**
* 布局文件id
*/
protected abstract int attachLayoutRes();
/**
* 初始化 View
*/
public abstract void initView();
/**
* 初始化数据
*/
public abstract void initData();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//防止截屏攻击风险
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
//仿系统自带短信界面 可以完全漂浮在软键盘之上
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onCreate(savedInstanceState);
setContentView(attachLayoutRes());
mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
initView();
initData();
initTipView();
}
/**
* 初始化提示控件
*/
private void initTipView() {
//加载Dialog
loadDialog = LoadDialog.getInstance();
loadDialog.setCancelable(false);
}
/**
* 显示加载Dialog
*/
public void showLoadDialog() {
loadDialog.show(getSupportFragmentManager(), getLocalClassName());
}
/**
* 关闭加载Dialog
*/
public void dismissLoadDialog() {
loadDialog.dismiss();
}
/**
* 获取控件大小接口
*/
public interface OnMeasureSizeCallback {
void getMeasureSize(View view);
}
/**
* 设置获取控件大小的回调
*/
public void setOnMeasureSizeCallback(OnMeasureSizeCallback onMeasureSizeCallback, View... views) {
this.onMeasureSizeCallback = onMeasureSizeCallback;
this.views = views;
}
/**
* 获取焦点时调用获取控件大小的回调
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && onMeasureSizeCallback != null) {
for (View view : views) {
onMeasureSizeCallback.getMeasureSize(view);
}
}
}
/**
* 重写startActivity
*
* @param clz 跳转页面的class
*/
public void startActivity(Class> clz) {
Intent intent = new Intent(this, clz);
startActivity(intent);
enterTransitionAnim();
}
/**
* 重写startActivity
*
* @param clz 跳转页面的class
* @param bundle 携带的数据
*/
public void startActivity(Class> clz, @NonNull Bundle bundle) {
Intent intent = new Intent(this, clz);
intent.putExtras(bundle);
startActivity(intent);
enterTransitionAnim();
}
public void startActivityForResult(Class> clz, int requestCode) {
Intent intent = new Intent(this, clz);
startActivityForResult(intent, requestCode);
enterTransitionAnim();
}
public void startActivityForResult(Class> clz, int requestCode, @NonNull Bundle bundle) {
Intent intent = new Intent(this, clz);
startActivityForResult(intent, requestCode, bundle);
enterTransitionAnim();
}
public Bundle getIntentBundle() {
return getIntent().getExtras();
}
/**
* 注册本地广播,关闭Activity时会自动注销本地广播
*/
public void registerReceiver(BroadcastReceiver receiver, String... actions) {
this.receiver = receiver;
IntentFilter filter = new IntentFilter();
for (String action : actions) {
filter.addAction(action);
}
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}
/**
* 自动注销本地广播
*/
private void unregisterReceiver() {
if (receiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
}
/**
* 开启apk下载服务
*/
public void updateApk(String url, String actions) {
HttpUpdateService updateService = new HttpUpdateService();
Intent intent = new Intent();
intent.putExtra("apkName", apkName);
intent.putExtra("url", url);
intent.putExtra("actions", actions);
updateService.enqueueWork(this, intent);
}
/**
* 安装apk Dialog
*/
public void showInstallationDialog(int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (getPackageManager().canRequestPackageInstalls()) {
showDialogN();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("检测到新版本")
.setMessage("安装新版本需要打开未知来源权限,请去设置中开启权限")
.setPositiveButton("设置", (dialog, which) -> {
Uri selfPackageUri = Uri.parse("package:" + getPackageName());
Intent intentPermission = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, selfPackageUri);
//8.0以上跳转至“安装未知应用”权限界面,引导用户开启权限
startActivityForResult(intentPermission, requestCode);
})
.setNegativeButton("取消", (dialog, which) -> {
})
.setCancelable(false)
.show();
}
} else {
showDialogN();
}
}
/**
* 7.0以下新版本提示
*/
private void showDialogN() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示")
.setMessage("检测到新版本是否更新")
.setPositiveButton("更新", (dialog, which) -> installationN())
.setNegativeButton("取消", (dialog, which) -> {
})
.setCancelable(false)
.show();
}
/**
* 7.0以下安装
*/
private void installationN() {
String path = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath();
File file = new File(path, apkName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//判读版本是否在7.0以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
String authority = getPackageName() + ".fileProvider";
//生成File URI
Uri apkUri = FileProvider.getUriForFile(this, authority, file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
//Uri.fromFile(file) 生成File URI
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
startActivity(intent);
}
/**
* 检测网络是否连接
* 如果未注册[registerNetworkMonitoring] 会使用isNetworkConnectedLOLLIPOP
*/
public boolean isNetworkConnected() {
if (networkCallback != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return networkCallback.isNetworkConnected();
}
return isNetworkConnectedLOLLIPOP();
}
/**
* 5.0以下检测网络是否连接
*/
private boolean isNetworkConnectedLOLLIPOP() {
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
return false;
}
/**
* 注册网络监听
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void registerNetworkMonitoring() {
networkCallback = NetworkCallbackImpl.getInstance();
if (networkCallback != null) {
//需要 权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mConnectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest.Builder builder = new NetworkRequest.Builder();
mConnectivityManager.registerNetworkCallback(builder.build(), networkCallback);
}
}
}
/**
* 注销网络监听
*/
private void unregisterNetworkMonitoring() {
if (networkCallback != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mConnectivityManager.unregisterNetworkCallback(networkCallback);
}
}
/**
* 进入Activity过渡动画
*/
private void enterTransitionAnim() {
overridePendingTransition(android.R.anim.fade_out, android.R.anim.fade_in);
}
/**
* 退出Activity过渡动画
*/
private void quitTransitionAnim() {
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
@Override
public void onBackPressed() {
super.onBackPressed();
// Fragment 逐个出栈
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
@Override
public void finish() {
super.finish();
quitTransitionAnim();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterNetworkMonitoring();
unregisterReceiver();
}
// /**
// * 沉浸状态栏
// * 重写onWindowFocusChanged方法实现沉浸模式
// */
// @Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// if (hasFocus && Build.VERSION.SDK_INT >= 21) {
// View decorView = getWindow().getDecorView();
// decorView.setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_FULLSCREEN
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
// getWindow().setNavigationBarColor(Color.TRANSPARENT);//设置虚拟按键透明
// getWindow().setStatusBarColor(Color.TRANSPARENT);//设置状态栏透明
// } else if (hasFocus && Build.VERSION.SDK_INT >= 19) {
// View decorView = getWindow().getDecorView();
// decorView.setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_FULLSCREEN
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
// }
// }
}
public class LoadDialog extends DialogFragment {
private static class LoadDialogHolder {
private static final LoadDialog INSTANCE = new LoadDialog();
}
private LoadDialog (){}
public static LoadDialog getInstance() {
return LoadDialog.LoadDialogHolder.INSTANCE;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_progress_bar,container,false);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
private static class NetworkCallbackImplHolder {
private static final NetworkCallbackImpl INSTANCE = new NetworkCallbackImpl();
}
private NetworkCallbackImpl (){}
public static NetworkCallbackImpl getInstance() {
return NetworkCallbackImplHolder.INSTANCE;
}
private boolean isNetworkConnected;
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
//网络已连接
isNetworkConnected = true;
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
//网络已断开
isNetworkConnected = false;
}
@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {//网络类型为wifi
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {//蜂窝网络
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)){//蓝牙
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){//以太网
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)){//
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE)){//Wi-Fi Aware
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_LOWPAN)){//LoWPAN
} else { //其他网络
}
}
}
/**
* 判断网络是否连接
*/
public boolean isNetworkConnected(){
return isNetworkConnected;
}
}
获取控件大小示例
ImageView ancient = findViewById(R.id.ancient);
Toolbar toolbar = findViewById(R.id.toolbar);
setOnMeasureSizeCallback(new OnMeasureSizeCallback() {
@Override
public void getMeasureSize(View view) {
switch (view.getId()) {
case R.id.ancient:
case R.id.toolbar:
showLongToast("宽度:" + view.getMeasuredWidth() + "高度:" + view.getMeasuredHeight());
break;
}
}
},ancient,toolbar);