update:2020.10.19

fix:设备号获取问题,兼容Android10,报错修复
add:
This commit is contained in:
2020-10-19 18:41:47 +08:00
parent 12172e6706
commit 49b19777b9
13 changed files with 1380 additions and 544 deletions

View File

@@ -15,8 +15,8 @@ android {
applicationId "com.info.sn"
minSdkVersion 23
targetSdkVersion 28
versionCode 19
versionName "1.1.9"
versionCode 21
versionName "1.2.1"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
@@ -137,5 +137,7 @@ dependencies {
annotationProcessor 'com.arialyy.aria:compiler:3.8.5'
implementation "org.java-websocket:Java-WebSocket:1.4.1"
//高德地图定位
implementation 'com.amap.api:location:5.1.0'
}

View File

@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.info.sn">
package="com.info.sn"
android:sharedUserId="android.uid.system">
<uses-permission android:name="android.permission.ACTION_SCREEN_ON" />
<uses-permission android:name="android.permission.ACTION_SCREEN_OFF" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.MASTER_CLEAR" />
<uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE" />
@@ -16,31 +17,93 @@
<!-- Required -->
<permission
android:name="com.info.sn.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" /> <!-- Required 一些系统要求的权限,如访问网络等 -->
android:protectionLevel="signature" />
<!-- Required 一些系统要求的权限,如访问网络等 -->
<uses-permission android:name="com.info.sn.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
<!-- Optional for location -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- 用于开启 debug 版本的应用在6.0 系统上 层叠窗口权限 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<!-- Normal Permissions 不需要运行时注册 -->
<!-- 获取运营商信息,用于支持提供运营商信息相关的接口 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 用于访问wifi网络信息wifi信息会用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 这个权限用于获取wifi的获取权限wifi信息会用来进行网络定位 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限是示例中的后台唤醒定位需要的权限 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- 需要运行时注册的权限 -->
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 用于提高GPS定位速度 -->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!-- 写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 读取缓存数据 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 用于读取手机当前的状态 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--如果设置了target >= 28 如果需要启动后台定位则必须声明这个权限-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!--如果您的应用需要后台定位权限且有可能运行在Android Q设备上,并且设置了target>28必须增加这个权限声明-->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher"
android:networkSecurityConfig="@xml/network"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".receiver.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.BATTERY_LEVEL_CHANGED" />
<action android:name="android.intent.action.BATTERY_LOW" />
<action android:name="android.intent.action.BATTERY_OKAY" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
<action android:name="android.intent.action.DATE_CHANGED" />
<action android:name="android.intent.action.TIME_TICK" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name=".receiver.APKinstallReceiver"
android:enabled="true"
@@ -52,17 +115,8 @@
<data android:scheme="package" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.info.sn.fileprovider"
@@ -71,7 +125,8 @@
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider> <!-- Rich push 核心功能 since 2.0.6 -->
</provider>
<!-- Rich push 核心功能 since 2.0.6 -->
<activity
android:name="cn.jpush.android.ui.PopWinActivity"
android:exported="false"
@@ -158,7 +213,7 @@
</activity> <!-- Since JCore2.0.0 Required SDK核心功能 -->
<!-- 这个Service要继承JCommonService -->
<service
android:name=".jpush.PushService"
android:name="com.info.sn.jpush.PushService"
android:process=":pushcore">
<intent-filter>
<action android:name="cn.jiguang.user.service.action" />
@@ -168,26 +223,9 @@
<service android:name=".service.MyDownloadService" />
<service android:name=".service.StepService" />
<!-- User defined. For test only 用户自定义的广播接收器 -->
<receiver
android:name=".receiver.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.BATTERY_LEVEL_CHANGED" />
<action android:name="android.intent.action.BATTERY_LOW" />
<action android:name="android.intent.action.BATTERY_OKAY" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
<action android:name="android.intent.action.DATE_CHANGED" />
<action android:name="android.intent.action.TIME_TICK" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver> <!-- User defined. For test only 用户自定义的广播接收器 -->
<receiver
android:name=".jpush.MyReceiver"
android:name="com.info.sn.jpush.MyReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
@@ -199,19 +237,24 @@
<category android:name="com.info.sn" />
</intent-filter>
</receiver> <!-- User defined. For test only 用户自定义接收消息器,3.0.7开始支持,目前新tag/alias接口设置结果会在该广播接收器对应的方法中回调 -->
<receiver android:name=".jpush.MyJPushMessageReceiver">
<receiver android:name="com.info.sn.jpush.MyJPushMessageReceiver">
<intent-filter>
<action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
<category android:name="com.info.sn" />
</intent-filter>
</receiver> <!-- Required . Enable it you can get statistics data with channel -->
</receiver>
<!-- Required . Enable it you can get statistics data with channel -->
<meta-data
android:name="JPUSH_CHANNEL"
android:value="developer-default" />
<meta-data
android:name="JPUSH_APPKEY"
android:value="edf9cec22731b8b2fed56ee6" />
<!-- 设置key -->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="83869aed8624eb00615c2b6d3d15d777" />
</application>
</manifest>

View File

@@ -27,9 +27,15 @@ import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.info.sn.base.CheckPermissionsActivity;
import com.info.sn.bean.UserInfo;
import com.info.sn.jpush.ExampleUtil;
import com.info.sn.jpush.LocalBroadcastManager;
@@ -41,6 +47,7 @@ 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.info.sn.utils.amapUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
@@ -61,7 +68,9 @@ 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 class MainActivity extends CheckPermissionsActivity implements AMapLocationListener {
AMapLocationClient locationClient = null;
public static final String REFRESHACTION = BuildConfig.APPLICATION_ID + ".REFRESH";
public static boolean isForeground = false;
private ImageView imageView, exit;
@@ -77,9 +86,20 @@ public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationClient = new AMapLocationClient(this);
AMapLocationClientOption option = new AMapLocationClientOption();
option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
option.setNeedAddress(true);
locationClient.setLocationOption(option);
//设置定位模式为AMapLocationMode.Hight_Accuracy高精度模式。
//设置定位监听
locationClient.setLocationListener(this);
locationClient.startLocation();
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);
@@ -110,6 +130,67 @@ public class MainActivity extends AppCompatActivity {
registerReceiver(mRefreshReceiver, filter);
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
StringBuffer sb = new StringBuffer();
//errCode等于0代表定位成功其他的为定位失败具体的可以参照官网定位错误码说明
if (aMapLocation.getErrorCode() == 0) {
sb.append("定位成功" + "\n");
sb.append("定位类型: " + aMapLocation.getLocationType() + "\n");
sb.append("位置: " + aMapLocation.getAddress() + "\n");
sb.append("经 度 : " + aMapLocation.getLongitude() + "\n");
sb.append("纬 度 : " + aMapLocation.getLatitude() + "\n");
sb.append("精 度 : " + aMapLocation.getAccuracy() + "" + "\n");
sb.append("提供者 : " + aMapLocation.getProvider() + "\n");
sb.append("速 度 : " + aMapLocation.getSpeed() + "米/秒" + "\n");
sb.append("角 度 : " + aMapLocation.getBearing() + "\n");
// 定位完成的时间
sb.append("定位时间: " + amapUtils.formatUTC(aMapLocation.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
} else {
//定位失败
sb.append("定位失败" + "\n");
sb.append("错误码:" + aMapLocation.getErrorCode() + "\n");
sb.append("错误信息:" + aMapLocation.getErrorInfo() + "\n");
sb.append("错误描述:" + aMapLocation.getLocationDetail() + "\n");
}
sb.append("***定位质量报告***").append("\n");
sb.append("* WIFI开关").append(aMapLocation.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
sb.append("* GPS状态").append(getGPSStatusString(aMapLocation.getLocationQualityReport().getGPSStatus())).append("\n");
sb.append("* GPS星数").append(aMapLocation.getLocationQualityReport().getGPSSatellites()).append("\n");
sb.append("****************").append("\n");
// 定位之后的回调时间
sb.append("回调时间: " + amapUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
Log.e("onLocationChanged", sb.toString());
}
/**
* 获取GPS状态的字符串
*
* @param statusCode GPS状态码
* @return
*/
private String getGPSStatusString(int statusCode) {
String str = "";
switch (statusCode) {
case AMapLocationQualityReport.GPS_STATUS_OK:
str = "GPS状态正常";
break;
case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
str = "手机中没有GPS Provider无法进行GPS定位";
break;
case AMapLocationQualityReport.GPS_STATUS_OFF:
str = "GPS关闭建议开启GPS提高定位质量";
break;
case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
str = "选择的定位模式中不包含GPS定位建议选择包含GPS定位的模式提高定位质量";
break;
case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
str = "没有GPS定位权限建议开启gps定位权限";
break;
}
return str;
}
public class RefreshReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
@@ -197,7 +278,7 @@ public class MainActivity extends AppCompatActivity {
}
private void setImageAndText(ImageView imageView, String text) {
Bitmap bitmap = Utils.createQRImage(Utils.getSn(), 250, 250);
Bitmap bitmap = Utils.createQRImage(Utils.getSerial(), 250, 250);
imageView.setImageBitmap(bitmap);
tv_note.setText(text);
}

View File

@@ -13,18 +13,22 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.task.DownloadTask;
import com.blankj.utilcode.util.ToastUtils;
import com.info.sn.jpush.LocalBroadcastManager;
import com.info.sn.jpush.TagAliasOperatorHelper;
import com.info.sn.network.UrlPath;
import com.info.sn.network.api.HTTPInterface;
import com.info.sn.service.MyDownloadService;
@@ -47,8 +51,13 @@ import java.net.URI;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import rx.Observable;
import rx.functions.Action1;
//import com.blankj.utilcode.util.NetworkUtils;
@@ -68,7 +77,35 @@ public class MyApplication extends Application {
// NetworkUtils.registerNetworkStatusChangedListener(this);
Aria.init(this);
Aria.download(this).resumeAllTask();
if (!BuildConfig.DEBUG) {
catchException();
}
}
private void catchException() {
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
Log.d("捕获异常子线程:", Thread.currentThread().getName() +
"在:" + e.getStackTrace()[0].getClassName());
}
}
);
//下面是新增方法!
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
while (true) {
try {
Looper.loop(); //会先执行这个方法,然后在执行下面的异常捕获方法!
} catch (Exception e) {
Log.d("捕获异常主线程:", Thread.currentThread().getName() + "在:" + e.getStackTrace()[0].getClassName());
e.printStackTrace();
}
}
}
});
}
// protected void attachBaseContext(Context newBase) {
@@ -94,69 +131,153 @@ public class MyApplication extends Application {
return context;
}
public static String getTaskPackname() {
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
@SuppressLint("WrongConstant") 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;
// public void onTagOperatorResult(JPushMessage jPushMessage) {
// if (jPushMessage == null) {
// return;
// }
// String s = "tags:\t";
// int errorCode = jPushMessage.getErrorCode();
// switch (errorCode) {
// case 0:
// Log.e("jiguangInterface", s + "Tag绑定成功");
// break;
// case 6001:
// Log.e("jiguangInterface", s + "无效的设置");
// break;
// case 6005:
// Log.e("jiguangInterface", s + "某一个 tag 字符串不合法");
// ToastUtil.show("设备标签不合法,联系管理员修改\t" + "code:6005");
// break;
// case 6006:
// Log.e("jiguangInterface", s + "某一个 tag 超长");
// ToastUtil.show("设备标签过长,联系管理员修改\t" + "code:6006");
// break;
// case 6007:
// Log.e("jiguangInterface", s + "tags 数量超出限制");
// ToastUtil.show("设备标签数量超出限制,联系管理员修改\t" + "code:6007");
// break;
// case 6008:
// Log.e("jiguangInterface", s + "tag 超出总长度限制");
// ToastUtil.show("设备标签超出总长度限制,联系管理员修改\t" + "code:6008");
// break;
// case 6011:
// Log.e("jiguangInterface", s + "短时间内操作过于频繁");
// break;
// case 6013:
// Log.e("jiguangInterface", s + "用户设备时间轴异常");
// ToastUtil.show("用户设备时间轴异常,修改后重新登陆\t" + "code:6013");
// break;
// case 6018:
// Log.e("jiguangInterface", s + "Tags 过多");
// ToastUtil.show("设备标签数量超出限制,联系管理员修改\t" + "code:6018");
// break;
// case 6021:
// Log.e("jiguangInterface", s + "tags 操作正在进行中");
// break;
//
// //需要重新设置
// case 6002:
// Log.e("jiguangInterface", s + "设置超时,请重试");
// setJpushTags();
// break;
// case 6014:
// Log.e("jiguangInterface", s + "服务器繁忙,建议重试");
// setJpushTags();
// break;
// case 6020:
// Log.e("jiguangInterface", s + "建议过一段时间再设置");
// setJpushTags();
// break;
// case 6024:
// Log.e("jiguangInterface", s + "服务器内部错误");
// setJpushTags();
// break;
// }
// }
// public static void setJpushTags() {
// Log.e("jiguangInterface", "10s后重新设置tags");
// Observable.timer(10000, TimeUnit.MILLISECONDS)
// .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
// .subscribe(new Action1<Long>() {
// @Override
// public void call(Long aLong) {
// HTTPInterface.setJpushTags(context);
// }
// });
// }
public void onAliasOperatorResult(JPushMessage jPushMessage) {
if (jPushMessage == null) {
return;
}
String s = "alias:\t";
int errorCode = jPushMessage.getErrorCode();
switch (errorCode) {
case 0:
Log.e("jiguangInterface", s + "Alias绑定成功");
break;
case 6001:
Log.e("jiguangInterface", s + "无效的设置");
break;
case 6011:
Log.e("jiguangInterface", s + "短时间内操作过于频繁");
break;
case 6013:
Log.e("jiguangInterface", s + "用户设备时间轴异常");
ToastUtil.show("用户设备时间轴异常,修改后重新登陆\t" + s + "code:6013");
break;
case 6022:
Log.e("jiguangInterface", s + "alias 操作正在进行中");
break;
//需要重新设置
case 6002:
Log.e("jiguangInterface", s + "设置超时,请重试");
setJpushAlias();
break;
case 6014:
Log.e("jiguangInterface", s + "服务器繁忙,建议重试");
setJpushAlias();
break;
case 6020:
Log.e("jiguangInterface", s + "建议过一段时间再设置");
setJpushAlias();
break;
case 6024:
Log.e("jiguangInterface", s + "服务器内部错误");
setJpushAlias();
break;
case 6017:
case 6027:
Log.e("jiguangInterface", s + "别名绑定的设备数超过限制");
clean();
setJpushAlias();
break;
}
// 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;
public static void setJpushAlias() {
Log.e("jiguangInterface", "10s后重新设置alias");
Observable.timer(10000, TimeUnit.MILLISECONDS)
.observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
JPushInterface.setAlias(context, TagAliasOperatorHelper.sequence++, Utils.getSerial());
}
});
}
public void clean() {
//alias的绑定的设备超过10个但是alias应该是一个设备对应一个在重置设备后jpush的regid会变动所以需要清除
//https://docs.jiguang.cn/jpush/server/push/rest_api_v3_device/#_5
// HTTPInterface.cleanJpushAlias(Utils.getSerial());
}
//定义接收极光推送消息的类型。
//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";
private static final String JIGUANG_BIND_DEVIVES = "11";
synchronized public void manageCustomMessage(CustomMessage customMessage) {
@@ -171,40 +292,48 @@ public class MyApplication extends Application {
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;
case JIGUANG_BIND_DEVIVES:
bindService(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;
// case JIGUANG_BIND_DEVIVES:
// bindService(EXTRA);
// break;
// case JIGUANG_TFMEDIA:
//
// break;
// case JIGUANG_CAMRERA:
// break;
// case JIGUANG_PHONE:
// break;
// }
}
@@ -230,329 +359,20 @@ public class MyApplication extends Application {
//仅充电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_allow = Settings.System.putString(getContentResolver(), "qch_jgy_network_allow", package0);
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_allow + ":" + Settings.System.getString(getContentResolver(), "qch_jgy_network_allow"));
} else {
boolean qch_jgy_network_allow = Settings.System.putString(getContentResolver(), "qch_jgy_network_allow", "invalid");
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_allow + ":" + 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");
if (Aria.download(this).taskExists(url)) {
List<DownloadEntity> entity = Aria.download(this).getDownloadEntity(url);
for (DownloadEntity downloadEntity : entity) {
Aria.download(this).load(downloadEntity.getId()).cancel(true);
}
}
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);
// }
// });
Aria.download(this).resumeAllTask();
} 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());
}
}
synchronized void bindService(String json) {
ToastUtil.debugShow("收到绑定设备请求");
try {
JSONObject object = new JSONObject(json);
String userName = object.getString("member_name");
final String id = object.getString("id");
String phoneNum = object.getString("member_phone");
final CustomDialog dialog = new CustomDialog(getAppContext());
dialog.setMessage(phoneNum + "的用户请求绑定你的平板")
.setTitle("绑定请求")
.setPositive("允许")
.setNegtive("拒绝")
// .setSingle(true)
.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
@Override
public void onPositiveClick() {
bind(id);
dialog.dismiss();
}
@Override
public void onNegtiveClick() {
ToastUtil.show("设备取消绑定");
dialog.dismiss();
}
});
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
// AlertDialog.Builder builder = new AlertDialog.Builder(this)
// .setTitle("设备绑定")
// .setIcon(R.mipmap.ic_launcher)
// .setCancelable(false)
// .setMessage("用户:“" + userName + "”" + "\n手机“" + phoneNum + "”" + "\n请求绑定此设备")
// .setPositiveButton("确认绑定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// bind(id);
// }
// })
// .setNegativeButton("取消", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// ToastUtil.show("设备取消绑定");
// }
// });
// AlertDialog ad = builder.create();
// ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失
// ad.show();
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("bindService", e.getMessage());
}
}
synchronized private void bind(String id) {
OkGo.<String>post(UrlPath.BIND_DEVICES)
.params("id", id)
.params("sn", Utils.getSerial())
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
String s = response.body();
try {
JSONObject jsonObject = new JSONObject(s);
int code = jsonObject.getInt("code");
String msg = jsonObject.getString("msg");
if (code == 200) {
ToastUtil.show("绑定成功");
} else {
ToastUtil.show(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.REFRESHACTION);
sendBroadcast(intent);
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Log.e("bind", response.getException().getMessage());
}
});
}
// @Override
// public void onDisconnected() {
// LogUtils.e("onDisconnected", "网络断开");

View File

@@ -0,0 +1,227 @@
/**
*
*/
package com.info.sn.base;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import com.info.sn.R;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* 继承了Activity实现Android6.0的运行时权限检测
* 需要进行运行时权限检测的Activity可以继承这个类
*
* @创建时间2016年5月27日 下午3:01:31
* @项目名称: AMapLocationDemo
* @author hongming.wang
* @文件名称PermissionsChecker.java
* @类型名称PermissionsChecker
* @since 2.5.0
*/
public class CheckPermissionsActivity extends Activity {
//是否需要检测后台定位权限设置为true时如果用户没有给予后台定位权限会弹窗提示
private boolean needCheckBackLocation = false;
//如果设置了target > 28需要增加这个权限否则不会弹出"始终允许"这个选择框
private static String BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION";
/**
* 需要进行检测的权限数组
*/
protected String[] needPermissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE
};
private static final int PERMISSON_REQUESTCODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT > 28
&& getApplicationContext().getApplicationInfo().targetSdkVersion > 28) {
needPermissions = new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
BACKGROUND_LOCATION_PERMISSION
};
}
}
/**
* 判断是否需要检测,防止不停的弹框
*/
private boolean isNeedCheck = true;
@Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= 23
&& getApplicationInfo().targetSdkVersion >= 23) {
if (isNeedCheck) {
checkPermissions(needPermissions);
}
}
}
/**
*
* @param permissions
* @since 2.5.0
*
*/
private void checkPermissions(String... permissions) {
try {
if (Build.VERSION.SDK_INT >= 23
&& getApplicationInfo().targetSdkVersion >= 23) {
List<String> needRequestPermissonList = findDeniedPermissions(permissions);
if (null != needRequestPermissonList
&& needRequestPermissonList.size() > 0) {
String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
int.class});
method.invoke(this, array, PERMISSON_REQUESTCODE);
}
}
} catch (Throwable e) {
}
}
/**
* 获取权限集中需要申请权限的列表
*
* @param permissions
* @return
* @since 2.5.0
*
*/
private List<String> findDeniedPermissions(String[] permissions) {
List<String> needRequestPermissonList = new ArrayList<String>();
if (Build.VERSION.SDK_INT >= 23
&& getApplicationInfo().targetSdkVersion >= 23){
try {
for (String perm : permissions) {
Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
String.class);
if ((Integer)checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
|| (Boolean)shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
if(!needCheckBackLocation
&& BACKGROUND_LOCATION_PERMISSION.equals(perm)) {
continue;
}
needRequestPermissonList.add(perm);
}
}
} catch (Throwable e) {
}
}
return needRequestPermissonList;
}
/**
* 检测是否所有的权限都已经授权
* @param grantResults
* @return
* @since 2.5.0
*
*/
private boolean verifyPermissions(int[] grantResults) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
@Override
@TargetApi(23)
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] paramArrayOfInt) {
if (requestCode == PERMISSON_REQUESTCODE) {
if (!verifyPermissions(paramArrayOfInt)) {
showMissingPermissionDialog();
isNeedCheck = false;
}
}
}
/**
* 显示提示信息
*
* @since 2.5.0
*
*/
private void showMissingPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.notifyTitle);
builder.setMessage(R.string.notifyMsg);
// 拒绝, 退出应用
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setPositiveButton(R.string.setting,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startAppSettings();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 启动应用的设置
*
* @since 2.5.0
*
*/
private void startAppSettings() {
Intent intent = new Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

View File

@@ -29,6 +29,7 @@ public class MyJPushMessageReceiver extends JPushMessageReceiver {
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context, jPushMessage);
super.onAliasOperatorResult(context, jPushMessage);
MyApplication.getInstance().onAliasOperatorResult(jPushMessage);
}
@Override
@@ -40,7 +41,7 @@ public class MyJPushMessageReceiver extends JPushMessageReceiver {
@Override
public void onMessage(Context context, CustomMessage customMessage) {
super.onMessage(context, customMessage);
MyApplication.getInstance().manageCustomMessage(customMessage);
// MyApplication.getInstance().manageCustomMessage(customMessage);
}

View File

@@ -1,129 +1,614 @@
package com.info.sn.jpush;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.info.sn.MainActivity;
import com.info.sn.network.UrlPath;
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.info.sn.utils.Utils;
import com.info.sn.view.CustomDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import cn.jpush.android.api.JPushInterface;
/**
* 自定义接收器
*
* <p>
* 如果不定义这个 Receiver
* 1) 默认用户会打开主界面
* 2) 接收不到自定义消息
*/
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "JIGUANG-Example";
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));
@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...
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_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_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] 用户点击打开了通知");
} 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);
//打开自定义的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_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){
} 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;
}
// 打印所有的 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();
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!");
}
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) {
} else {
sb.append("\nkey:" + key + ", value:" + bundle.get(key));
}
}
return sb.toString();
}
//定义接收极光推送消息的类型。
private static final String JIGUANG_GET_DRIVELINE = "1";
//1.获取设备在线信息
private static final String JIGUANG_GET_STARTTIME = "2";
// 2.获取当前正在运行得应用和电量
private static final String JIGUANG_USB_STATE = "3";
// 3.数据线传输管控
private static final String JIGUANG_TFCARD_STATE = "4";
// 4.TF卡管控
private static final String JIGUANG_BLUETOOTH_STATE = "5";
// 5.蓝牙管控
private static final String JIGUANG_BROWSER_URLPATH = "6";
// 6.浏览器上网管控
private static final String JIGUANG_APP_NETWORKSTATE = "7";
// 7.应用联网管控
private static final String JIGUANG_APP_LOCKEDSTATE = "8";
// 8.应用锁管控
private static final String JIGUANG_FORCE_INSTALLAPK = "9";
// 9.强制安装应用
private static final String JIGUANG_FORCE_UNINSTALLAPK = "10";
// 10.强制卸载应用
private static final String JIGUANG_BIND_DEVIVES = "11";
// 11.绑定设备
private static final String JIGUANG_TFMEDIA = "12";
//12.影音格式管控
private static final String JIGUANG_CAMRERA = "13";
//13.摄像头管控
private static final String JIGUANG_PHONE = "14";
//14.电话管控管控
private static final String JIGUANG_DISABLE_UPDATAE = "15";
//14.电话管控管控
private static final String JIGUANG_APP_WEBSITE = "16";
//16.app内部网址管控
//
//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);
// }
String sn_id = (String) SPUtils.get(context, "sn_id", "-1");
String member_id = (String) SPUtils.get(context, "member_id", "-1");
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
String title = bundle.getString(JPushInterface.EXTRA_TITLE);
String type = bundle.getString(JPushInterface.EXTRA_CONTENT_TYPE);
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
switch (message) {
case JIGUANG_GET_DRIVELINE:
HTTPInterface.getDriveState(member_id, sn_id);
break;
case JIGUANG_GET_STARTTIME:
sendStartTime(context, extras);
break;
case JIGUANG_USB_STATE:
setUsbState(context, extras);
break;
case JIGUANG_TFCARD_STATE:
setTfcardState(context, extras);
break;
case JIGUANG_BLUETOOTH_STATE:
setBluetoothState(context, extras);
break;
case JIGUANG_BROWSER_URLPATH:
setBrowserUrlpath(context, extras);
break;
case JIGUANG_APP_NETWORKSTATE:
setAppNetworkstate(context, extras);
break;
case JIGUANG_APP_LOCKEDSTATE:
setAppLockedstate(context, extras);
break;
case JIGUANG_FORCE_INSTALLAPK:
intallApk(extras);
break;
case JIGUANG_FORCE_UNINSTALLAPK:
unintallApk(context, extras);
break;
case JIGUANG_BIND_DEVIVES:
bindService(context, extras);
break;
case JIGUANG_TFMEDIA:
break;
case JIGUANG_CAMRERA:
break;
case JIGUANG_PHONE:
break;
case JIGUANG_DISABLE_UPDATAE:
break;
case JIGUANG_APP_WEBSITE:
break;
}
}
synchronized private void sendStartTime(Context context, String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String random = extra.getString("random");
int battery = getSystemBattery(context);
HTTPInterface.sendStartTime(context, 0, getTaskPackname(context), battery, random);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/**
* 实时获取电量
*/
public static int getSystemBattery(Context context) {
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;
}
public static String getTaskPackname(Context context) {
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
@SuppressLint("WrongConstant") 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;
}
synchronized private void setUsbState(Context context, 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(context.getContentResolver(), "qch_usb_choose", "usb_charge");
LogUtils.e("setUsbState:", Settings.System.getString(context.getContentResolver(), "qch_usb_choose"));
} else {
boolean qch_usb_choose = Settings.System.putString(context.getContentResolver(), "qch_usb_choose", "usb_mtp");
LogUtils.e("setUsbState:", Settings.System.getString(context.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(Context context, 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(context.getContentResolver(), "qch_sdcard_forbid_on", is_tf);
if (qch_sdcard_forbid_on) {
LogUtils.e("setTfcardState:", Settings.System.getString(context.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(Context context, 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(context.getContentResolver(), "qch_bt_forbid_on", is_bluetooth);
if (qch_bt_forbid_on) {
LogUtils.e("setBluetoothState:", Settings.System.getString(context.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(Context context, String jsonArray) {
if (jsonArray.length() > 0) {
try {
JSONObject extra = new JSONObject(jsonArray);
String white = extra.getString("white");
if (white != null && !white.equals("")) {
boolean whiteList = Settings.System.putString(context.getContentResolver(), "DeselectBrowserArray", white);
Log.e("SystemSetting", "setBrowserList---------" + whiteList + ":" + white);
} else {
Settings.System.putString(context.getContentResolver(), "DeselectBrowserArray", " ");
}
String black = extra.getString("black");
if (black != null && !black.equals("")) {
boolean blackList = Settings.System.putString(context.getContentResolver(), "qch_webblack_url", black);
Log.e("SystemSetting", "setBrowserList---------" + blackList + ":" + black);
} else {
Settings.System.putString(context.getContentResolver(), "qch_webblack_url", " ");
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setBrowserUrlpath", e.getMessage());
}
} else {
boolean setBrowserUrlpath = Settings.System.putString(context.getContentResolver(), "DeselectBrowserArray", "invalid");
ToastUtil.debugShow("setBrowserUrlpath jsonArray is NULL,set default: " + setBrowserUrlpath);
}
}
synchronized private void setAppNetworkstate(Context context, 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_allow = Settings.System.putString(context.getContentResolver(), "qch_jgy_network_allow", package0);
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_allow + ":" + Settings.System.getString(context.getContentResolver(), "qch_jgy_network_allow"));
} else {
boolean qch_jgy_network_allow = Settings.System.putString(context.getContentResolver(), "qch_jgy_network_allow", "invalid");
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_allow + ":" + Settings.System.getString(context.getContentResolver(), "qch_jgy_network_allow"));
}
if (package1.length() != 0) {
boolean qch_jgy_network_disallow = Settings.System.putString(context.getContentResolver(), "qch_jgy_network_disallow", package1);
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_disallow + ":" + Settings.System.getString(context.getContentResolver(), "qch_jgy_network_disallow"));
} else {
boolean qch_jgy_network_disallow = Settings.System.putString(context.getContentResolver(), "qch_jgy_network_disallow", "invalid");
LogUtils.e("fht", "setAppNetworkstate::" + qch_jgy_network_disallow + ":" + Settings.System.getString(context.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(Context context, 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 = context.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");
if (Aria.download(this).taskExists(url)) {
List<DownloadEntity> entity = Aria.download(this).getDownloadEntity(url);
for (DownloadEntity downloadEntity : entity) {
Aria.download(this).load(downloadEntity.getId()).cancel(true);
}
}
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);
// }
// });
Aria.download(this).resumeAllTask();
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("intallApk", e.getMessage());
}
}
synchronized private void unintallApk(Context context, 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(context.getApplicationContext().getPackageName())) {
if (!ApkUtils.isAvailable(context.getApplicationContext(), packageName)) {
HTTPInterface.setAppuninstallInfo(sn_id, packageName);
} else {
ApkUtils.deleteApkInSilence(packageName);
}
}
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("unintallApk", e.getMessage());
}
}
synchronized void bindService(final Context context, String json) {
ToastUtil.debugShow("收到绑定设备请求");
try {
// com.alibaba.fastjson.JSONObject jsonObject= JSON.parseObject(json);
// String userName =jsonObject.getString("member_name");
// final String id =jsonObject.getString("id");
// String phoneNum =jsonObject.getString("member_phone");
JSONObject object = new JSONObject(json);
String userName = object.getString("member_name");
final String id = object.getString("id");
String phoneNum = object.getString("member_phone");
final CustomDialog dialog = new CustomDialog(context);
dialog.setMessage(phoneNum + "的用户请求绑定你的平板")
.setTitle("绑定请求")
.setPositive("允许")
.setNegtive("拒绝")
// .setSingle(true)
.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
@Override
public void onPositiveClick() {
bind(context, id);
dialog.dismiss();
}
@Override
public void onNegtiveClick() {
ToastUtil.show("设备取消绑定");
dialog.dismiss();
}
});
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
// AlertDialog.Builder builder = new AlertDialog.Builder(this)
// .setTitle("设备绑定")
// .setIcon(R.mipmap.ic_launcher)
// .setCancelable(false)
// .setMessage("用户:“" + userName + "”" + "\n手机“" + phoneNum + "”" + "\n请求绑定此设备")
// .setPositiveButton("确认绑定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// bind(id);
// }
// })
// .setNegativeButton("取消", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// ToastUtil.show("设备取消绑定");
// }
// });
// AlertDialog ad = builder.create();
// ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失
// ad.show();
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("bindService", e.getMessage());
}
}
synchronized private void bind(final Context context, String id) {
OkGo.<String>post(UrlPath.BIND_DEVICES)
.params("id", id)
.params("sn", Utils.getSerial())
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
String s = response.body();
try {
JSONObject jsonObject = new JSONObject(s);
int code = jsonObject.getInt("code");
String msg = jsonObject.getString("msg");
if (code == 200) {
ToastUtil.show("绑定成功");
} else {
ToastUtil.show(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.REFRESHACTION);
context.sendBroadcast(intent);
}
@Override
public void onError(Response<String> response) {
super.onError(response);
Log.e("bind", response.getException().getMessage());
}
});
}
}
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
}
}
}

View File

@@ -23,5 +23,6 @@ public class UrlPath {
//获取所有应用包名
public final static String BIND_DEVICES = HOMEPATHRUL + "Member/binding";
//绑定设备消息
public final static String SET_BROWSER_URL = HOMEPATHRUL + "Contorl/snbrower";
//浏览器网址管控
}

View File

@@ -6,14 +6,17 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import androidx.annotation.RequiresApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.info.sn.bean.MessageWhat;
import com.info.sn.bean.UserInfo;
import com.info.sn.jpush.TagAliasOperatorHelper;
import com.info.sn.network.UrlPath;
import com.info.sn.utils.LogUtils;
import com.info.sn.utils.SPUtils;
@@ -24,15 +27,20 @@ import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import okhttp3.Call;
import okhttp3.internal.Util;
public class HTTPInterface {
//获取设备信息接口
public static synchronized void checkDevicesInfo(final Handler handler) {
OkGo.<String>post(UrlPath.SNINFO)
.params("sn", Utils.getSn())
.params("sn", Utils.getSerial())
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
@@ -161,6 +169,7 @@ public class HTTPInterface {
}
});
}
synchronized public static void checkUpdateByself(final Handler handler, String packageName, String versionCode) {
OkGo.<String>post(UrlPath.GET_APP_UPDATE)
.params("code", versionCode)
@@ -279,6 +288,7 @@ public class HTTPInterface {
}
});
}
synchronized public static void getAllAppPackageName(final Handler handler) {
OkGo.<String>get(UrlPath.GET_ALL_PACKAGENAME).execute(new StringCallback() {
@Override
@@ -318,4 +328,42 @@ public class HTTPInterface {
}
private void setBrowser(final Context context) {
OkGo.<String>post(UrlPath.SET_BROWSER_URL)
.params("sn", Utils.getSerial())
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
try {
JSONObject jsonObject = JSON.parseObject(response.body());
int code = jsonObject.getInteger("code");
String msg = jsonObject.getString("msg");
if (code == 200) {
JSONObject data = JSON.parseObject(jsonObject.getString("data"));
String white = data.getString("white");
if (white != null && !white.equals("")) {
boolean whiteList = Settings.System.putString(context.getContentResolver(), "DeselectBrowserArray", white);
Log.e("SystemSetting", "setBrowserList---------" + whiteList + ":" + white);
} else {
Settings.System.putString(context.getContentResolver(), "DeselectBrowserArray", " ");
}
String black = data.getString("black");
if (black != null && !black.equals("")) {
boolean blackList = Settings.System.putString(context.getContentResolver(), "qch_webblack_url", black);
Log.e("SystemSetting", "setBrowserList---------" + blackList + ":" + black);
} else {
Settings.System.putString(context.getContentResolver(), "qch_webblack_url", " ");
}
} else {
Log.e("fht", "setBrowserList" + msg);
}
} catch (JSONException e) {
Log.e("fht", "setBrowserList" + e.getMessage());
}
}
});
}
}

View File

@@ -176,7 +176,7 @@ public class MyDownloadService extends Service implements NetworkUtils.OnNetwork
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)
// AlertDialog.Builder builder = new AlertDialog.Builder(MyDownFile download FailureloadService.this)
// .setTitle("软件更新")
// .setIcon(R.mipmap.ic_launcher)
// .setCancelable(false)

View File

@@ -0,0 +1,119 @@
/**
*
*/
package com.info.sn.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import com.amap.api.location.AMapLocation;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* 辅助工具类
* @创建时间: 2015年11月24日 上午11:46:50
* @项目名称: AMapLocationDemo2.x
* @author hongming.wang
* @文件名称: amapUtils.java
* @类型名称: amapUtils
*/
public class amapUtils {
/**
* 开始定位
*/
public final static int MSG_LOCATION_START = 0;
/**
* 定位完成
*/
public final static int MSG_LOCATION_FINISH = 1;
/**
* 停止定位
*/
public final static int MSG_LOCATION_STOP= 2;
public final static String KEY_URL = "URL";
public final static String URL_H5LOCATION = "file:///android_asset/sdkLoc.html";
/**
* 根据定位结果返回定位信息的字符串
* @param location
* @return
*/
public synchronized static String getLocationStr(AMapLocation location){
if(null == location){
return null;
}
StringBuffer sb = new StringBuffer();
//errCode等于0代表定位成功其他的为定位失败具体的可以参照官网定位错误码说明
if(location.getErrorCode() == 0){
sb.append("定位成功" + "\n");
sb.append("定位类型: " + location.getLocationType() + "\n");
sb.append("经 度 : " + location.getLongitude() + "\n");
sb.append("纬 度 : " + location.getLatitude() + "\n");
sb.append("精 度 : " + location.getAccuracy() + "" + "\n");
sb.append("提供者 : " + location.getProvider() + "\n");
sb.append("速 度 : " + location.getSpeed() + "米/秒" + "\n");
sb.append("角 度 : " + location.getBearing() + "\n");
// 获取当前提供定位服务的卫星个数
sb.append("星 数 : " + location.getSatellites() + "\n");
sb.append("国 家 : " + location.getCountry() + "\n");
sb.append("省 : " + location.getProvince() + "\n");
sb.append("市 : " + location.getCity() + "\n");
sb.append("城市编码 : " + location.getCityCode() + "\n");
sb.append("区 : " + location.getDistrict() + "\n");
sb.append("区域 码 : " + location.getAdCode() + "\n");
sb.append("地 址 : " + location.getAddress() + "\n");
sb.append("兴趣点 : " + location.getPoiName() + "\n");
//定位完成的时间
sb.append("定位时间: " + formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
} else {
//定位失败
sb.append("定位失败" + "\n");
sb.append("错误码:" + location.getErrorCode() + "\n");
sb.append("错误信息:" + location.getErrorInfo() + "\n");
sb.append("错误描述:" + location.getLocationDetail() + "\n");
}
//定位之后的回调时间
sb.append("回调时间: " + formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
return sb.toString();
}
private static SimpleDateFormat sdf = null;
public static String formatUTC(long l, String strPattern) {
if (TextUtils.isEmpty(strPattern)) {
strPattern = "yyyy-MM-dd HH:mm:ss";
}
if (sdf == null) {
try {
sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
} catch (Throwable e) {
}
} else {
sdf.applyPattern(strPattern);
}
return sdf == null ? "NULL" : sdf.format(l);
}
/**
* 获取app的名称
* @param context
* @return
*/
public static String getAppName(Context context) {
String appName = "";
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
appName = context.getResources().getString(labelRes);
} catch (Throwable e) {
e.printStackTrace();
}
return appName;
}
}

View File

@@ -3,6 +3,8 @@ package com.info.sn.view;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
@@ -237,4 +239,5 @@ public class CustomDialog extends Dialog {
return this;
}
}

View File

@@ -3,4 +3,10 @@
<string name="download_btn_had">打开</string>
<string name="open_app_fail">打开失败!</string>
<string name="search_edit">请输入应用名称或关键字</string>
<string name="notifyTitle">提示</string>
<string name="notifyMsg">当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。</string>
<string name="setting">设置</string>
<string name="cancel">取消</string>
</resources>