This commit is contained in:
2019-12-25 11:28:10 +08:00
commit cdd3d43ae3
87 changed files with 16373 additions and 0 deletions

View File

@@ -0,0 +1,379 @@
package com.info.sn;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
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.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;
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.LogUtils;
import com.info.sn.utils.SPUtils;
import com.info.sn.utils.ToastUtil;
import com.info.sn.utils.Utils;
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 boolean isForeground = false;
private ImageView imageView;
private TextView tv_note, tv_devsn, tv_username, tv_school, tv_grade, tv_version;
private int DeviceInfo;
@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
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);
startService(new Intent(MainActivity.this, MyDownloadService.class));
}
private void initView() {
tv_note = (TextView) findViewById(R.id.tv_note);
imageView = (ImageView) findViewById(R.id.imageView);
tv_devsn = (TextView) findViewById(R.id.tv_devsn);
tv_devsn.setText("设备SN:" + Utils.getSerial());
tv_username = (TextView) findViewById(R.id.tv_username);
tv_school = (TextView) findViewById(R.id.tv_school);
tv_grade = (TextView) findViewById(R.id.tv_grade);
tv_version = findViewById(R.id.version);
tv_version.setText("版本:"+ BuildConfig.VERSION_NAME);
}
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;
}
}
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 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;
}
}
};
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<String> 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<String> denied, boolean quick) {
if (quick) {
ToastUtil.show("被永久拒绝授权,请手动授予权限!");
//如果是被永久拒绝就跳转到应用权限系统设置页面
XXPermissions.gotoPermissionSettings(MainActivity.this);
} else {
ToastUtil.show("获取权限失败");
}
}
});
}
public void onTagAliasAction(int i) {
Set<String> 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.example.jpushdemo.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) {
}
}
}
}

View File

@@ -0,0 +1,447 @@
package com.info.sn;
import android.app.ActivityManager;
import android.app.Application;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.blankj.utilcode.util.NetworkUtils;
import com.info.sn.network.api.HTTPInterface;
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.lzy.okgo.OkGo;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import cn.jpush.android.api.CustomMessage;
public class MyApplication extends Application implements NetworkUtils.OnNetworkStatusChangedListener {
public static Context context;
private static MyApplication app;
@Override
public void onCreate() {
super.onCreate();
app = this;
ToastUtil.init(this);
context = getApplicationContext();
ToastUtil.init(this);
OkGo.getInstance().init(this);
NetworkUtils.registerNetworkStatusChangedListener(this);
Aria.init(this);
Aria.download(this).register();
Aria.download(this).resumeAllTask();
}
@Override
public void onTerminate() {
super.onTerminate();
NetworkUtils.unregisterNetworkStatusChangedListener(this);
}
public static MyApplication getInstance() {
return app;
}
public static Context getAppContext() {
if (context == null) {
context = getAppContext();
}
return context;
}
public static String getTaskPackname() {
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
// LogUtils.e("TAG", "Current App in foreground is: " + currentApp);
return currentApp;
}
/**
* 实时获取电量
*/
public static int getSystemBattery() {
int level = 0;
Intent batteryInfoIntent = context.getApplicationContext().registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
level = batteryInfoIntent.getIntExtra("level", 0);
int batterySum = batteryInfoIntent.getIntExtra("scale", 100);
int percentBattery = 100 * level / batterySum;
LogUtils.i("getSystemBattery", "level = " + level);
LogUtils.i("getSystemBattery", "batterySum = " + batterySum);
LogUtils.i("getSystemBattery", "percent is " + percentBattery + "%");
return percentBattery;
}
//定义接收极光推送消息的类型。
//1.获取设备在线信息
// 2.获取当前正在运行得应用和电量
// 3.数据线传输管控
// 4.TF卡管控
// 5.蓝牙管控
// 6.浏览器上网管控
// 7.应用联网管控
// 8.应用锁管控
// 9.强制安装应用
// 10.强制卸载应用
private static final String JIGUANG_GET_DRIVELINE = "1";
private static final String JIGUANG_GET_STARTTIME = "2";
private static final String JIGUANG_USB_STATE = "3";
private static final String JIGUANG_TFCARD_STATE = "4";
private static final String JIGUANG_BLUETOOTH_STATE = "5";
private static final String JIGUANG_BROWSER_URLPATH = "6";
private static final String JIGUANG_APP_NETWORKSTATE = "7";
private static final String JIGUANG_APP_LOCKEDSTATE = "8";
private static final String JIGUANG_FORCE_INSTALLAPK = "9";
private static final String JIGUANG_FORCE_UNINSTALLAPK = "10";
synchronized public void manageCustomMessage(CustomMessage customMessage) {
String sn_id = (String) SPUtils.get(context, "sn_id", "-1");
String member_id = (String) SPUtils.get(context, "member_id", "-1");
if (customMessage == null) {
LogUtils.e("jiguang", "customMessage is NULL");
} else {
String MESSAGE = customMessage.message;
//MESSAGE用作判断
String TITLE = customMessage.title;
String CONTENT_TYPE = customMessage.contentType;
String EXTRA = customMessage.extra;
LogUtils.e("EXTRA", EXTRA);
switch (MESSAGE) {
case JIGUANG_GET_DRIVELINE:
HTTPInterface.getDriveState(member_id, sn_id);
break;
case JIGUANG_GET_STARTTIME:
sendStartTime(EXTRA);
break;
case JIGUANG_USB_STATE:
setUsbState(EXTRA);
break;
case JIGUANG_TFCARD_STATE:
setTfcardState(EXTRA);
break;
case JIGUANG_BLUETOOTH_STATE:
setBluetoothState(EXTRA);
break;
case JIGUANG_BROWSER_URLPATH:
setBrowserUrlpath(EXTRA);
break;
case JIGUANG_APP_NETWORKSTATE:
setAppNetworkstate(EXTRA);
break;
case JIGUANG_APP_LOCKEDSTATE:
setAppLockedstate(EXTRA);
break;
case JIGUANG_FORCE_INSTALLAPK:
intallApk(EXTRA);
break;
case JIGUANG_FORCE_UNINSTALLAPK:
unintallApk(EXTRA);
break;
}
}
}
synchronized private void defaults(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String packageName = extra.getString("package");
int is_network = extra.getInt("is_network");
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("defaults", e.getMessage());
}
} else {
ToastUtil.debugShow("defaults jsonArray is NULL");
}
}
//USB数据功能管控
//仅充电usb_charge
//MTP模式usb_mtp
//Midi模式usb_midi
synchronized public static void sendStartTime() {
int battery = getSystemBattery();
HTTPInterface.sendStartTime(getAppContext(), 0, getTaskPackname(), battery, "111");
}
synchronized private void sendStartTime(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String random = extra.getString("random");
int battery = getSystemBattery();
HTTPInterface.sendStartTime(getAppContext(), 0, getTaskPackname(), battery, random);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
synchronized private void setUsbState(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
int is_dataline = extra.getInt("is_dataline");
if (is_dataline == 1) {
boolean qch_usb_choose = Settings.System.putString(getContentResolver(), "qch_usb_choose", "usb_charge");
LogUtils.e("setUsbState:", Settings.System.getString(getContentResolver(), "qch_usb_choose"));
} else {
boolean qch_usb_choose = Settings.System.putString(getContentResolver(), "qch_usb_choose", "usb_mtp");
LogUtils.e("setUsbState:", Settings.System.getString(getContentResolver(), "qch_usb_choose"));
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setUsbState", e.getMessage());
}
} else {
ToastUtil.debugShow("setUsbState jsonArray is NULL");
}
}
synchronized private void setTfcardState(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
int is_tf = extra.getInt("is_tf");
boolean qch_sdcard_forbid_on = Settings.System.putInt(getContentResolver(), "qch_sdcard_forbid_on", is_tf);
if (qch_sdcard_forbid_on) {
LogUtils.e("setTfcardState:", Settings.System.getString(getContentResolver(), "qch_sdcard_forbid_on"));
} else {
ToastUtil.debugShow("setTfcardState failed,state:" + is_tf);
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setTfcardState", e.getMessage());
}
} else {
ToastUtil.debugShow("setTfcardState jsonArray is NULL");
}
}
synchronized private void setBluetoothState(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
int is_bluetooth = extra.getInt("is_bluetooth");
boolean qch_bt_forbid_on = Settings.System.putInt(getContentResolver(), "qch_bt_forbid_on", is_bluetooth);
if (qch_bt_forbid_on) {
LogUtils.e("setBluetoothState:", Settings.System.getString(getContentResolver(), "qch_bt_forbid_on"));
} else {
ToastUtil.debugShow("setBluetoothState failed,state:" + is_bluetooth);
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setBluetoothState", e.getMessage());
}
} else {
ToastUtil.debugShow("setBluetoothState jsonArray is NULL");
}
}
synchronized private void setBrowserUrlpath(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String browser = extra.getString("browser");
boolean setBrowserUrlpath = Settings.System.putString(getContentResolver(), "DeselectBrowserArray", browser);
LogUtils.e("setBrowserUrlpath:", String.valueOf(setBrowserUrlpath));
if (setBrowserUrlpath) {
LogUtils.e("getBrowserUrlpath:", Settings.System.getString(getContentResolver(), "DeselectBrowserArray"));
} else {
ToastUtil.debugShow("setBrowserUrlpath failed,url:" + browser);
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setBrowserUrlpath", e.getMessage());
}
} else {
boolean setBrowserUrlpath = Settings.System.putString(getContentResolver(), "DeselectBrowserArray", "invalid");
ToastUtil.debugShow("setBrowserUrlpath jsonArray is NULL,set default: " + setBrowserUrlpath);
}
}
synchronized private void setAppNetworkstate(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String package0 = extra.getString("package0");
String package1 = extra.getString("package1");
if (package0.length() != 0) {
boolean qch_jgy_network_disallow = Settings.System.putString(getContentResolver(), "qch_jgy_network_allow", package0);
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_disallow + ":" + Settings.System.getString(getContentResolver(), "qch_jgy_network_allow"));
} else {
boolean qch_jgy_network_disallow = Settings.System.putString(getContentResolver(), "qch_jgy_network_allow", "invalid");
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_disallow + ":" + Settings.System.getString(getContentResolver(), "qch_jgy_network_allow"));
}
if (package1.length() != 0) {
boolean qch_jgy_network_disallow = Settings.System.putString(getContentResolver(), "qch_jgy_network_disallow", package1);
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_disallow + ":" + Settings.System.getString(getContentResolver(), "qch_jgy_network_disallow"));
} else {
boolean qch_jgy_network_disallow = Settings.System.putString(getContentResolver(), "qch_jgy_network_disallow", "invalid");
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_disallow + ":" + Settings.System.getString(getContentResolver(), "qch_jgy_network_disallow"));
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setAppNetworkstate", e.getMessage());
}
} else {
ToastUtil.debugShow("setAppNetworkstate jsonArray is NULL");
}
}
synchronized private void setAppLockedstate(String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String packageName = extra.getString("package");
int is_lock = extra.getInt("is_lock");
ToastUtil.debugShow("收到应用锁管控消息:包名" + packageName + "is_lock_state:" + is_lock);
PackageManager pm = getPackageManager();
//后台为0可能传过来null
if (is_lock == 1) {
pm.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
} else {
pm.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setAppLockedstate", e.getMessage());
}
} else {
ToastUtil.debugShow("setAppLockedstate jsonArray is NULL");
}
}
//静默安装应用使用okgo断网会出现问题等待修改使用aria
synchronized private void intallApk(String jsondata) {
try {
JSONObject extra = new JSONObject(jsondata);
final String packages = extra.getString("package");
ToastUtil.debugShow("收到应用安装消息:包名" + packages);
String url = extra.getString("url");
File file = new File(Environment.getExternalStoragePublicDirectory("Download") + "/Sninfo/apk");
file.mkdirs();
Aria.download(this).load(url).setFilePath(file.getAbsolutePath() + "/" + packages + ".apk").ignoreFilePathOccupy().setExtendField(packages).create();
// OkGo.<File>get(url)
// .execute(new FileCallback() {
// @Override
// public void onSuccess(Response<File> response) {
//// Settings.System.putString(getApplicationContext().getContentResolver(), "qch_app_forbid", "com.baidu.video");
// ApkUtils.installApkInSilence(response.body().getAbsolutePath(), packages);
// LogUtils.e("onSuccess", "download file successful,now installing");
// }
//
// @Override
// public void onError(Response<File> response) {
// super.onError(response);
// LogUtils.e("manageCustomMessage", "File download Failure");
// }
//
// @Override
// public void downloadProgress(Progress progress) {
// super.downloadProgress(progress);
// LogUtils.e("downloadProgress", "已下载:" + progress.currentSize + ",总大小:" + progress.totalSize + ",进度:" + progress.fraction + ",当前网速:" + progress.speed);
// }
// });
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("intallApk", e.getMessage());
}
}
synchronized private void unintallApk(String json) {
String sn_id = (String) SPUtils.get(context, "sn_id", "-1");
try {
JSONObject object = new JSONObject(json);
String packageName = object.getString("package");
ToastUtil.debugShow("收到应用卸载消息:包名" + packageName);
if (!packageName.equals("") && !packageName.equals(getApplicationContext().getPackageName())) {
if (!ApkUtils.isAvailable(getApplicationContext(), packageName)) {
HTTPInterface.setAppuninstallInfo(sn_id, packageName);
} else {
ApkUtils.deleteApkInSilence(packageName);
}
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("unintallApk", e.getMessage());
}
}
@Override
public void onDisconnected() {
LogUtils.e("onDisconnected", "网络断开");
}
@Override
public void onConnected(NetworkUtils.NetworkType networkType) {
Aria.download(this).resumeAllTask();
LogUtils.e("onConnected", "网络连接");
}
//在这里处理任务执行中的状态,如进度进度条的刷新
@Download.onTaskRunning
protected void running(DownloadTask task) {
Log.e("aria running", task.getState() + "--" + task.getPercent() + "--" + task.getExtendField());
}
@Download.onTaskComplete
void taskComplete(DownloadTask task) {
//在这里处理任务完成的状态
ApkUtils.installApkInSilence(task.getFilePath(), task.getExtendField());
}
}

View File

@@ -0,0 +1,6 @@
package com.info.sn.bean;
public class MessageWhat {
public static int CODE_SUCCESSFUL = 200;
}

View File

@@ -0,0 +1,124 @@
package com.info.sn.bean;
import java.io.Serializable;
public class UserInfo implements Serializable {
private String id;
private String sn_value;
private String sn_name;
private String sn_phone;
private String sn_grade;
private String sn_app;
private String sn_area;
private String member_id;
private String is_delete;
private String is_reset;
private String is_lock;
private String sn_school;
private String createtime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSn_value() {
return sn_value;
}
public void setSn_value(String sn_value) {
this.sn_value = sn_value;
}
public String getSn_name() {
return sn_name;
}
public void setSn_name(String sn_name) {
this.sn_name = sn_name;
}
public String getSn_phone() {
return sn_phone;
}
public void setSn_phone(String sn_phone) {
this.sn_phone = sn_phone;
}
public String getSn_grade() {
return sn_grade;
}
public void setSn_grade(String sn_grade) {
this.sn_grade = sn_grade;
}
public String getSn_app() {
return sn_app;
}
public void setSn_app(String sn_app) {
this.sn_app = sn_app;
}
public String getSn_area() {
return sn_area;
}
public void setSn_area(String sn_area) {
this.sn_area = sn_area;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getIs_delete() {
return is_delete;
}
public void setIs_delete(String is_delete) {
this.is_delete = is_delete;
}
public String getIs_reset() {
return is_reset;
}
public void setIs_reset(String is_reset) {
this.is_reset = is_reset;
}
public String getIs_lock() {
return is_lock;
}
public void setIs_lock(String is_lock) {
this.is_lock = is_lock;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getSn_school() {
return sn_school;
}
public void setSn_school(String sn_school) {
this.sn_school = sn_school;
}
}

View File

@@ -0,0 +1,22 @@
package com.info.sn.jpush;
import android.app.Application;
import cn.jpush.android.api.JPushInterface;
/**
* For developer startup JPush SDK
*
* 一般建议在自定义 Application 类里初始化。也可以在主 Activity 里。
*/
public class ExampleApplication extends Application {
private static final String TAG = "JIGUANG-Example";
@Override
public void onCreate() {
Logger.d(TAG, "[ExampleApplication] onCreate");
super.onCreate();
JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
JPushInterface.init(this); // 初始化 JPush
}
}

View File

@@ -0,0 +1,133 @@
package com.info.sn.jpush;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.jpush.android.api.JPushInterface;
public class ExampleUtil {
public static final String PREFS_NAME = "JPUSH_EXAMPLE";
public static final String PREFS_DAYS = "JPUSH_EXAMPLE_DAYS";
public static final String PREFS_START_TIME = "PREFS_START_TIME";
public static final String PREFS_END_TIME = "PREFS_END_TIME";
public static final String KEY_APP_KEY = "JPUSH_APPKEY";
public static boolean isEmpty(String s) {
if (null == s)
return true;
if (s.length() == 0)
return true;
if (s.trim().length() == 0)
return true;
return false;
}
/**
* 只能以 “+” 或者 数字开头;后面的内容只能包含 “-” 和 数字。
* */
private final static String MOBILE_NUMBER_CHARS = "^[+0-9][-0-9]{1,}$";
public static boolean isValidMobileNumber(String s) {
if(TextUtils.isEmpty(s)) return true;
Pattern p = Pattern.compile(MOBILE_NUMBER_CHARS);
Matcher m = p.matcher(s);
return m.matches();
}
// 校验Tag Alias 只能是数字,英文字母和中文
public static boolean isValidTagAndAlias(String s) {
Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");
Matcher m = p.matcher(s);
return m.matches();
}
// 取得AppKey
public static String getAppKey(Context context) {
Bundle metaData = null;
String appKey = null;
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
if (null != ai)
metaData = ai.metaData;
if (null != metaData) {
appKey = metaData.getString(KEY_APP_KEY);
if ((null == appKey) || appKey.length() != 24) {
appKey = null;
}
}
} catch (NameNotFoundException e) {
}
return appKey;
}
// 取得版本号
public static String GetVersion(Context context) {
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return manager.versionName;
} catch (NameNotFoundException e) {
return "Unknown";
}
}
public static void showToast(final String toast, final Context context)
{
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
// Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
}
public static boolean isConnected(Context context) {
ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conn.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
public static String getImei(Context context, String imei) {
String ret = null;
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
ret = telephonyManager.getDeviceId();
} catch (Exception e) {
Logger.e(ExampleUtil.class.getSimpleName(), e.getMessage());
}
if (isReadableASCII(ret)){
return ret;
} else {
return imei;
}
}
private static boolean isReadableASCII(CharSequence string){
if (TextUtils.isEmpty(string)) return false;
try {
Pattern p = Pattern.compile("[\\x20-\\x7E]+");
return p.matcher(string).matches();
} catch (Throwable e){
return true;
}
}
public static String getDeviceId(Context context) {
return JPushInterface.getUdid(context);
}
}

View File

@@ -0,0 +1,263 @@
package com.info.sn.jpush;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* Created by efan on 2017/4/14.
*/
public final class LocalBroadcastManager {
private static final String TAG = "JIGUANG-Example";
private static final boolean DEBUG = false;
private final Context mAppContext;
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers = new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
private final HashMap<String, ArrayList<ReceiverRecord>> mActions = new HashMap<String, ArrayList<ReceiverRecord>> ();
private final ArrayList<BroadcastRecord> mPendingBroadcasts = new ArrayList<BroadcastRecord>();
static final int MSG_EXEC_PENDING_BROADCASTS = 1;
private final Handler mHandler;
private static final Object mLock = new Object();
private static LocalBroadcastManager mInstance;
public static LocalBroadcastManager getInstance(Context context) {
Object var1 = mLock;
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}
private LocalBroadcastManager(Context context) {
this.mAppContext = context;
this.mHandler = new Handler(context.getMainLooper()) {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
LocalBroadcastManager.this.executePendingBroadcasts();
break;
default:
super.handleMessage(msg);
}
}
};
}
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
HashMap var3 = this.mReceivers;
synchronized (this.mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
ArrayList filters = (ArrayList) this.mReceivers.get(receiver);
if (filters == null) {
filters = new ArrayList(1);
this.mReceivers.put(receiver, filters);
}
filters.add(filter);
for (int i = 0; i < filter.countActions(); ++i) {
String action = filter.getAction(i);
ArrayList entries = (ArrayList) this.mActions.get(action);
if (entries == null) {
entries = new ArrayList(1);
this.mActions.put(action, entries);
}
entries.add(entry);
}
}
}
public void unregisterReceiver(BroadcastReceiver receiver) {
HashMap var2 = this.mReceivers;
synchronized (this.mReceivers) {
ArrayList filters = (ArrayList) this.mReceivers.remove(receiver);
if (filters != null) {
for (int i = 0; i < filters.size(); ++i) {
IntentFilter filter = (IntentFilter) filters.get(i);
for (int j = 0; j < filter.countActions(); ++j) {
String action = filter.getAction(j);
ArrayList receivers = (ArrayList) this.mActions.get(action);
if (receivers != null) {
for (int k = 0; k < receivers.size(); ++k) {
if (((ReceiverRecord) receivers.get(k)).receiver == receiver) {
receivers.remove(k);
--k;
}
}
if (receivers.size() <= 0) {
this.mActions.remove(action);
}
}
}
}
}
}
}
public boolean sendBroadcast(Intent intent) {
HashMap var2 = this.mReceivers;
synchronized (this.mReceivers) {
String action = intent.getAction();
String type = intent.resolveTypeIfNeeded(this.mAppContext.getContentResolver());
Uri data = intent.getData();
String scheme = intent.getScheme();
Set categories = intent.getCategories();
boolean debug = (intent.getFlags() & 8) != 0;
if (debug) {
Logger.v("LocalBroadcastManager", "Resolving type " + type + " scheme " + scheme + " of intent " + intent);
}
ArrayList entries = (ArrayList) this.mActions.get(intent.getAction());
if (entries != null) {
if (debug) {
Logger.v("LocalBroadcastManager", "Action list: " + entries);
}
ArrayList receivers = null;
int i;
for (i = 0; i < entries.size(); ++i) {
ReceiverRecord receiver = (ReceiverRecord) entries.get(i);
if (debug) {
Logger.v("LocalBroadcastManager", "Matching against filter " + receiver.filter);
}
if (receiver.broadcasting) {
if (debug) {
Logger.v("LocalBroadcastManager", " Filter\'s target already added");
}
} else {
int match = receiver.filter.match(action, type, scheme, data, categories, "LocalBroadcastManager");
if (match >= 0) {
if (debug) {
Logger.v("LocalBroadcastManager", " Filter matched! match=0x" + Integer.toHexString(match));
}
if (receivers == null) {
receivers = new ArrayList();
}
receivers.add(receiver);
receiver.broadcasting = true;
} else if (debug) {
String reason;
switch (match) {
case -4:
reason = "category";
break;
case -3:
reason = "action";
break;
case -2:
reason = "data";
break;
case -1:
reason = "type";
break;
default:
reason = "unknown reason";
}
Logger.v("LocalBroadcastManager", " Filter did not match: " + reason);
}
}
}
if (receivers != null) {
for (i = 0; i < receivers.size(); ++i) {
((ReceiverRecord) receivers.get(i)).broadcasting = false;
}
this.mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
if (!this.mHandler.hasMessages(1)) {
this.mHandler.sendEmptyMessage(1);
}
return true;
}
}
return false;
}
}
public void sendBroadcastSync(Intent intent) {
if (this.sendBroadcast(intent)) {
this.executePendingBroadcasts();
}
}
private void executePendingBroadcasts() {
while (true) {
BroadcastRecord[] brs = null;
HashMap i = this.mReceivers;
synchronized (this.mReceivers) {
int br = this.mPendingBroadcasts.size();
if (br <= 0) {
return;
}
brs = new BroadcastRecord[br];
this.mPendingBroadcasts.toArray(brs);
this.mPendingBroadcasts.clear();
}
for (int var6 = 0; var6 < brs.length; ++var6) {
BroadcastRecord var7 = brs[var6];
for (int j = 0; j < var7.receivers.size(); ++j) {
((ReceiverRecord) var7.receivers.get(j)).receiver.onReceive(this.mAppContext, var7.intent);
}
}
}
}
private static class BroadcastRecord {
final Intent intent;
final ArrayList<ReceiverRecord> receivers;
BroadcastRecord(Intent _intent, ArrayList<ReceiverRecord> _receivers) {
this.intent = _intent;
this.receivers = _receivers;
}
}
private static class ReceiverRecord {
final IntentFilter filter;
final BroadcastReceiver receiver;
boolean broadcasting;
ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) {
this.filter = _filter;
this.receiver = _receiver;
}
public String toString() {
StringBuilder builder = new StringBuilder(128);
builder.append("Receiver{");
builder.append(this.receiver);
builder.append(" filter=");
builder.append(this.filter);
builder.append("}");
return builder.toString();
}
}
}

View File

@@ -0,0 +1,40 @@
package com.info.sn.jpush;
import android.util.Log;
/**
* Created by efan on 2017/4/13.
*/
public class Logger {
//设为false关闭日志
private static final boolean LOG_ENABLE = true;
public static void i(String tag, String msg){
if (LOG_ENABLE){
Log.i(tag, msg);
}
}
public static void v(String tag, String msg){
if (LOG_ENABLE){
Log.v(tag, msg);
}
}
public static void d(String tag, String msg){
if (LOG_ENABLE){
Log.d(tag, msg);
}
}
public static void w(String tag, String msg){
if (LOG_ENABLE){
Log.w(tag, msg);
}
}
public static void e(String tag, String msg){
if (LOG_ENABLE){
Log.e(tag, msg);
}
}
}

View File

@@ -0,0 +1,47 @@
package com.info.sn.jpush;
import android.content.Context;
import com.info.sn.MyApplication;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.service.JPushMessageReceiver;
/**
* 自定义JPush message 接收器,包括操作tag/alias的结果返回(仅仅包含tag/alias新接口部分)
*/
public class MyJPushMessageReceiver extends JPushMessageReceiver {
@Override
public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
TagAliasOperatorHelper.getInstance().onTagOperatorResult(context, jPushMessage);
super.onTagOperatorResult(context, jPushMessage);
}
@Override
public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context, jPushMessage);
super.onCheckTagOperatorResult(context, jPushMessage);
}
@Override
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context, jPushMessage);
super.onAliasOperatorResult(context, jPushMessage);
}
@Override
public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context, jPushMessage);
super.onMobileNumberOperatorResult(context, jPushMessage);
}
@Override
public void onMessage(Context context, CustomMessage customMessage) {
super.onMessage(context, customMessage);
MyApplication.getInstance().manageCustomMessage(customMessage);
}
}

View File

@@ -0,0 +1,129 @@
package com.info.sn.jpush;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import com.info.sn.MainActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import cn.jpush.android.api.JPushInterface;
/**
* 自定义接收器
*
* 如果不定义这个 Receiver
* 1) 默认用户会打开主界面
* 2) 接收不到自定义消息
*/
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "JIGUANG-Example";
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
//send the Registration Id to your server...
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
processCustomMessage(context, bundle);
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知");
int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");
//打开自定义的Activity
Intent i = new Intent(context, TestActivity.class);
i.putExtras(bundle);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
context.startActivity(i);
} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码比如打开新的Activity 打开一个网页等..
} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
Logger.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
} else {
Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
}
} catch (Exception e){
}
}
// 打印所有的 intent extra 数据
private static String printBundle(Bundle bundle) {
StringBuilder sb = new StringBuilder();
for (String key : bundle.keySet()) {
if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
Logger.i(TAG, "This message has no Extra data");
continue;
}
try {
JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
Iterator<String> it = json.keys();
while (it.hasNext()) {
String myKey = it.next();
sb.append("\nkey:" + key + ", value: [" +
myKey + " - " +json.optString(myKey) + "]");
}
} catch (JSONException e) {
Logger.e(TAG, "Get message extra JSON error!");
}
} else {
sb.append("\nkey:" + key + ", value:" + bundle.get(key));
}
}
return sb.toString();
}
//send msg to MainActivity
private void processCustomMessage(Context context, Bundle bundle) {
if (MainActivity.isForeground) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
if (!ExampleUtil.isEmpty(extras)) {
try {
JSONObject extraJson = new JSONObject(extras);
if (extraJson.length() > 0) {
msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
}
} catch (JSONException e) {
}
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
}
}
}

View File

@@ -0,0 +1,7 @@
package com.info.sn.jpush;
import cn.jpush.android.service.JCommonService;
public class PushService extends JCommonService {
}

View File

@@ -0,0 +1,338 @@
package com.info.sn.jpush;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import java.util.Locale;
import java.util.Set;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
/**
* 处理tagalias相关的逻辑
* */
public class TagAliasOperatorHelper {
private static final String TAG = "JIGUANG-TagAliasHelper";
public static int sequence = 1;
/**增加*/
public static final int ACTION_ADD = 1;
/**覆盖*/
public static final int ACTION_SET = 2;
/**删除部分*/
public static final int ACTION_DELETE = 3;
/**删除所有*/
public static final int ACTION_CLEAN = 4;
/**查询*/
public static final int ACTION_GET = 5;
public static final int ACTION_CHECK = 6;
public static final int DELAY_SEND_ACTION = 1;
public static final int DELAY_SET_MOBILE_NUMBER_ACTION = 2;
private Context context;
private static TagAliasOperatorHelper mInstance;
private TagAliasOperatorHelper(){
}
public static TagAliasOperatorHelper getInstance(){
if(mInstance == null){
synchronized (TagAliasOperatorHelper.class){
if(mInstance == null){
mInstance = new TagAliasOperatorHelper();
}
}
}
return mInstance;
}
public void init(Context context){
if(context != null) {
this.context = context.getApplicationContext();
}
}
private SparseArray<Object> setActionCache = new SparseArray<Object>();
public Object get(int sequence){
return setActionCache.get(sequence);
}
public Object remove(int sequence){
return setActionCache.get(sequence);
}
public void put(int sequence,Object tagAliasBean){
setActionCache.put(sequence,tagAliasBean);
}
private Handler delaySendHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case DELAY_SEND_ACTION:
if(msg.obj !=null && msg.obj instanceof TagAliasBean){
Logger.i(TAG,"on delay time");
sequence++;
TagAliasBean tagAliasBean = (TagAliasBean) msg.obj;
setActionCache.put(sequence, tagAliasBean);
if(context!=null) {
handleAction(context, sequence, tagAliasBean);
}else{
Logger.e(TAG,"#unexcepted - context was null");
}
}else{
Logger.w(TAG,"#unexcepted - msg obj was incorrect");
}
break;
case DELAY_SET_MOBILE_NUMBER_ACTION:
if(msg.obj !=null && msg.obj instanceof String) {
Logger.i(TAG, "retry set mobile number");
sequence++;
String mobileNumber = (String) msg.obj;
setActionCache.put(sequence, mobileNumber);
if(context !=null) {
handleAction(context, sequence, mobileNumber);
}else {
Logger.e(TAG, "#unexcepted - context was null");
}
}else{
Logger.w(TAG,"#unexcepted - msg obj was incorrect");
}
break;
}
}
};
public void handleAction(Context context,int sequence,String mobileNumber){
put(sequence,mobileNumber);
Logger.d(TAG,"sequence:"+sequence+",mobileNumber:"+mobileNumber);
JPushInterface.setMobileNumber(context,sequence,mobileNumber);
}
/**
* 处理设置tag
* */
public void handleAction(Context context,int sequence, TagAliasBean tagAliasBean){
init(context);
if(tagAliasBean == null){
Logger.w(TAG,"tagAliasBean was null");
return;
}
put(sequence,tagAliasBean);
if(tagAliasBean.isAliasAction){
switch (tagAliasBean.action){
case ACTION_GET:
JPushInterface.getAlias(context,sequence);
break;
case ACTION_DELETE:
JPushInterface.deleteAlias(context,sequence);
break;
case ACTION_SET:
JPushInterface.setAlias(context,sequence,tagAliasBean.alias);
break;
default:
Logger.w(TAG,"unsupport alias action type");
return;
}
}else {
switch (tagAliasBean.action) {
case ACTION_ADD:
JPushInterface.addTags(context, sequence, tagAliasBean.tags);
break;
case ACTION_SET:
JPushInterface.setTags(context, sequence, tagAliasBean.tags);
break;
case ACTION_DELETE:
JPushInterface.deleteTags(context, sequence, tagAliasBean.tags);
break;
case ACTION_CHECK:
//一次只能check一个tag
String tag = (String)tagAliasBean.tags.toArray()[0];
JPushInterface.checkTagBindState(context,sequence,tag);
break;
case ACTION_GET:
JPushInterface.getAllTags(context, sequence);
break;
case ACTION_CLEAN:
JPushInterface.cleanTags(context, sequence);
break;
default:
Logger.w(TAG,"unsupport tag action type");
return;
}
}
}
private boolean RetryActionIfNeeded(int errorCode,TagAliasBean tagAliasBean){
if(!ExampleUtil.isConnected(context)){
Logger.w(TAG,"no network");
return false;
}
//返回的错误码为6002 超时,6014 服务器繁忙,都建议延迟重试
if(errorCode == 6002 || errorCode == 6014){
Logger.d(TAG,"need retry");
if(tagAliasBean!=null){
Message message = new Message();
message.what = DELAY_SEND_ACTION;
message.obj = tagAliasBean;
delaySendHandler.sendMessageDelayed(message,1000*60);
String logs =getRetryStr(tagAliasBean.isAliasAction, tagAliasBean.action,errorCode);
ExampleUtil.showToast(logs, context);
return true;
}
}
return false;
}
private boolean RetrySetMObileNumberActionIfNeeded(int errorCode,String mobileNumber){
if(!ExampleUtil.isConnected(context)){
Logger.w(TAG,"no network");
return false;
}
//返回的错误码为6002 超时,6024 服务器内部错误,建议稍后重试
if(errorCode == 6002 || errorCode == 6024){
Logger.d(TAG,"need retry");
Message message = new Message();
message.what = DELAY_SET_MOBILE_NUMBER_ACTION;
message.obj = mobileNumber;
delaySendHandler.sendMessageDelayed(message,1000*60);
String str = "Failed to set mobile number due to %s. Try again after 60s.";
str = String.format(Locale.ENGLISH,str,(errorCode == 6002 ? "timeout" : "server internal error”"));
ExampleUtil.showToast(str, context);
return true;
}
return false;
}
private String getRetryStr(boolean isAliasAction,int actionType,int errorCode){
String str = "Failed to %s %s due to %s. Try again after 60s.";
str = String.format(Locale.ENGLISH,str,getActionStr(actionType),(isAliasAction? "alias" : " tags") ,(errorCode == 6002 ? "timeout" : "server too busy"));
return str;
}
private String getActionStr(int actionType){
switch (actionType){
case ACTION_ADD:
return "add";
case ACTION_SET:
return "set";
case ACTION_DELETE:
return "delete";
case ACTION_GET:
return "get";
case ACTION_CLEAN:
return "clean";
case ACTION_CHECK:
return "check";
}
return "unkonw operation";
}
public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
int sequence = jPushMessage.getSequence();
Logger.i(TAG,"action - onTagOperatorResult, sequence:"+sequence+",tags:"+jPushMessage.getTags());
Logger.i(TAG,"tags size:"+jPushMessage.getTags().size());
init(context);
//根据sequence从之前操作缓存中获取缓存记录
TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence);
if(tagAliasBean == null){
ExampleUtil.showToast("获取缓存记录失败", context);
return;
}
if(jPushMessage.getErrorCode() == 0){
Logger.i(TAG,"action - modify tag Success,sequence:"+sequence);
setActionCache.remove(sequence);
String logs = getActionStr(tagAliasBean.action)+" tags success";
Logger.i(TAG,logs);
ExampleUtil.showToast(logs, context);
}else{
String logs = "Failed to " + getActionStr(tagAliasBean.action)+" tags";
if(jPushMessage.getErrorCode() == 6018){
//tag数量超过限制,需要先清除一部分再add
logs += ", tags is exceed limit need to clean";
}
logs += ", errorCode:" + jPushMessage.getErrorCode();
Logger.e(TAG, logs);
if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) {
ExampleUtil.showToast(logs, context);
}
}
}
public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage){
int sequence = jPushMessage.getSequence();
Logger.i(TAG,"action - onCheckTagOperatorResult, sequence:"+sequence+",checktag:"+jPushMessage.getCheckTag());
init(context);
//根据sequence从之前操作缓存中获取缓存记录
TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence);
if(tagAliasBean == null){
ExampleUtil.showToast("获取缓存记录失败", context);
return;
}
if(jPushMessage.getErrorCode() == 0){
Logger.i(TAG,"tagBean:"+tagAliasBean);
setActionCache.remove(sequence);
String logs = getActionStr(tagAliasBean.action)+" tag "+jPushMessage.getCheckTag() + " bind state success,state:"+jPushMessage.getTagCheckStateResult();
Logger.i(TAG,logs);
ExampleUtil.showToast(logs, context);
}else{
String logs = "Failed to " + getActionStr(tagAliasBean.action)+" tags, errorCode:" + jPushMessage.getErrorCode();
Logger.e(TAG, logs);
if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) {
ExampleUtil.showToast(logs, context);
}
}
}
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
int sequence = jPushMessage.getSequence();
Logger.i(TAG,"action - onAliasOperatorResult, sequence:"+sequence+",alias:"+jPushMessage.getAlias());
init(context);
//根据sequence从之前操作缓存中获取缓存记录
TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence);
if(tagAliasBean == null){
ExampleUtil.showToast("获取缓存记录失败", context);
return;
}
if(jPushMessage.getErrorCode() == 0){
Logger.i(TAG,"action - modify alias Success,sequence:"+sequence);
setActionCache.remove(sequence);
String logs = getActionStr(tagAliasBean.action)+" alias success";
Logger.i(TAG,logs);
ExampleUtil.showToast(logs, context);
}else{
String logs = "Failed to " + getActionStr(tagAliasBean.action)+" alias, errorCode:" + jPushMessage.getErrorCode();
Logger.e(TAG, logs);
if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) {
ExampleUtil.showToast(logs, context);
}
}
}
//设置手机号码回调
public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
int sequence = jPushMessage.getSequence();
Logger.i(TAG,"action - onMobileNumberOperatorResult, sequence:"+sequence+",mobileNumber:"+jPushMessage.getMobileNumber());
init(context);
if(jPushMessage.getErrorCode() == 0){
Logger.i(TAG,"action - set mobile number Success,sequence:"+sequence);
setActionCache.remove(sequence);
}else{
String logs = "Failed to set mobile number, errorCode:" + jPushMessage.getErrorCode();
Logger.e(TAG, logs);
if(!RetrySetMObileNumberActionIfNeeded(jPushMessage.getErrorCode(),jPushMessage.getMobileNumber())){
ExampleUtil.showToast(logs, context);
}
}
}
public static class TagAliasBean{
public int action;
public Set<String> tags;
public String alias;
public boolean isAliasAction;
@Override
public String toString() {
return "TagAliasBean{" +
"action=" + action +
", tags=" + tags +
", alias='" + alias + '\'' +
", isAliasAction=" + isAliasAction +
'}';
}
}
}

View File

@@ -0,0 +1,32 @@
package com.info.sn.jpush;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("用户自定义打开的Activity");
Intent intent = getIntent();
if (null != intent) {
Bundle bundle = getIntent().getExtras();
String title = null;
String content = null;
if(bundle!=null){
title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
content = bundle.getString(JPushInterface.EXTRA_ALERT);
}
tv.setText("Title : " + title + " " + "Content : " + content);
}
addContentView(tv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
}

View File

@@ -0,0 +1,22 @@
package com.info.sn.network;
public class UrlPath {
public static final String HOMEPATHRUL = "http://homework.tuiinfo.com/api/";
//主页接口
public static final String SNINFO = HOMEPATHRUL + "Member/snInfo";
//设备信息接口
public static final String APPLOG = HOMEPATHRUL + "App/getApplog";
public final static String GET_APP_UPDATE = HOMEPATHRUL + "Update/update";
//根据包名获取更新
public final static String SET_APP_INSTALL_INFO = HOMEPATHRUL + "App/appInstall";
//发送app安装信息
public final static String SET_APP_UNINSTALL_INFO = HOMEPATHRUL + "App/appUnload";
//发送app卸载信息
public final static String SEND_RUNINGAPPINFO = HOMEPATHRUL + "Monitoring/getAppNow";
//获取当前最顶层应用和电量
public final static String SEND_DRIVE_STATE = HOMEPATHRUL + "Online/online";
}

View File

@@ -0,0 +1,239 @@
package com.info.sn.network.api;
import android.content.Context;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import androidx.annotation.RequiresApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.info.sn.bean.MessageWhat;
import com.info.sn.bean.UserInfo;
import com.info.sn.network.UrlPath;
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.StringCallback;
import com.lzy.okgo.model.Response;
import java.util.Date;
import java.util.Random;
public class HTTPInterface {
private final static int requestCodeOK = 200;
//获取设备信息接口
public static synchronized void checkDevicesInfo(final Handler handler) {
OkGo.<String>post(UrlPath.SNINFO)
.params("sn", Utils.getSn())
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Log.e("onSuccess", "checkDevicesInfo");
try {
JSONObject bodyObject = JSON.parseObject(response.body());
Integer code = (bodyObject.getInteger("code"));
String msg = bodyObject.getString("msg");
String data = bodyObject.getString("data");
UserInfo userInfo = JSON.parseObject(data, UserInfo.class);
Message message = new Message();
message.obj = userInfo;
if (code == requestCodeOK) {
message.what = 1;
handler.sendMessage(message);
} else if (code == -200) {
message.what = 0;
handler.sendMessage(message);
} else if (code == -250) {
ToastUtil.show(msg);
handler.sendEmptyMessage(2);
//设备验证
}
} catch (Exception ex) {
Log.e("checkDevicesInfo", ex.getMessage());
}
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Log.e("onError", response.getException().toString());
}
});
}
@RequiresApi(api = Build.VERSION_CODES.N)
public static void sendTimeLog(final Handler handler, UserInfo userInfo, String appname, int status, long time) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
String times = simpleDateFormat.format(date);
OkGo.<String>post(UrlPath.APPLOG)
.params("sn", Utils.getSerial())
.params("app_name", appname)
.params("use_time", time)
.params("status", status)
.params("createtime", times)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Log.e("onSuccess", "sendTimeLog");
try {
JSONObject bodyObject = JSON.parseObject(response.body());
Log.e("onSuccess", bodyObject.toString());
Integer code = (bodyObject.getInteger("code"));
String msg = bodyObject.getString("msg");
String data = bodyObject.getString("data");
UserInfo userInfo = JSON.parseObject(data, UserInfo.class);
Message message = new Message();
message.obj = userInfo;
if (code == requestCodeOK) {
} else if (code == -200) {
} else if (code == -250) {
}
} catch (Exception ex) {
Log.e("checkDevicesInfo", ex.getMessage());
}
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Log.e("onError", response.getException().toString());
}
});
}
synchronized public static void checkUpdateByPackage(final Handler handler, String packageName, String versionCode) {
OkGo.<String>post(UrlPath.GET_APP_UPDATE)
.params("code", versionCode)
.params("package", packageName)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
try {
JSONObject body = JSON.parseObject(response.body());
int code = body.getInteger("code");
String msg = body.getString("msg");
if (code == 200) {
Message message = new Message();
JSONObject data = JSON.parseObject(body.getString("data"));
if (data != null) {
String url = data.getString("downloadurl");
String newversion = data.getString("newversion");
String content = data.getString("content");
message.what = 200;
Bundle bundle = new Bundle();
bundle.putString("url", url);
bundle.putString("versionCode", newversion);
bundle.putString("content", content);
message.obj = bundle;
} else {
message.what = -200;
}
handler.sendMessage(message);
Log.e("checkUpdateByPackage", msg);
} else {
Log.e("checkUpdateByPackage", msg);
}
} catch (Exception e) {
Log.e("checkUpdateByPackage", e.getMessage());
}
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Log.e("checkUpdateByPackage", response.getException().toString());
}
});
}
synchronized public static void setAppuninstallInfo(String sn_id, String packageName) {
OkGo.<String>post(UrlPath.SET_APP_UNINSTALL_INFO)
.params("sn_id", sn_id)
.params("package", packageName)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
JSONObject object = JSON.parseObject(response.body());
int code = object.getInteger("code");
String msg = object.getString("msg");
LogUtils.e("setAppinstallInfo", msg);
if (code == MessageWhat.CODE_SUCCESSFUL) {
} else {
}
}
@Override
public void onError(Response<String> response) {
super.onError(response);
LogUtils.e("setAppinstallInfo", "onError:" + response.getException());
}
});
}
synchronized public static void sendStartTime(Context context, long startTime, String packageName, int battery, String random) {
String sn_id = (String) SPUtils.get(context, "sn_id", "-1");
String member_id = (String) SPUtils.get(context, "member_id", "-1");
OkGo.<String>post(UrlPath.SEND_RUNINGAPPINFO)
.params("start_time", startTime)
.params("package", packageName)
.params("battery", battery)
.params("member_id", member_id)
.params("sn_id", sn_id)
.params("random", random)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
String body = response.body();
LogUtils.e("sendStartTime", body);
}
@Override
public void onError(Response<String> response) {
super.onError(response);
LogUtils.e("sendStartTime", response.getException().toString());
}
});
}
synchronized public static void getDriveState(String member_id, String sn_id) {
OkGo.<String>post(UrlPath.SEND_DRIVE_STATE)
.params("member_id", member_id)
.params("sn_id", sn_id)
.params("status", 1)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
}
@Override
public void onError(Response<String> response) {
super.onError(response);
}
});
}
}

View File

@@ -0,0 +1,19 @@
package com.info.sn.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class APKinstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) || intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
String packageName = intent.getDataString().replace("package:", "");
}
}
}

View File

@@ -0,0 +1,23 @@
package com.info.sn.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("BootReceiver", intent.getAction());
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Intent i = new Intent(context, InitJpushServer.class);
// context.startService(i);
context.startService(new Intent(context, StepService.class));
context.startService(new Intent(context, GuardService.class));
}
}
}

View File

@@ -0,0 +1,67 @@
package com.info.sn.service;
/**
* 作者 mjsheng
* 日期 2019/4/1 10:58
* 邮箱 501802639@qq.com
* 来自:
*/
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import androidx.annotation.Nullable;
import com.info.sn.KeepAliveConnection;
import com.info.sn.utils.LogUtils;
import com.info.sn.utils.ServiceAliveUtils;
/**
* 守护进程 双进程通讯
*
* @author LiGuangMin
* @time Created by 2018/8/17 11:27
*/
public class GuardService extends Service {
private final static String TAG = GuardService.class.getSimpleName();
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
LogUtils.e(TAG, "GuardService:建立链接");
boolean isServiceRunning = ServiceAliveUtils.isServiceAlice();
if (!isServiceRunning) {
Intent i = new Intent(GuardService.this, MyDownloadService.class);
startService(i);
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 断开链接
startService(new Intent(GuardService.this, StepService.class));
// 重新绑定
bindService(new Intent(GuardService.this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new KeepAliveConnection.Stub() {
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 绑定建立链接
bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
return START_STICKY;
}
}

View File

@@ -0,0 +1,159 @@
package com.info.sn.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.info.sn.BuildConfig;
import com.info.sn.MyApplication;
import com.info.sn.R;
import com.info.sn.network.api.HTTPInterface;
import com.info.sn.utils.ApkUtils;
import com.info.sn.utils.LogUtils;
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;
// 下载管理服务
public class MyDownloadService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
}
synchronized private void CheckUpdate() {
HTTPInterface.checkUpdateByPackage(handler, this.getPackageName(), String.valueOf(BuildConfig.VERSION_CODE));
}
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, StepService.class));
startService(new Intent(this, GuardService.class));
CheckUpdate();
// new Thread(new Runnable() {
// @Override
// public void run() {
// while (true) {
// LogUtils.e("packagename", MyApplication.getTaskPackname());
// LogUtils.e("packagename", String.valueOf(MyApplication.getSystemBattery()));
//// MyApplication.sendStartTime();
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
// }).start();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
break;
case 200:
Bundle bundle = (Bundle) msg.obj;
getFile(bundle);
break;
}
}
};
private void getFile(final Bundle bundle) {
final File path = new File(Environment.getExternalStoragePublicDirectory("Download") + "/Sninfo/");
path.mkdirs();
final File file = new File(Environment.getExternalStoragePublicDirectory("Download") + "/Sninfo/Update" + bundle.getString("versionCode") + ".apk");
if (file.exists() && file.isFile()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("软件更新")
.setIcon(R.mipmap.ic_launcher_home)
.setCancelable(false)
.setMessage("发现新版本,点击确定更新\n" + "更新内容:" + bundle.getString("content"))
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ApkUtils.installApk(MyDownloadService.this, file);
dialogInterface.dismiss();
}
});
AlertDialog ad = builder.create();
ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失
ad.show();
} else {
OkGo.<File>get(bundle.getString("url"))
.execute(new FileCallback("Sninfo/Update" + bundle.getString("versionCode") + ".apk") {
@Override
public void onSuccess(final Response<File> 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(MyDownloadService.this)
.setTitle("软件更新")
.setIcon(R.mipmap.ic_launcher_home)
.setCancelable(false)
.setMessage("发现新版本,点击确定更新\n" + "更新内容:" + bundle.getString("content"))
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ApkUtils.installApk(MyDownloadService.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<File> 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);
}
});
}
}
}

View File

@@ -0,0 +1,68 @@
package com.info.sn.service;
/**
* 作者 mjsheng
* 日期 2019/4/1 10:57
* 邮箱 501802639@qq.com
* 来自:
*/
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import androidx.annotation.Nullable;
import com.info.sn.KeepAliveConnection;
import com.info.sn.utils.LogUtils;
import com.info.sn.utils.ServiceAliveUtils;
/**
* 主进程 双进程通讯
*
* @author LiGuangMin
* @time Created by 2018/8/17 11:26
*/
public class StepService extends Service {
private final static String TAG = StepService.class.getSimpleName();
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
LogUtils.e(TAG, "StepService:建立链接");
boolean isServiceRunning = ServiceAliveUtils.isServiceAlice();
if (!isServiceRunning) {
Intent i = new Intent(StepService.this, MyDownloadService.class);
startService(i);
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 断开链接
startService(new Intent(StepService.this, GuardService.class));
// 重新绑定
bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new KeepAliveConnection.Stub() {
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// startForeground(1, new Notification());
// 绑定建立链接
bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
return START_STICKY;
}
}

View File

@@ -0,0 +1,454 @@
package com.info.sn.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import com.info.sn.R;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class ApkUtils {
public static synchronized boolean getRootAhth() {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("exit\n");
os.flush();
int exitValue = process.waitFor();
if (exitValue == 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
Log.e("*** DEBUG ***", "Unexpected error - Here is what I know: "
+ e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openApp(Context context, View view) {
try {
Intent intent = context.getPackageManager().getLaunchIntentForPackage((String) view.getTag(R.string.download_btn_had));
context.startActivity(intent);
} catch (Exception e) {
Toast.makeText(context, R.string.open_app_fail, Toast.LENGTH_LONG).show();
}
return;
}
public static void openApp(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
/**
* 安装一个apk文件
*/
public static void install(Context context, File uriFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
Uri apkUri =
FileProvider.getUriForFile(context, "com.info.sn.fileprovider", uriFile);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(uriFile),
"application/vnd.android.package-archive");
}
context.startActivity(intent);
}
/**
* 卸载一个app
*/
public static void uninstall(Context context, String packageName) {
//通过程序的包名创建URI
Uri packageURI = Uri.parse("package:" + packageName);
//创建Intent意图
Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
//执行卸载程序
context.startActivity(intent);
}
/**
* 检查手机上是否安装了指定的软件
*/
public static boolean isAvailable(Context context, String packageName) {
// 获取packagemanager
final PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
// 用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<>();
// 从pinfo中将包名字逐一取出压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
// 判断packageNames中是否有目标程序的包名有TRUE没有FALSE
return packageNames.contains(packageName);
}
/**
* 检查手机上是否安装了指定的软件
*/
public static boolean isAvailable(Context context, File file) {
return isAvailable(context, getPackageName(context, file.getAbsolutePath()));
}
/**
* 根据文件路径获取包名
*/
public static String getPackageName(Context context, String filePath) {
PackageManager packageManager = context.getPackageManager();
PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
return appInfo.packageName; //得到安装包名称
}
return null;
}
/**
* 从apk中获取版本信息
*/
public static String getChannelFromApk(Context context, String channelPrefix) {
//从apk包中获取
ApplicationInfo appinfo = context.getApplicationInfo();
String sourceDir = appinfo.sourceDir;
//默认放在meta-inf/里, 所以需要再拼接一下
String key = "META-INF/" + channelPrefix;
String ret = "";
ZipFile zipfile = null;
try {
zipfile = new ZipFile(sourceDir);
Enumeration<?> entries = zipfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.startsWith(key)) {
ret = entryName;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] split = ret.split(channelPrefix);
String channel = "";
if (split.length >= 2) {
channel = ret.substring(key.length());
}
return channel;
}
public static void installRx(final Context context, final String packageName, final String filePath) {
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
File file = new File(filePath);
if (filePath == null || filePath.length() == 0 || file == null) {
Log.e("fanhuitong", "errormesg=========" + " 空啊 ");
subscriber.onNext(0);
return;
}
// String[] args = { "pm", "install", "-r", filePath };
String[] args = {"pm", "install", "-i", "com.colorflykids", "--user", "0", filePath};
// String argss = "pm install -i " + "com.colorflykids" + " --user 0 " + filePath;
Log.e("fanhuitong", "argss====" + args);
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = processBuilder.start();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
Log.e("mjhseng", "successResult----------" + s);
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
Log.e("mjhseng", "errorResult----------" + s);
errorMsg.append(s);
}
} catch (IOException e1) {
Log.e("fanhuitong", "IOException e1)----------" + e1.toString());
e1.printStackTrace();
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e1) {
Log.e("fanhuitong", "IOException e11)---------" + e1.toString());
e1.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
subscriber.onNext(2);
} else {
Log.e("fanhuitong", "errormesg=========" + errorMsg.toString());
subscriber.onNext(1);
}
}
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Integer>() {
@Override
public void onNext(Integer value) {
if (value == 2) {
//安装成功
Utils.showToast(context, "安装成功");
Log.e("fanhuitong", "-----------安装成功-----------");
} else {
//安装错误
Log.e("fanhuitong", "------------安装错误-----------");
Utils.showToast(context, "安装失败");
}
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//安装错误
}
});
}
// public static void installApp(final String path, final String packageNames){
// File apkFile = new File(path);
// try {
// Class<?> clazz = Class.forName("android.os.ServiceManager");
// Method method_getService = clazz.getMethod("getService", String.class);
// IBinder bind = (IBinder) method_getService.invoke(null, "package");
// IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
// iPm.installPackage(Uri.fromFile(apkFile),null, 2, apkFile.getName());
// Log.e("fanhuitong", "安装成功");
// } catch (Exception e) {
// e.printStackTrace();
// Log.e("fanhuitong", "安装失败");
// }
// }
//使用系统签名
public static void installApkInSilence(String installPath, String packageName) {
ToastUtil.show("正在安装应用...");
Class<?> pmService;
Class<?> activityTherad;
Method method;
try {
activityTherad = Class.forName("android.app.ActivityThread");
Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
method = activityTherad.getMethod("getPackageManager", paramTypes);
Object PackageManagerService = method.invoke(activityTherad);
pmService = PackageManagerService.getClass();
Class<?> paramTypes1[] = getParamTypes(pmService, "installPackageAsUser");
method = pmService.getMethod("installPackageAsUser", paramTypes1);
method.invoke(PackageManagerService, installPath, null, 0x00000040, packageName, getUserId(Binder.getCallingUid()));//getUserId
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static void deleteApkInSilence(String packageName) {
Class<?> pmService;
Class<?> activityTherad;
Method method;
try {
activityTherad = Class.forName("android.app.ActivityThread");
Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
method = activityTherad.getMethod("getPackageManager", paramTypes);
Object PackageManagerService = method.invoke(activityTherad);
pmService = PackageManagerService.getClass();
Class<?> paramTypes1[] = getParamTypes(pmService, "deletePackageAsUser");
method = pmService.getMethod("deletePackageAsUser", paramTypes1);
method.invoke(PackageManagerService, packageName, null, getUserId(Binder.getCallingUid()), 0x00000040);//getUserId
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private static Class<?>[] getParamTypes(Class<?> cls, String mName) {
Class<?> cs[] = null;
Method[] mtd = cls.getMethods();
for (int i = 0; i < mtd.length; i++) {
if (!mtd[i].getName().equals(mName)) {
continue;
}
cs = mtd[i].getParameterTypes();
}
return cs;
}
public static final int PER_USER_RANGE = 100000;
public static int getUserId(int uid) {
return uid / PER_USER_RANGE;
}
public static boolean checkIsUpdate(Context context, String packageName, int versionCode) {
PackageManager packageManager = context.getPackageManager();
boolean update = false;
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
int code = packageInfo.versionCode;
update = versionCode > code;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// LogUtils.e("NameNotFoundException", e.getMessage());
update = false;
}
return update;
}
synchronized public static PackageInfo getPackageInfo(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("getPackageInfo", packageName + ":" + e.getMessage());
}
return packageInfo;
}
synchronized public static String getApplicationName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
String name = "";
try {
packageInfo = pm.getPackageInfo(packageName, 0);
name = pm.getApplicationLabel(packageInfo.applicationInfo).toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("getPackageInfo", packageName + ":" + e.getMessage());
}
return name;
}
public static void installApk(Activity activity, File newApkFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(activity, "com.info.sn.fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
activity.startActivity(intent);
}
public static void installApk(Context context, File newApkFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, "com.info.sn.fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
context.startActivity(intent);
}
}

View File

@@ -0,0 +1,34 @@
package com.info.sn.utils;
/**
* Created by Administrator on 2017/1/10.
*/
public class AppUpdateInfo {
private String packageName;
private String version;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@Override
public String toString() {
return "AppUpdateInfo{" +
"packageName='" + packageName + '\'' +
", version='" + version + '\'' +
'}';
}
}

View File

@@ -0,0 +1,146 @@
package com.info.sn.utils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AppsManagerUtils {
public static AppUpdateInfo getUpAppsByPackageName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
AppUpdateInfo appInfo = new AppUpdateInfo();
try {
PackageInfo packinfo = pm.getPackageInfo(packageName, 0);
appInfo.setPackageName(packageName);
appInfo.setVersion(packinfo.versionName);
if (packinfo.versionName == null || packinfo.versionName.equals("")) {
appInfo.setVersion(packinfo.versionCode + "");
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return appInfo;
}
public static LocalAppInfo getAppsByPackageName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
List<LocalAppInfo> appInfos = new ArrayList<LocalAppInfo>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
// 不列出系统应用
String pkg = info.activityInfo.packageName;
if (pkg.equals(packageName)) {
extractedAppInfo(pm, appInfos, info);
}
}
return appInfos.get(0);
}
public static List<AppUpdateInfo> getUpadteApps(Context context) {
PackageManager pm = context.getPackageManager();
List<AppUpdateInfo> appInfos = new ArrayList<AppUpdateInfo>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
// 不列出系统应用
String pkg = info.activityInfo.packageName;
if (!isSystemApp(context, pkg)) {
PackageInfo packageInfo = null;
AppUpdateInfo appInfo = new AppUpdateInfo();
appInfo.setPackageName(info.activityInfo.packageName);
try {
packageInfo = pm.getPackageInfo(info.activityInfo.packageName, 0);
appInfo.setVersion(packageInfo.versionName);
if (packageInfo.versionName == null || packageInfo.versionName.equals("")) {
appInfo.setVersion(packageInfo.versionCode + "");
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
appInfos.add(appInfo);
}
}
return appInfos;
}
public static List<LocalAppInfo> getUserApps(Context context) {
PackageManager pm = context.getPackageManager();
List<LocalAppInfo> appInfos = new ArrayList<LocalAppInfo>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
// 不列出系统应用
String pkg = info.activityInfo.packageName;
if (!isSystemApp(context, pkg)) {
extractedAppInfo(pm, appInfos, info);
}
}
return appInfos;
}
private static void extractedAppInfo(PackageManager pm,
List<LocalAppInfo> appInfos, ResolveInfo info) {
PackageInfo packageInfo = null;
LocalAppInfo appInfo = new LocalAppInfo();
appInfo.setIcon(info.activityInfo.loadIcon(pm));
appInfo.setAppName(info.activityInfo.loadLabel(pm).toString());
appInfo.setPackageName(info.activityInfo.packageName);
try {
packageInfo = pm.getPackageInfo(info.activityInfo.packageName, 0);
appInfo.setVersion(packageInfo.versionName);
if (packageInfo.versionName == null || packageInfo.versionName.equals("")) {
appInfo.setVersion(packageInfo.versionCode + "");
}
String appInstallDir = info.activityInfo.applicationInfo.publicSourceDir;
int size = Integer.valueOf((int) new File(appInstallDir).length());
appInfo.setSize(size);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
appInfos.add(appInfo);
}
public static boolean isSystemApp(Context context, String pkg) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pkg, 0);
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
if (pkg.equals(context.getPackageName())) {
return true;
} else {
//第三方应用
return false;
}
} else {
//系统应用
return true;
}
} catch (NameNotFoundException e) {
e.printStackTrace();
return true;
}
}
}

View File

@@ -0,0 +1,28 @@
package com.info.sn.utils;
public class CommonData {
public static final String MAJOR_ACTION = "MAJOR_ACTION";
public static final String FLAG_FIRST_ENTER = "first_enter";
public static final String SP_USER_ID = "user_ID";
public static final String SP_USER_PHONE = "user_phone";
public static final String SP_USER_NAME = "user_name";
public static final String SP_USER_IDCARD = "user_idcard";
public static final String SP_USER_PASSWORD = "user_pass";
public static final String SP_RECOMMEND_PHONE = "recommend_phone";
public static final String SP_RECOMMEND_NAME = "sup_name";
public static final String SP_USER_LEVEL = "user_level";
public static final String SP_ISLOGINED = "user_islogined";
public static final String NEXT_PAGE = "next_page";
public static final String BANK_NAME = "bank_name";
public static final String OPERATOR_NAME = "bank_name";
public static final String PRODUCT_LINK = "product_link";
public static final String PRODUCT_NAME = "product_name";
}

View File

@@ -0,0 +1,144 @@
package com.info.sn.utils;
import android.graphics.drawable.Drawable;
public class LocalAppInfo {
public static final int DOWNLOAD_STATUS_NORMAL = 0;
public static final int DOWNLOAD_STATUS_DOWNLOADING = 1;
public static final int DOWNLOAD_STATUS_PAUSE = 2;
private Drawable icon;
private String iconUrl = "";
private String appName;
private String packageName;
private String version;
private String latestVersion = "";
private int size;
private String latestSize;
private String downLoadUrl;
private int dowloadStatus = DOWNLOAD_STATUS_NORMAL;
private String tip;
private int id;
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getLatestVersion() {
return latestVersion;
}
public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}
public String getLatestSize() {
return latestSize;
}
public void setLatestSize(String latestSize) {
this.latestSize = latestSize;
}
public String getDownLoadUrl() {
return downLoadUrl;
}
public void setDownLoadUrl(String downLoadUrl) {
this.downLoadUrl = downLoadUrl;
}
public int getDowloadStatus() {
return dowloadStatus;
}
public void setDowloadStatus(int dowloadStatus) {
this.dowloadStatus = dowloadStatus;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "AppUpdateInfo{" +
"packageName='" + packageName + '\'' +
", version='" + version + '\'' +
'}';
}
public boolean equals(Object obj) {
if (this == obj) //传入的对象就是它自己如s.equals(s);肯定是相等的;
return true;
if (obj == null) //如果传入的对象是空,肯定不相等
return false;
if (getClass() != obj.getClass()) //如果不是同一个类型的如Studnet类和Animal类
//也不用比较了,肯定是不相等的
return false;
LocalAppInfo other = (LocalAppInfo) obj;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName)) //如果name属性相等则相等
return false;
return true;
}
}

View File

@@ -0,0 +1,40 @@
package com.info.sn.utils;
import android.util.Log;
import com.info.sn.BuildConfig;
public class LogUtils {
static boolean isDebug = BuildConfig.LOG_DEBUG;
// static boolean isDebug = BuildConfig.LOG_DEBUG;
public static void v(String tag, String msg) {
if (isDebug) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (isDebug) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (isDebug) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (isDebug) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if (isDebug) {
Log.e(tag, msg);
}
}
}

View File

@@ -0,0 +1,198 @@
package com.info.sn.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
/**
* 作者 mjsheng
* 日期 2018/10/9 18:41
* 邮箱 278359328@qq.com
* 来自:
*/
public class SPUtils {
/**
* 保存在手机里面的文件名
*/
public static final String FILE_NAME = "share_data";
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*/
public static void put(Context context, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else {
editor.putString(key, object.toString());
}
SharedPreferencesCompat.apply(editor);
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*/
public static Object get(Context context, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
/**
* 移除某个key值已经对应的值
*/
public static void remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}
/**
* 清除所有数据
*/
public static void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
reductFirstEnter(context);
}
//还原状态firstEnter信息
private static void reductFirstEnter(Context context){
put(context, CommonData.FLAG_FIRST_ENTER,CommonData.FLAG_FIRST_ENTER);
}
/**
* 查询某个key是否已经存在
*/
public static boolean contains(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.contains(key);
}
/**
* 返回所有的键值对
*/
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.getAll();
}
/**
* 保存图片到SharedPreferences
*
* @param mContext
* @param imageView
*/
public static void putImage(Context mContext, String key, ImageView imageView) {
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
// 将Bitmap压缩成字节数组输出流
ByteArrayOutputStream byStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);
// 利用Base64将我们的字节数组输出流转换成String
byte[] byteArray = byStream.toByteArray();
String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
// 将String保存shareUtils
SPUtils.put(mContext, key, imgString);
}
/**
* 从SharedPreferences读取图片
*
* @param mContext
* @param imageView
*/
public static Bitmap getImage(Context mContext, String key, ImageView imageView) {
String imgString = (String) SPUtils.get(mContext, key, "");
if (!imgString.equals("")) {
// 利用Base64将我们string转换
byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT);
ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray);
// 生成bitmap
return BitmapFactory.decodeStream(byStream);
}
return null;
}
/**
* 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
*/
private static class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
/**
* 反射查找apply的方法
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private static Method findApplyMethod() {
try {
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e) {
}
return null;
}
/**
* 如果找到则使用apply执行否则使用commit
*/
public static void apply(SharedPreferences.Editor editor) {
try {
if (sApplyMethod != null) {
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
editor.commit();
}
}
}

View File

@@ -0,0 +1,24 @@
package com.info.sn.utils;
import android.app.ActivityManager;
import android.content.Context;
import com.info.sn.MyApplication;
public class ServiceAliveUtils {
public static boolean isServiceAlice() {
boolean isServiceRunning = false;
ActivityManager manager =
(ActivityManager) MyApplication.getInstance().getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
if (manager == null) {
return true;
}
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("demo.lgm.com.keepalivedemo.service.DownloadService".equals(service.service.getClassName())) {
isServiceRunning = true;
}
}
return isServiceRunning;
}
}

View File

@@ -0,0 +1,65 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import com.info.sn.BuildConfig;
/**
* Created by haoge on 2017/3/2.
*/
public class ToastUtil {
static Handler mainHandler = new Handler(Looper.getMainLooper());
static Toast toast;
@SuppressLint("ShowToast")
public static void init(Context context) {
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
debugToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
public static void show(final String msg) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.setText(msg);
toast.show();
}
}
});
}
// public static void showInCenter(String msg) {
// mainHandler.post(() -> {
// if (toast != null) {
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.setText(msg);
// toast.show();
// }
// });
// }
static Handler debugHandler = new Handler(Looper.getMainLooper());
static Toast debugToast;
public static void debugShow(final String msg) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if (BuildConfig.LOG_DEBUG) {
if (toast != null) {
toast.setText(msg);
toast.show();
}
}
}
});
}
}

View File

@@ -0,0 +1,864 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.info.sn.MyApplication;
import com.info.sn.R;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Utils {
public static final String PACKAGE = "appstore";
public static final String DOWNLOAD_STARTALL_ACTION = PACKAGE + "_startall"; // 开始所有任务
public static final String DOWNLOAD_DELETE_UPDATE_ACTION = PACKAGE + "_download_update_delete"; // 删除应用更新文件
public static final String DOWNLOAD_DELETEALL_ACTION = PACKAGE + "_deleteall_alltask"; // 删除所有任务
public static final String DOWNLOAD_ALLTASK_ACTION = PACKAGE + "_download_alltask"; // 获取所有任务
public static final String DOWNLOAD_START_ACTION = PACKAGE + "_download_start"; // 下载标识
public static final String DOWNLOAD_STOP_ACTION = PACKAGE + "_download_stop"; // 暂停标识
public static final String DOWNLOAD_DELETE_PACKAGENAME_ACTION = PACKAGE + "_download_packagename_delete"; // 删除标识 根据包名
public static final String DOWNLOAD_DELETE_URL_ACTION = PACKAGE + "_download_url_delete"; // 删除标识 根据下载地址
public static final String DOWNLOAD_INITIALIZE_ACTION = PACKAGE + "_download_initialize"; // item初始化状态
public static final String DOWNLOAD_PACKAGENAME_ACTION = PACKAGE + "_download_packagename"; // item初始化状态 包名
public static final String DOWNLOAD_SERVICE_ACTION = PACKAGE + "_download_service"; // 下载状态回调服务
public static final String DOWNLOAD_ALLSERVICE_ACTION = PACKAGE + "_download_allservice"; // 返回所有下载任务
public static final String DOWNLOAD_NEWSERVICE_ACTION = PACKAGE + "_download_newservice"; // 一个新的下载任务
// JPush 推送消息
public static final String MESSAGE_RECEIVED_ACTION = "com.appstore.jpushdemo.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 static final String KEY_TYPE = "type"; // 消息内容类型
public static final String ACTION_PACKAGE_REPLACED = PACKAGE + "PACKAGE_REPLACED"; // 替换应用
public static final String ACTION_PACKAGE_REMOVED = PACKAGE + "PACKAGE_REMOVED"; // 卸载应用
public static final String ACTION_PACKAGE_ADDED = PACKAGE + "PACKAGE_ADDED"; // 安装应用
// public static int[] babyImage = {R.drawable.language, R.drawable.habit, R.drawable.knowledge, R.drawable.security, R.drawable.promotion};
// public static int[] childImage = {R.drawable.yuwen, R.drawable.shuxue, R.drawable.yingyu, R.drawable.qingshang, R.drawable.yishu, R.drawable.promotion};
// public static int[] youngImage = {R.drawable.yuwen, R.drawable.shuxue, R.drawable.yingyu, R.drawable.promotion};
// 学习日志上传标识
public static final String APP_LRARNLOG = "com.colorflykids.alarm";
// 学习日志下载标识
public static final String APP_DOWNLOADLEARNLOG = "com.colorflykids.downloadlearnlog";
// 账号注销标识
public static final String APP_USERLOGOUT = "com.colorflykids.userlogout";
public static final String UPDATE_SYSTEMUI = "cn.colorflykids.UPDATE_SYSTEMUI";
public static final int COUNT_ONE_PAGE = 8;
public static final int COUNT_ONE_PAGE2 = 10;
public static final String YOUNGSYSTEM_APP_TONGBU = "com.school.app.syn"; // 小学系统 同步教材app
/**
*
*/
public static final String number[] = {
"1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "0", "11"};
public static final String STORE = "store";
public static final String CATEGORY_THREE = "3";
public static final String CATEGORY_SIX = "6";
public static final String CATEGORY_UPSIX = "10";
public static final String CLOSE_REST_WINDOW = "colse_rest_window";
public static final String STOP_LOOPING_TIMER = "stop_looping_timer";
public static final String START_LOOPING_TIMER = "start_looping_timer";
public static String DOWNLOADAPP_CALLBACK = "com.colorflykids.downloadapp"; // 子界面下载回调 提示更新UI
public static String MENU_YOUYOU = "youyou";
public static String MENU_LANGUAGE = "语言启蒙";
public static String MENU_HABIT = "行为习惯";
public static String MENU_KNOWLEDGE = "生活认知";
public static String MENU_SECURITY = "安全自理";
public static String MENU_PROMOTION = "入园-综合提升";
public static String MENU_LY = "优优乐园";
public static String MENU_YW = "语文知识";
public static String MENU_SX = "数理逻辑";
public static String MENU_YY = "英语启蒙";
public static String MENU_QS = "情商培养";
public static String MENU_YS = "艺术提升";
public static String MENU_ZH = "学前-综合提升";
public static String MENU_TONGBUJIAOCAI = "同步教材";
public static String MENU_YUWEN = "语文";
public static String MENU_SHUXUE = "数学";
public static String MENU_YINGYU = "英语";
public static String MENU_ZONGHETISHEGN = "小学-综合提升";
public static String[] babySystem = {MENU_LANGUAGE, MENU_HABIT, MENU_KNOWLEDGE, MENU_SECURITY, MENU_PROMOTION};
public static String[] childSystem = {MENU_LY, MENU_YW, MENU_SX, MENU_YY, MENU_QS, MENU_YS, MENU_ZH};
public static String[] youngSystem = {MENU_YUWEN, MENU_SHUXUE, MENU_YINGYU, MENU_ZONGHETISHEGN};
public static String[] sonSystem = {MENU_HABIT, MENU_SECURITY, MENU_LANGUAGE, MENU_KNOWLEDGE, MENU_PROMOTION,
MENU_LY, MENU_YW, MENU_SX, MENU_YY, MENU_QS, MENU_YS, MENU_ZH,
MENU_TONGBUJIAOCAI, MENU_YUWEN, MENU_SHUXUE, MENU_YINGYU, MENU_YINGYU, MENU_ZONGHETISHEGN};
public static String[][] tagList = {babySystem, childSystem, youngSystem};
public static String subcategories[][] = {babySystem, childSystem, youngSystem};
public static String system[] = {"入园系统", "学前系统", "小学系统"};
public static String systemandno[] = {"入园系统", "学前系统", "小学系统", "未分配"};
protected static Toast toast = null;
private static String oldMsg;
private static long oneTime = 0;
private static long twoTime = 0;
// 积分记录 达人标准次数记录
// MD5 设备地址标识
public static String getMAC(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 如果当前设备系统大于等于6.0 使用下面的方法
return getMac();
} else {
try {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// 获取MAC地址
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String mac = wifiInfo.getMacAddress();
if (null == mac) {
// 未获取到
mac = "";
}
return mac;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
/**
* 获取手机的MAC地址
*
* @return
*/
public static String getMac() {
String str = "";
String macSerial = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
macSerial = getAndroid7MAC();
}
}
return macSerial;
}
/**
* 兼容7.0获取不到的问题
*
* @return
*/
public static String getAndroid7MAC() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0"))
continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "";
}
public static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
public static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
int readLength = reader.read(buffer);
while (readLength >= 0) {
builder.append(buffer, 0, readLength);
readLength = reader.read(buffer);
}
return builder.toString();
}
// MD5 设备地址标识
public static String getMD5(Context context) {
String WLANMAC = getMAC(context);
// compute md5
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (WLANMAC != null && !WLANMAC.equals("")) {
m.update(WLANMAC.getBytes(), 0, WLANMAC.length());
} else if (getSimSerialNumber(context) != null && !getSimSerialNumber(context).equals("")) {
m.update(getSimSerialNumber(context).getBytes(), 0, getSimSerialNumber(context).length());
} else {
m.update(getPesudoUniqueID().getBytes(), 0, getPesudoUniqueID().length());
}
// get md5 bytes
byte p_md5Data[] = m.digest();
// create a hex string
String m_szUniqueID = new String();
for (int i = 0; i < p_md5Data.length; i++) {
int b = (0xFF & p_md5Data[i]);
// if it is a single digit, make sure it have 0 in front (proper padding)
if (b <= 0xF)
m_szUniqueID += "0";
// add number to string
m_szUniqueID += Integer.toHexString(b);
} // hex string to uppercase
m_szUniqueID = m_szUniqueID.toUpperCase();
return m_szUniqueID;
}
private static String getSimSerialNumber(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
@SuppressLint("MissingPermission") String simSerialNumber = tm.getSimSerialNumber();
return simSerialNumber;
}
private static String getPesudoUniqueID() {
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length() % 10 +
Build.BRAND.length() % 10 +
Build.CPU_ABI.length() % 10 +
Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 +
Build.HOST.length() % 10 +
Build.ID.length() % 10 +
Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 +
Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 +
Build.TYPE.length() % 10 +
Build.USER.length() % 10;
return m_szDevIDShort;
}
// 防止连续点击
private static long lastClickTime;
public static boolean isFastDoubleClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < 500) {
return true;
}
lastClickTime = time;
return false;
}
// 5分钟 = 1 转换成时间
public static String getRangeTime(int range) {
StringBuffer sBuffer = new StringBuffer();
String hour;
String minute;
if ((range / 12) >= 10) {
hour = range / 12 + "";
} else {
hour = "0" + range / 12 + "";
}
if ((range % 12) > 0) {
minute = ":" + range % 12 / 2 + "0";
} else {
minute = ":00";
}
sBuffer.append(hour.trim());
sBuffer.append(minute.trim());
return sBuffer.toString();
}
// 根据日期取得星期几
public static String getWeek(Date date) {
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (week_index < 0) {
week_index = 0;
}
return weeks[week_index];
}
// 非空判断
public static boolean isEmpty(String s) {
if (null == s)
return true;
if (s.length() == 0)
return true;
if (s.trim().length() == 0)
return true;
return false;
}
// 手动隐藏键盘
public static void CloseKeyBoard(Context context) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
System.out.println("isActive:" + imm.isActive());
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
// 接受软键盘输入
public static void hideKeyboard(Context context, View view) {
if (context == null || view == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// 卸载app
public static void unInstallAPP(Context context, String packageName) {
if (!TextUtils.isEmpty(packageName) && !AppsManagerUtils.isSystemApp(context, packageName)) {
if (AppsManagerUtils.isSystemApp(context, packageName)) {
Toast.makeText(MyApplication.getAppContext(), "系统应用无法卸载!", Toast.LENGTH_SHORT).show();
} else {
Uri packageURI = Uri.parse("package:" + packageName);
Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(intent);
}
} else {
Toast.makeText(MyApplication.getAppContext(), "系统应用无法卸载!", Toast.LENGTH_SHORT).show();
}
}
// 打开app
public static void startApp(Context context, String packageName,
String activityName) {
if (TextUtils.isEmpty(packageName))
return;
try {
Intent intent = null;
if (TextUtils.isEmpty(activityName)) {
intent = context.getPackageManager().getLaunchIntentForPackage(
packageName);
} else {
intent = new Intent();
intent.setComponent(new ComponentName(packageName, activityName));
}
if (intent == null) {
intent = getLaunchIntentForNoCategory(context, packageName);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Intent getLaunchIntentForNoCategory(Context context,
String packageName) {
Intent intent = null;
PackageManager packageManager = context.getPackageManager();
PackageInfo packageinfo = null;
try {
packageinfo = packageManager.getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (packageinfo == null) {
return null;
}
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.setPackage(packageinfo.packageName);
List<ResolveInfo> resolveinfoList = packageManager
.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
String className = resolveinfo.activityInfo.name;
intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
}
return intent;
}
// 设置系统亮度模式
public static void systemBrightness(Context context) {
try {
SharedPreferences mPrefs = context.getSharedPreferences("colorflykids", 0);
boolean initSetting = mPrefs.getBoolean("init_setting", true);
if (initSetting) {
mPrefs.edit().putBoolean("init_setting", false).commit();
}
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
mPrefs.edit().putBoolean("first_init", false).commit();
} catch (Exception err) {
err.printStackTrace();
}
}
// 更新 版本比较
public static boolean isUpdate(String oldVersion, String newVersion) {
if (TextUtils.isEmpty(oldVersion) || TextUtils.isEmpty(newVersion) || oldVersion.equals(newVersion)) {
return false;
}
String[] oldVersionSp = oldVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
String[] newVsersionSp = newVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
int index = 0;
int minLen = Math.min(oldVersionSp.length, newVsersionSp.length);
int diff = 0;
while (index < minLen && (diff = Integer.parseInt(newVsersionSp[index]) - Integer.parseInt(oldVersionSp[index])) == 0) {
index++;
}
if (diff == 0) {
for (int i = index; i < oldVersionSp.length; i++) {
if (Integer.parseInt(oldVersionSp[i]) > 0) {
return false;
}
}
for (int i = index; i < newVsersionSp.length; i++) {
if (Integer.parseInt(newVsersionSp[i]) > 0) {
return true;
}
}
} else {
return diff > 0 ? true : false;
}
return false;
}
/***
* 半角转换为全角
*
* @param input
* @return
*/
public static String ToDBC(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char) (c[i] - 65248);
}
return new String(c);
}
public static void showToast(Context context, String s) {
if (toast == null) {
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
toast.show();
oneTime = System.currentTimeMillis();
} else {
twoTime = System.currentTimeMillis();
if (s.equals(oldMsg)) {
if (twoTime - oneTime > Toast.LENGTH_SHORT) {
toast.show();
}
} else {
oldMsg = s;
toast.setText(s);
toast.show();
}
}
oneTime = twoTime;
}
public static boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = {0, 0};
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
public static boolean isIntent(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (manager == null) {
return false;
}
// 检查网络连接,如果无网络可用,就不需要进行连网操作等
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
if (networkinfo == null || !networkinfo.isAvailable()) {
return false;
}
return true;
}
public static String getTime(int time) {
int min = time / 60;
int sec = time % 60;
if (sec > 0) {
return String.valueOf(min + 1);
} else {
return String.valueOf(min);
}
}
public static String getTimeClick(int time) {
StringBuffer timeClick = new StringBuffer();
int min = time / 60;
int sec = time % 60;
timeClick.append(min >= 10 ? (int) Math.ceil(min / 10) : 0)
.append(min % 10)
.append(":")
.append(sec >= 10 ? (int) Math.ceil(sec / 10) : 0)
.append(sec % 10);
return timeClick.toString();
}
public static String getVersionName(Context context) {
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名0代表是获取版本信息
PackageInfo packInfo;
try {
packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
String version = packInfo.versionName.replaceAll("[a-zA-Z]", "").trim();
;
return version;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static float dp2px(Resources resources, float dp) {
final float scale = resources.getDisplayMetrics().density;
return dp * scale + 0.5f;
}
public static float sp2px(Resources resources, float sp) {
final float scale = resources.getDisplayMetrics().scaledDensity;
return sp * scale;
}
public static String getTime() {
long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = new Date(time);
String t1 = format.format(d1);
return t1;
}
private static void getAdmin(Context context, ComponentName componentName) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "宏云萌书院OS");
context.startActivity(intent);
}
/**
* 获取设备序列号
*
* @return
*/
public static String getSerial() {
return Build.SERIAL;
// return "QNS3AI000111";
// return "QNW8WJ900002";
}
public static final long A_GB = 1073741824;
public static final long A_MB = 1048576;
public static final int A_KB = 1024;
public static String fmtSpace(long space) {
if (space <= 0) {
return "0";
}
double gbValue = (double) space / A_GB;
if (gbValue >= 1) {
return String.format("%.2fGB", gbValue);
} else {
double mbValue = (double) space / A_MB;
// Log.e("GB", "gbvalue=" + mbValue);
if (mbValue >= 1) {
return String.format("%.2fMB", mbValue);
} else {
final double kbValue = space / A_KB;
return String.format("%.2fKB", kbValue);
}
}
}
public static String transferLongToDate(Long millSec) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(millSec);
return sdf.format(date);
}
public static String getSn() {
return Build.SERIAL;
}
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
try {
// if (content == null || "".equals(content)) {
// return false;
// }
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 1); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
} catch (WriterException e) {
e.printStackTrace();
}
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
//
// if (logoBm != null) {
// bitmap = addLogo(bitmap, logoBm);
// }
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的
// 内存消耗巨大!
return bitmap;
// return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//判断是否为系统应用
public static boolean isSystemApp(Context context, String pkgName) {
boolean isSystemApp = false;
PackageInfo pi = null;
try {
PackageManager pm = context.getPackageManager();
pi = pm.getPackageInfo(pkgName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
Log.e("isSystemApp", e.getMessage(), e);
}
// 是系统中已安装的应用
if (pi != null) {
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
isSystemApp = isSysApp || isSysUpd;
}
return isSystemApp;
}
public static Bitmap getRoundedBitmap(Bitmap mBitmap, Context context) {
Bitmap bgBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap mask = BitmapFactory.decodeResource(context.getResources(), R.drawable.mask);
int width = mask.getWidth();
int height = mask.getHeight();
Bitmap bitmapScale = Bitmap.createScaledBitmap(mBitmap, width, height, true);
// Palette p = Palette.from(mBitmap).generate();
// Palette.Swatch vibrant = p.getVibrantSwatch();//有活力的
// int color = vibrant.getRgb(); //样本中的像素数量
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas();
Paint paint = new Paint();
canvas.setBitmap(result);
// canvas.drawColor(color);
canvas.drawBitmap(mask, 0, 0, paint);
// paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmapScale, 0, 0, paint);
// return result;
Bitmap result2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas2 = new Canvas();
Paint paint2 = new Paint();
canvas2.setBitmap(result2);
canvas2.drawBitmap(mask, 0, 0, paint2);
paint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas2.drawBitmap(result, 0, 0, paint2);
return result2;
// Canvas mCanvas = new Canvas();
// mCanvas.setBitmap(bgBitmap);
// Paint mPaint = new Paint();
// RectF mRectM = new RectF(scaleM, scaleM, mBitmap.getWidth() - scaleM, mBitmap.getHeight() - scaleM); //设置剪裁圆角的区域
// Rect mRect = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
// RectF mRectF = mRectM;
//
// float roundPx = 15; //圆角半径
// mPaint.setAntiAlias(true);
// //Log.d("wy"+TAG,"mBitmap.getWidth()="+mBitmap.getWidth()+", mBitmap.getHeight()="+mBitmap.getHeight());
// mCanvas.drawRoundRect(mRectF, roundPx, roundPx, mPaint);
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// mCanvas.drawBitmap(mBitmap, mRect, mRect, mPaint);
// return bgBitmap;
}
}