package com.info.sn; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.hjq.permissions.OnPermission; import com.hjq.permissions.Permission; import com.hjq.permissions.XXPermissions; import com.info.sn.bean.UserInfo; import com.info.sn.jpush.ExampleUtil; import com.info.sn.jpush.LocalBroadcastManager; import com.info.sn.jpush.TagAliasOperatorHelper; import com.info.sn.network.api.HTTPInterface; import com.info.sn.service.MyDownloadService; import com.info.sn.utils.ApkUtils; import com.info.sn.utils.LogUtils; import com.info.sn.utils.SPUtils; import com.info.sn.utils.ToastUtil; import com.info.sn.utils.Utils; import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.FileCallback; import com.lzy.okgo.model.Progress; import com.lzy.okgo.model.Response; import java.io.File; import java.util.List; import java.util.Set; import cn.jpush.android.api.JPushInterface; import static com.info.sn.jpush.TagAliasOperatorHelper.ACTION_ADD; import static com.info.sn.jpush.TagAliasOperatorHelper.ACTION_CHECK; import static com.info.sn.jpush.TagAliasOperatorHelper.ACTION_CLEAN; import static com.info.sn.jpush.TagAliasOperatorHelper.ACTION_DELETE; import static com.info.sn.jpush.TagAliasOperatorHelper.ACTION_GET; import static com.info.sn.jpush.TagAliasOperatorHelper.ACTION_SET; import static com.info.sn.jpush.TagAliasOperatorHelper.TagAliasBean; import static com.info.sn.jpush.TagAliasOperatorHelper.sequence; public class MainActivity extends AppCompatActivity { public static final String REFRESHACTION = BuildConfig.APPLICATION_ID + ".REFRESH"; public static boolean isForeground = false; private ImageView imageView, exit; private TextView tv_note, tv_devsn, tv_username, tv_school, tv_grade, tv_version; private ConstraintLayout layout; private int DeviceInfo; private long mExitTime; private RefreshReceiver mRefreshReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } PackageManager pm = getPackageManager(); //后台为0可能传过来null pm.setApplicationEnabledSetting("com.info.sn", PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0); requestPermission(); registerMessageReceiver(); // used for receive msg registerRefreshReceiver(); String rid = JPushInterface.getRegistrationID(getApplicationContext()); if (!rid.isEmpty()) { ToastUtil.debugShow("RegId:" + rid); LogUtils.e("RegId", rid); onTagAliasAction(7); } else { // ToastUtil.show("Get registration fail, JPush init failed!"); // Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show(); } initView(); initData(); HTTPInterface.checkDevicesInfo(handler); HTTPInterface.checkUpdateByself(handler, this.getPackageName(), String.valueOf(BuildConfig.VERSION_CODE)); startService(new Intent(MainActivity.this, MyDownloadService.class)); } public void registerRefreshReceiver() { mRefreshReceiver = new RefreshReceiver(); IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(REFRESHACTION); registerReceiver(mRefreshReceiver, filter); } public class RefreshReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (REFRESHACTION.equals(intent.getAction())) { HTTPInterface.checkDevicesInfo(handler); } } } private void initView() { tv_note = findViewById(R.id.tv_note); imageView = findViewById(R.id.imageView); exit = findViewById(R.id.iv_exit); exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { exit(); } }); layout = findViewById(R.id.layout); layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { continuousClick(COUNTS, DURATION); } }); tv_devsn = findViewById(R.id.tv_devsn); tv_devsn.setText(Utils.getSerial()); tv_username = findViewById(R.id.tv_username); tv_school = findViewById(R.id.tv_school); tv_grade = findViewById(R.id.tv_grade); tv_version = findViewById(R.id.version); tv_version.setText(BuildConfig.VERSION_NAME); } final static int COUNTS = 4;// 点击次数 final static long DURATION = 1000;// 规定有效时间 long[] mHits = new long[COUNTS]; private void continuousClick(int count, long time) { //每次点击时,数组向前移动一位 System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1); //为数组最后一位赋值 mHits[mHits.length - 1] = SystemClock.uptimeMillis(); if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) { mHits = new long[COUNTS];//重新初始化数组 ToastUtil.show("正在检查更新"); HTTPInterface.checkUpdateByself(handler, this.getPackageName(), String.valueOf(BuildConfig.VERSION_CODE)); } } private void initData() { DeviceInfo = (int) SPUtils.get(this, "isLogined", 2); switch (DeviceInfo) { case 0: setImageAndText(imageView, "设备未绑定"); break; case 1: setImageAndText(imageView, "设备已绑定"); break; case 2: setImageAndText(imageView, "未经验证的设备,请联系客服"); break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { exit(); return true; } return super.onKeyDown(keyCode, event); } public void exit() { if ((System.currentTimeMillis() - mExitTime) > 2000) { ToastUtil.show("再按一次退出程序"); mExitTime = System.currentTimeMillis(); } else { finish(); } } private void setImageAndText(ImageView imageView, String text) { Bitmap bitmap = Utils.createQRImage(Utils.getSn(), 250, 250); imageView.setImageBitmap(bitmap); tv_note.setText(text); } private void setUserInfo(UserInfo userInfo) { String name = userInfo.getSn_name(); String school = userInfo.getSn_school(); String grade = userInfo.getSn_grade(); if (name == null || name.equals("")) { tv_username.setText("用户姓名:未设置"); } else { tv_username.setText(name); } if (school == null || school.equals("")) { tv_school.setText("学校:未设置"); } else { tv_school.setText(school); } if (grade == null || grade.equals("")) { tv_grade.setText("年级:未设置"); } else { tv_grade.setText(getGrade(grade)); } } private void setUserInfo() { tv_username.setText("未设置"); tv_school.setText("未设置"); tv_grade.setText("未设置"); tv_grade.setText("未设置"); } private String getGrade(String grade) { String s; switch (grade) { case "1": s = "一年级"; break; case "2": s = "二年级"; break; case "3": s = "三年级"; break; case "4": s = "四年级"; break; case "5": s = "五年级"; break; case "6": s = "六年级"; break; case "7": s = "初一"; break; case "8": s = "初二"; break; case "9": s = "初三"; break; case "10": s = "高一"; break; case "11": s = "高二"; break; case "12": s = "高三"; break; default: s = "一年级"; break; } return s; } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: SPUtils.put(MainActivity.this, "isLogined", 0); setImageAndText(imageView, "设备未绑定"); break; case 1: UserInfo userInfo = (UserInfo) msg.obj; SPUtils.put(MainActivity.this, "isLogined", 1); SPUtils.put(MainActivity.this, "member_id", userInfo.getMember_id()); SPUtils.put(MainActivity.this, "sn_id", userInfo.getId()); setUserInfo((UserInfo) msg.obj); setImageAndText(imageView, "设备已绑定"); break; case 2: SPUtils.put(MainActivity.this, "isLogined", 2); setImageAndText(imageView, "未经验证的设备,请联系客服"); break; case 300: Bundle bundle = (Bundle) msg.obj; getFile(bundle); break; case -200: ToastUtil.show("已是最新版本"); break; case -300: ToastUtil.show("网络连接失败,检查网络连接"); break; } } }; private void getFile(final Bundle bundle) { String url = bundle.getString("url"); final File path = new File(Environment.getExternalStoragePublicDirectory("Download") + "/Sninfo/"); path.mkdirs(); final File file = new File(Environment.getExternalStoragePublicDirectory("Download") + "/Sninfo/" + url.substring(url.lastIndexOf("/") + 1)); if (file.exists() && file.isFile()) { AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle("软件更新") .setIcon(R.mipmap.ic_launcher) .setCancelable(false) .setMessage("发现新版本,点击确定更新\n" + "更新内容:" + bundle.getString("content")) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ApkUtils.installApk(MainActivity.this, file); dialogInterface.dismiss(); } }); AlertDialog ad = builder.create(); ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失 ad.show(); } else { OkGo.get(url) .execute(new FileCallback("Sninfo/" + url.substring(url.lastIndexOf("/") + 1)) { @Override public void onSuccess(final Response response) { // Settings.System.putString(getApplicationContext().getContentResolver(), "qch_app_forbid", "com.baidu.video"); // ApkUtils.installApkInSilence(response.body().getAbsolutePath(), Launcher.this.getPackageName()); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this) .setTitle("软件更新") .setIcon(R.mipmap.ic_launcher) .setCancelable(false) .setMessage("发现新版本,点击确定更新\n" + "更新内容:" + bundle.getString("content")) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ApkUtils.installApk(MainActivity.this, response.body()); dialogInterface.dismiss(); } }); AlertDialog ad = builder.create(); ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失 ad.show(); Log.e("getFile", "download file successful,now installing"); } @Override public void onError(Response response) { super.onError(response); Log.e("getFile", "File download Failure" + response.getException()); } @Override public void downloadProgress(Progress progress) { super.downloadProgress(progress); Log.e("getFile", "已下载:" + progress.currentSize + ",总大小:" + progress.totalSize + ",进度:" + progress.fraction + ",当前网速:" + progress.speed); } }); } } private String[] permission = new String[]{ // Permission.SYSTEM_ALERT_WINDOW, // Permission.CAMERA, // Permission.READ_SMS, // Permission.RECEIVE_SMS, // Permission.SEND_SMS, Permission.REQUEST_INSTALL_PACKAGES, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, // Permission.READ_PHONE_STATE }; public void requestPermission() { XXPermissions.with(this) // 可设置被拒绝后继续申请,直到用户授权或者永久拒绝 .constantRequest() // 支持请求6.0悬浮窗权限8.0请求安装权限 //.permission(Permission.REQUEST_INSTALL_PACKAGES) // 不指定权限则自动获取清单中的危险权限 .permission(permission) .request(new OnPermission() { @Override public void hasPermission(List granted, boolean isAll) { if (isAll) { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "POStemp"; File file = new File(path); file.mkdirs(); } else { ToastUtil.show("需要授予所有权限才能正常使用本程序!"); } } @Override public void noPermission(List denied, boolean quick) { if (quick) { ToastUtil.show("被永久拒绝授权,请手动授予权限!"); //如果是被永久拒绝就跳转到应用权限系统设置页面 XXPermissions.gotoPermissionSettings(MainActivity.this); } else { ToastUtil.show("获取权限失败"); } } }); } public void onTagAliasAction(int i) { Set tags = null; String alias = null; int action = -1; boolean isAliasAction = false; switch (i) { //设置手机号码: case 0: // handleSetMobileNumber(); return; //增加tag case 1: // tags = getInPutTags(); if (tags == null) { return; } action = ACTION_ADD; break; //设置tag case 2: // tags = getInPutTags(); if (tags == null) { return; } action = ACTION_SET; break; //删除tag case 3: // tags = getInPutTags(); if (tags == null) { return; } action = ACTION_DELETE; break; //获取所有tag case 4: action = ACTION_GET; break; //清除所有tag case 5: action = ACTION_CLEAN; break; case 6: // tags = getInPutTags(); if (tags == null) { return; } action = ACTION_CHECK; break; //设置alias case 7: // alias = getInPutAlias(); alias = Utils.getSerial(); if (TextUtils.isEmpty(alias)) { return; } isAliasAction = true; action = ACTION_SET; break; //获取alias case 8: isAliasAction = true; action = ACTION_GET; break; //删除alias case 9: isAliasAction = true; action = ACTION_DELETE; break; default: return; } TagAliasBean tagAliasBean = new TagAliasBean(); tagAliasBean.action = action; sequence++; if (isAliasAction) { tagAliasBean.alias = alias; } else { tagAliasBean.tags = tags; } tagAliasBean.isAliasAction = isAliasAction; TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean); } //for receive customer msg from jpush server private MessageReceiver mMessageReceiver; public static final String MESSAGE_RECEIVED_ACTION = "com.info.sn.MESSAGE_RECEIVED_ACTION"; public static final String KEY_TITLE = "title"; public static final String KEY_MESSAGE = "message"; public static final String KEY_EXTRAS = "extras"; public void registerMessageReceiver() { mMessageReceiver = new MessageReceiver(); IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(MESSAGE_RECEIVED_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter); } public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) { String messge = intent.getStringExtra(KEY_MESSAGE); String extras = intent.getStringExtra(KEY_EXTRAS); StringBuilder showMsg = new StringBuilder(); showMsg.append(KEY_MESSAGE + " : " + messge + "\n"); if (!ExampleUtil.isEmpty(extras)) { showMsg.append(KEY_EXTRAS + " : " + extras + "\n"); } // setCostomMsg(showMsg.toString()); } } catch (Exception e) { } } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mRefreshReceiver); } }