update:2021.01.29
fix:增加锁屏管控,增加时间管控,
add:
This commit is contained in:
2021-01-29 16:35:57 +08:00
parent ea2c9676b4
commit c87b898829
17 changed files with 712 additions and 75 deletions

View File

@@ -182,15 +182,9 @@ public class MyApplication extends MultiDexApplication {
startService(new Intent(this, MyDownloadService.class));
}
registerTimeReceiver();
//忽略电池优化
// ignoreBatteryOptimization(this);
// try {
// Process exec = Runtime.getRuntime().exec(running);
// final InputStream is = exec.getInputStream();
// new LogThread(is).start();
// } catch (IOException e) {
//// e.printStackTrace();
// Log.e("第一个是Logcat", e.getMessage());
// }
initAmap();
}
@@ -242,54 +236,7 @@ public class MyApplication extends MultiDexApplication {
locationClient.startLocation();
}
//第一个是Logcat 也就是我们想要获取的log日志
//第二个是 -s 也就是表示过滤的意思
//第三个就是 我们要过滤的类型 W表示warm ,我们也可以换成 D debug IinfoEerror等等
// String[] running = new String[]{"logcat", "-s", "adb logcat *: W"};
String[] running = new String[]{"logcat"};
String filePath = "/sdcard/Log/Log.txt";
class LogThread extends Thread {
InputStream is;
LogThread(InputStream inputStream) {
super();
this.is = inputStream;
}
@Override
public void run() {
FileOutputStream os = null;
try {
//新建一个路径信息
File file = new File(filePath);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
os = new FileOutputStream(filePath);
int len = 0;
byte[] buf = new byte[1024];
while (-1 != (len = is.read(buf))) {
os.write(buf, 0, len);
os.flush();
}
} catch (Exception e) {
Log.e("writelog", "read logcat process failed. message: "
+ e.getMessage());
} finally {
if (null != os) {
try {
os.close();
os = null;
} catch (IOException e) {
// Do nothing
}
}
}
}
}
/**
* 忽略电池优化

View File

@@ -177,6 +177,7 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
// Utils.shotScreen(this);
HTTPInterface.updateDeviceInfo(this);
// testFilepath();
HTTPInterface.getSnTimeControl(MainActivity.this);
}
private void testFilepath() {

View File

@@ -0,0 +1,26 @@
package com.mjsheng.myappstore.bean;
import android.support.annotation.NonNull;
import java.io.Serializable;
public class BaseResponse<T> implements Serializable {
private static final long serialVersionUID = 5468533687801294972L;
public int code;
public String msg;
public T data;
@NonNull
@Override
public String toString() {
return "{\n" +//
"\tcode=" + code + "\n" +//
"\tmsg='" + msg + "\'\n" +//
"\tdata=" + data + "\n" +//
'}';
}
}

View File

@@ -0,0 +1,24 @@
package com.mjsheng.myappstore.bean;
import java.io.Serializable;
public class TimeControl implements Serializable {
String start_time;
String end_time;
public String getStart_time() {
return start_time;
}
public void setStart_time(String start_time) {
this.start_time = start_time;
}
public String getEnd_time() {
return end_time;
}
public void setEnd_time(String end_time) {
this.end_time = end_time;
}
}

View File

@@ -24,15 +24,22 @@ import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mjsheng.myappstore.MyApplication;
import com.mjsheng.myappstore.bean.Appground;
import com.mjsheng.myappstore.bean.BaseResponse;
import com.mjsheng.myappstore.bean.NetAndLaunchBean;
import com.mjsheng.myappstore.bean.NetAndLaunchData;
import com.mjsheng.myappstore.bean.TimeControl;
import com.mjsheng.myappstore.bean.UserInfo;
import com.mjsheng.myappstore.jpush.TagAliasOperatorHelper;
import com.mjsheng.myappstore.network.api.newapi.SnTimeControl;
import com.mjsheng.myappstore.network.api.newapi.TopAppControl;
import com.mjsheng.myappstore.network.api.newapi.UpdateDeviceInfo;
import com.mjsheng.myappstore.server.InitJpushServer;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.ForegroundAppUtil;
import com.mjsheng.myappstore.utils.Logger;
import com.mjsheng.myappstore.utils.SPUtils;
import com.mjsheng.myappstore.utils.TimeUtils;
import com.mjsheng.myappstore.utils.ToastUtil;
import com.mjsheng.myappstore.utils.Utils;
@@ -51,6 +58,7 @@ import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import static com.mjsheng.myappstore.jpush.TagAliasOperatorHelper.ACTION_SET;
import static com.mjsheng.myappstore.jpush.TagAliasOperatorHelper.sequence;
@@ -798,4 +806,85 @@ public class HTTPInterface {
});
ApkUtils.getAppInfo(context);
}
public static void getSnTimeControl(final Context context) {
SnTimeControl snTimeControl = Network.getSnTimeControlApi();
snTimeControl.getSnTimeControl(Utils.getSerial())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseResponse>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(BaseResponse response) {
int code = response.code;
if (code == 200) {
JSONObject jsonObject = (JSONObject) JSON.toJSON(response.data);
String start_time = jsonObject.getString("start_time");
String end_time = jsonObject.getString("end_time");
TimeUtils.ContralTime c = TimeUtils.String2ContralTime(context, start_time + "-" + end_time);
if (null != c) {
Log.e("getTimeControl", "200:" + c.toString());
}
} else {
TimeUtils.setEmpty(context);
TimeUtils.ContralTime c = TimeUtils.getDefaltContralTime(context);
if (null != c) {
Log.e("getTimeControl", c.toString());
}
}
}
@Override
public void onError(Throwable e) {
Log.e("getSnTimeControl", "onError: " + e.getMessage());
}
@Override
public void onComplete() {
Intent intent = new Intent();
intent.setAction(InitJpushServer.TimeChangedReceiver.ACTION_UPDATE);
context.sendBroadcast(intent);
}
});
}
public static void getTopAppControl(final Context context) {
TopAppControl topAppControl = Network.getTopAppControlApi();
topAppControl.getSnAppControl(Utils.getSerial())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseResponse>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(BaseResponse response) {
if (response.code == 200) {
JSONObject jsonObject = (JSONObject) JSON.toJSON(response.data);
String app_package = jsonObject.getString("app_package");
SPUtils.put(context, ForegroundAppUtil.TOPAPP_KEY, app_package);
ForegroundAppUtil.openTopApp(context);
} else {
SPUtils.put(context, ForegroundAppUtil.TOPAPP_KEY, "");
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}

View File

@@ -20,6 +20,8 @@ import com.mjsheng.myappstore.network.api.UpdateApi;
import com.mjsheng.myappstore.network.api.UploadAppInfoApi;
import com.mjsheng.myappstore.network.api.newapi.GetBatchApi;
import com.mjsheng.myappstore.network.api.newapi.GetLockState;
import com.mjsheng.myappstore.network.api.newapi.SnTimeControl;
import com.mjsheng.myappstore.network.api.newapi.TopAppControl;
import com.mjsheng.myappstore.network.api.newapi.UpdateDeviceInfo;
import java.io.File;
@@ -68,6 +70,8 @@ public class Network {
private static GetLockState getLockState;
private static UpdateDeviceInfo updateDeviceInfo;
private static GetBatchApi getBatchApi;
private static SnTimeControl SnTimeControlApi;
private static TopAppControl TopAppControlApi;
private static final long cacheSize = 1024 * 1024 * 20;// 缓存文件最大限制大小20M
private static String cacheDirectory = Environment.getExternalStorageDirectory() + "/okttpcaches"; // 设置缓存文件路径
@@ -298,5 +302,29 @@ public class Network {
return getBatchApi;
}
public static SnTimeControl getSnTimeControlApi() {
if (SnTimeControlApi == null) {
Retrofit retrofit = new Retrofit.Builder()
.client(cacheClient)
.baseUrl(ROOT_URL)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
SnTimeControlApi = retrofit.create(SnTimeControl.class);
}
return SnTimeControlApi;
}
public static TopAppControl getTopAppControlApi() {
if (TopAppControlApi == null) {
Retrofit retrofit = new Retrofit.Builder()
.client(cacheClient)
.baseUrl(ROOT_URL)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
TopAppControlApi = retrofit.create(TopAppControl.class);
}
return TopAppControlApi;
}
}

View File

@@ -19,5 +19,4 @@ public class UrlPath {
//获取当前最顶层应用和电量
public final static String SEND_DRIVE_STATE = HOMEPATHRUL + "Online/online";
}

View File

@@ -0,0 +1,16 @@
package com.mjsheng.myappstore.network.api.newapi;
import com.mjsheng.myappstore.bean.BaseResponse;
import com.mjsheng.myappstore.bean.TimeControl;
import com.mjsheng.myappstore.utils.Configure;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface SnTimeControl {
@GET(Configure.GET_SN_TIME_CONTROL)
Observable<BaseResponse> getSnTimeControl(
@Query("sn") String sn
);
}

View File

@@ -0,0 +1,15 @@
package com.mjsheng.myappstore.network.api.newapi;
import com.mjsheng.myappstore.bean.BaseResponse;
import com.mjsheng.myappstore.utils.Configure;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface TopAppControl {
@GET(Configure.GET_TOP_APP_CONTROL)
Observable<BaseResponse> getSnAppControl(
@Query("sn") String sn
);
}

View File

@@ -43,6 +43,7 @@ import com.mjsheng.myappstore.server.InitJpushServer;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.CmdUtil;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.ForegroundAppUtil;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SPUtils;
import com.mjsheng.myappstore.utils.SaveListUtils;
@@ -129,6 +130,11 @@ public class MyJPushReceiver extends BroadcastReceiver {
private final String KILL_SERVER = "26";//结束进程
private final String TIME_CONTROL = "27";//结束进程
private final String TOP_APP = "28";//结束进程
private Context mContext;
private int changeNum(int paramInt) {
@@ -346,6 +352,12 @@ public class MyJPushReceiver extends BroadcastReceiver {
e.printStackTrace();
}
break;
case TIME_CONTROL:
getTimeControl(context, extras);
break;
case TOP_APP:
getTopApp(context,extras);
break;
}
}
@@ -1316,4 +1328,15 @@ public class MyJPushReceiver extends BroadcastReceiver {
}
});
}
private void getTimeControl(Context context, String extras) {
HTTPInterface.getSnTimeControl(context);
}
private void getTopApp(Context context,String extras) {
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(extras);
String packageName = jsonObject.getString("app_package");
SPUtils.put(context, ForegroundAppUtil.TOPAPP_KEY, packageName);
ForegroundAppUtil.openTopApp(context);
}
}

View File

@@ -45,6 +45,10 @@ import com.mjsheng.myappstore.utils.ServiceAliveUtils;
import com.mjsheng.myappstore.utils.ToastUtil;
import com.mjsheng.myappstore.utils.Utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import okhttp3.Call;
@@ -88,6 +92,73 @@ public class GuardService extends Service {
}
private Process exec;
private LogThread logThread;
@Override
public void onCreate() {
// try {
// exec = Runtime.getRuntime().exec(running);
// final InputStream is = exec.getInputStream();
// logThread = new LogThread(is);
// is.close();
// exec.destroy();
// } catch (IOException e) {
//// e.printStackTrace();
// Log.e("第一个是Logcat", e.getMessage());
// }
super.onCreate();
}
//第一个是Logcat 也就是我们想要获取的log日志
//第二个是 -s 也就是表示过滤的意思
//第三个就是 我们要过滤的类型 W表示warm ,我们也可以换成 D debug IinfoEerror等等
// String[] running = new String[]{"logcat", "-s", "adb logcat *: W"};
String[] running = new String[]{"logcat"};
String filePath = "/sdcard/Log/Log.txt";
class LogThread extends Thread {
InputStream is;
LogThread(InputStream inputStream) {
super();
this.is = inputStream;
}
@Override
public void run() {
FileOutputStream os = null;
try {
//新建一个路径信息
File file = new File(filePath);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
os = new FileOutputStream(filePath);
int len = 0;
byte[] buf = new byte[1024];
while (-1 != (len = is.read(buf))) {
os.write(buf, 0, len);
os.flush();
}
} catch (Exception e) {
Log.e("writelog", "read logcat process failed. message: "
+ e.getMessage());
} finally {
if (null != os) {
try {
os.close();
os = null;
} catch (IOException e) {
// Do nothing
}
}
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
@@ -111,6 +182,8 @@ public class GuardService extends Service {
}
}
private NetworkChangedRecceiver mNetworkChangedRecceiver;
public void registerNetworkReceiver() {
@@ -234,16 +307,16 @@ public class GuardService extends Service {
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, okhttp3.Response response) {
Log.e("taskComplete",s);
Log.e("taskComplete", s);
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
Log.e("taskComplete",":"+e.getMessage());
Log.e("taskComplete", ":" + e.getMessage());
}
});
int userId= (int) SPUtils.get(GuardService.this,"admin_id",0);
int userId = (int) SPUtils.get(GuardService.this, "admin_id", 0);
long app_size = task.getFileSize();
OkGo.post(Configure.SEND_DOWNLOAD_FILE_INFO)
.params("key", Configure.HTTP_KEY)

View File

@@ -58,10 +58,12 @@ import com.mjsheng.myappstore.network.api.SystemSettingApi;
import com.mjsheng.myappstore.network.api.newapi.GetBatchApi;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.ForegroundAppUtil;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SPUtils;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.SysSettingUtils;
import com.mjsheng.myappstore.utils.TimeUtils;
import com.mjsheng.myappstore.utils.Utils;
import org.json.JSONArray;
@@ -111,6 +113,7 @@ public class InitJpushServer extends Service {
Log.e("InitJpushServer", "onCreate");
super.onCreate();
registReceiver();
registerTimeReceiver();
// android.os.Debug.waitForDebugger();
}
@@ -167,7 +170,6 @@ public class InitJpushServer extends Service {
});// 请求方式和请求url
}
private void getScreenLockState() {
OkGo.get(Configure.GET_LOCK_SCREEN_STATE)
.params("sn", Utils.getSerial())
@@ -181,10 +183,21 @@ public class InitJpushServer extends Service {
int lockScreen = data.getInteger("is_screen_lock");
String name = data.getString("name");
if (lockScreen == 1) {
showFloatingWindow(name);
if (!timelocked) {
showFloatingWindow(name);
}
screenlocked = true;
} else {
if (!timelocked) {
hideFloatingWindow();
}
screenlocked = false;
}
} else {
if (!timelocked) {
hideFloatingWindow();
}
screenlocked = false;
}
}
@@ -205,8 +218,9 @@ public class InitJpushServer extends Service {
};
private static WindowManager windowManager;
private static View topView;
private View topView;
boolean screenlocked = false;
boolean timelocked = false;
private void showFloatingWindow(String name) {
if (Settings.canDrawOverlays(this)) {
@@ -231,8 +245,12 @@ public class InitJpushServer extends Service {
});
if (null == topView) {
topView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_top, null);
TextView textView = topView.findViewById(R.id.textView);
textView.setText(name);
} else {
if (topView.getTag().equals("added")) {
TextView textView = topView.findViewById(R.id.textView);
textView.setText(name);
return;
}
}
@@ -297,13 +315,82 @@ public class InitJpushServer extends Service {
}
if (action.equals(action_lock)) {
String name = intent.getStringExtra("name");
showFloatingWindow(name);
if (!timelocked) {
showFloatingWindow(name);
}
screenlocked = true;
} else if (action.equals(action_unlock)) {
hideFloatingWindow();
if (!timelocked) {
hideFloatingWindow();
}
screenlocked = false;
}
}
}
private TimeChangedReceiver mTimeChangedReceiver;
//监听时间和日期变化
public void registerTimeReceiver() {
mTimeChangedReceiver = new TimeChangedReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(TimeChangedReceiver.ACTION_UPDATE);
registerReceiver(mTimeChangedReceiver, filter);
}
public class TimeChangedReceiver extends BroadcastReceiver {
public static final String ACTION_UPDATE = "TimeChangedReceiver_update";
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_DATE_CHANGED.equals(intent.getAction())) {
Log.e("fht", "TimeChangedReceiver:" + "data changed");
} else if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
Log.e("fht", "TimeChangedReceiver:" + "time changed");
} else if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
Log.e("fht", "TimeChangedReceiver:" + "timezone changed");
} else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
Log.e("fht", "TimeChangedReceiver:" + "time tick");
} else if (ACTION_UPDATE.equals(intent.getAction())) {
Log.e("fht", "TimeChangedReceiver:" + "date update");
}
ForegroundAppUtil.openTopApp(context);
long nowTime = System.currentTimeMillis();
TimeUtils.ContralTime contralTime = TimeUtils.getDefaltContralTime(InitJpushServer.this);
if (null != contralTime) {
if (contralTime.inControlTime(nowTime)) {
if (!screenlocked) {
showFloatingWindow("管控时间:" + contralTime.toString());
} else {
TextView textView = topView.findViewById(R.id.textView);
textView.setText("管控时间:" + contralTime.toString());
}
timelocked = true;
} else {
getScreenLockState();
if (!screenlocked) {
hideFloatingWindow();
}
timelocked = false;
}
} else {
if (!screenlocked) {
hideFloatingWindow();
}
getScreenLockState();
timelocked = false;
}
}
}
private void initJpush() {
TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
tagAliasBean.action = ACTION_SET;
@@ -339,7 +426,6 @@ public class InitJpushServer extends Service {
}
//重新设置jpush
synchronized private void timerImitate() {
Observable.timer(15000, TimeUnit.MILLISECONDS)
@@ -419,7 +505,6 @@ public class InitJpushServer extends Service {
}
private void getDeselectID() {
DeselectIDApi deselectIDApi = Network.getDeselectIDApi();
deselectIDApi.getDeselectIDApi(Configure.HTTP_KEY, Utils.getSerial())
@@ -592,7 +677,6 @@ public class InitJpushServer extends Service {
}
}
private void getDeviceBatch(final String result) {
GetBatchApi getBatchApi = Network.getBatchApi();
getBatchApi.getBatch(Utils.getSerial())
@@ -643,7 +727,6 @@ public class InitJpushServer extends Service {
}
//删除用户除了在应用市场的其他应用
private void deleteOtherApp(String packageList) {
Log.e("deleteOtherApp", "packageList:" + packageList);
@@ -962,7 +1045,6 @@ public class InitJpushServer extends Service {
// sendBroadcast(intent1);
}
private void writeDeselectBrowserIDtoSystem(String ids) {
// if (!TextUtils.isEmpty(ids)) {
boolean deselectBrowserArray = Settings.System.putString(InitJpushServer.this.getContentResolver(), "DeselectBrowserArray", ids);
@@ -1086,7 +1168,6 @@ public class InitJpushServer extends Service {
}
}
boolean locked = false;
synchronized public void getLockedState() {
@@ -1137,6 +1218,9 @@ public class InitJpushServer extends Service {
resetDevice();
// MyApplication.getInstance().getWhitePackageList();
getDefaultDesktop();
HTTPInterface.getSnTimeControl(InitJpushServer.this);
HTTPInterface.getTopAppControl(InitJpushServer.this);
}
} else if (code == -300) {
// ApkUtils.uninstallAllApp(InitJpushServer.this);
@@ -1152,7 +1236,6 @@ public class InitJpushServer extends Service {
});// 请求方式和请求url
}
private void resetDevice() {
boolean isReset = MySQLData.GetBooleanData(this, CommonDatas.IS_RESET);
int batteryLevel = getBatteryLevel();

View File

@@ -107,6 +107,14 @@ public class ApkUtils {
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文件
*/

View File

@@ -215,5 +215,8 @@ public class Configure {
//获取霸屏状态
public final static String GET_DESKTOP = HTTP_TAG_HEAD_NEW + "Sn/getSnDesktop";
//获取默认桌面升级
public final static String GET_SN_TIME_CONTROL = HTTP_TAG_HEAD_NEW + "Sn/getSnTimeControl";
//获取时间管控
public final static String GET_TOP_APP_CONTROL = HTTP_TAG_HEAD_NEW + "Sn/getSnAppControl";
//获取时间管控
}

View File

@@ -0,0 +1,131 @@
package com.mjsheng.myappstore.utils;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import java.util.List;
public class ForegroundAppUtil {
private static final long END_TIME = System.currentTimeMillis();
private static final long TIME_INTERVAL = 7 * 24 * 60 * 60 * 1000L;
private static final long START_TIME = END_TIME - TIME_INTERVAL;
public static final String TOPAPP_KEY = "TOP_ALWAYS_SHOW_APP_NAME";
public static String getForegroundPackageName(Context context) {
//系统应用可以直接获取
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfos = mActivityManager.getRunningTasks(1);
return runningTaskInfos.get(0).topActivity.getPackageName();
}
public static void openTopApp(Context context) {
String packages = ForegroundAppUtil.getForegroundPackageName(context);
String topAppName = (String) SPUtils.get(context, ForegroundAppUtil.TOPAPP_KEY, "");
Log.e("openTopApp", "old:" + topAppName);
if (!TextUtils.isEmpty(topAppName)) {
if (!packages.equals(topAppName)) {
ApkUtils.openApp(context, topAppName);
}
} else {
Log.e("openTopApp", ":" + packages);
}
}
/**
* 获取栈顶的应用包名
*/
public static String getForegroundActivityName(Context context) {
String currentClassName = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
ActivityManager manager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
currentClassName = manager.getRunningTasks(1).get(0).topActivity.getPackageName();
} else {
UsageStats initStat = getForegroundUsageStats(context, START_TIME, END_TIME);
if (initStat != null) {
currentClassName = initStat.getPackageName();
}
}
return currentClassName;
}
/**
* 判断当前应用是否在前台
*/
public static boolean isForegroundApp(Context context) {
return TextUtils.equals(getForegroundActivityName(context), context.getPackageName());
}
/**
* 获取时间段内,
*/
public static long getTotleForegroundTime(Context context) {
UsageStats usageStats = getCurrentUsageStats(context, START_TIME, END_TIME);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return usageStats != null ? usageStats.getTotalTimeInForeground() : 0;
}
return 0;
}
/**
* 获取记录前台应用的UsageStats对象
*/
private static UsageStats getForegroundUsageStats(Context context, long startTime, long endTime) {
UsageStats usageStatsResult = null;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
List<UsageStats> usageStatses = getUsageStatsList(context, startTime, endTime);
if (usageStatses == null || usageStatses.isEmpty()) return null;
for (UsageStats usageStats : usageStatses) {
if (usageStatsResult == null || usageStatsResult.getLastTimeUsed() < usageStats.getLastTimeUsed()) {
usageStatsResult = usageStats;
}
}
}
return usageStatsResult;
}
/**
* 获取记录当前应用的UsageStats对象
*/
public static UsageStats getCurrentUsageStats(Context context, long startTime, long endTime) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
List<UsageStats> usageStatses = getUsageStatsList(context, startTime, endTime);
if (usageStatses == null || usageStatses.isEmpty()) return null;
for (UsageStats usageStats : usageStatses) {
if (TextUtils.equals(usageStats.getPackageName(), context.getPackageName())) {
return usageStats;
}
}
}
return null;
}
/**
* 通过UsageStatsManager获取List<UsageStats>集合
*/
public static List<UsageStats> getUsageStatsList(Context context, long startTime, long endTime) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager manager = (UsageStatsManager) context.getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
//UsageStatsManager.INTERVAL_WEEKLYUsageStatsManager的参数定义了5个具体查阅源码
List<UsageStats> usageStatses = manager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, startTime, endTime);
if (usageStatses == null || usageStatses.size() == 0) {// 没有权限,获取不到数据
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intent);
return null;
}
return usageStatses;
}
return null;
}
}

View File

@@ -0,0 +1,171 @@
package com.mjsheng.myappstore.utils;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.mjsheng.myappstore.server.InitJpushServer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeUtils {
private static DateFormat df = new SimpleDateFormat("HH:mm");
public static final String START_TIME_KEY = "START_TIME";
public static final String END_TIME_KEY = "END_TIME";
public static long dayTime = 60 * 60 * 24 * 1000;
public static String getNowTime() {
long nowTime = System.currentTimeMillis();
DateFormat df = ContralTime.getDf();
return df.format(nowTime);
}
// public static boolean CurrentInTimeScope(ContralTime contralTime) {
// boolean result = true;
// final long aDayInMillis = 1000 * 60 * 60 * 24;
// long currentTimeMillis = System.currentTimeMillis();
//
// }
public static ContralTime String2ContralTime(Context context, @NonNull String timeText) {
DateFormat df = ContralTime.getDf();
String[] time = timeText.trim().split("-");
if (time.length != 2) {
throw new RuntimeException("Time format error!");
}
try {
SPUtils.put(context, START_TIME_KEY, time[0].trim());
SPUtils.put(context, END_TIME_KEY, time[1].trim());
Date startDate = df.parse(time[0].trim());
Date endDate = df.parse(time[1].trim());
ContralTime contralTime = new ContralTime();
// if (date1.getTime() < date2.getTime()) {
contralTime.setStartTime(df.format(startDate));
contralTime.setEndTime(df.format(endDate));
// } else {
// contralTime.setStartTime(df.format(date2));
// contralTime.setEndTime(df.format(date1));
// }
return contralTime;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static ContralTime getDefaltContralTime(Context context) {
String startTime = (String) SPUtils.get(context, START_TIME_KEY, "00:00");
String endTime = (String) SPUtils.get(context, END_TIME_KEY, "00:00");
if (null == startTime || null == endTime || (startTime.equals("00:00") && endTime.equals("00:00"))) {
return null;
} else {
try {
Date startDate = df.parse(startTime.trim());
Date endDate = df.parse(endTime.trim());
ContralTime contralTime = new ContralTime();
contralTime.setStartTime(df.format(startDate));
contralTime.setEndTime(df.format(endDate));
return contralTime;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
public static void setEmpty(Context context) {
SPUtils.put(context, START_TIME_KEY, "00:00");
SPUtils.put(context, END_TIME_KEY, "00:00");
Intent intent = new Intent();
intent.setAction(InitJpushServer.TimeChangedReceiver.ACTION_UPDATE);
context.sendBroadcast(intent);
}
public static class ContralTime {
//format HH:mm
static String startTime;
static String endTime;
public ContralTime() {
}
public ContralTime(String startT, String endT) {
startTime = startT;
endTime = endT;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startT) {
startTime = startT;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endT) {
endTime = endT;
}
public static DateFormat getDf() {
return df;
}
public static void setDf(DateFormat d) {
df = d;
}
public String getNowTimeString(long time) {
return df.format(new Date(time));
}
public boolean inControlTime(long time) {
return inControlTime(df.format(new Date(time)));
}
public boolean inControlTime(String time) {
if (TextUtils.isEmpty(time)) {
throw new RuntimeException("Time is empty");
} else {
if (!time.contains(":")) {
throw new RuntimeException("Time format error");
}
}
try {
Date startDate = df.parse(startTime);
Date endDate = df.parse(endTime);
Date nowDate = df.parse(time);
if (startDate.getTime() > endDate.getTime()) {
//开始时间大于结束时间 列 1600-0100
endDate.setTime(endDate.getTime() + dayTime);
}
if (nowDate.getTime() >= startDate.getTime() && nowDate.getTime() <= endDate.getTime()) {
return true;
} else {
return false;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
@NonNull
@Override
public String toString() {
return startTime + "\t-\t" + endTime;
}
}
}