全志代码首次提交

This commit is contained in:
2025-11-06 10:55:48 +08:00
commit fc767791f3
299 changed files with 26337 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
package com.android;
import java.lang.reflect.Field;
public class MXQConfig {
public static final int ALLWINNER_PLM=0;
public static final int RK_PLM=1;
public static final int ARMLOGIC_PLM=2;
public static int PLATFORM_TAG=ALLWINNER_PLM;
public static String RK_PLATFORM="rockchip";
public static String ALLWINNER_PLATFORM="allwinner";
public static String getManufacturer() {
try {
Class<?> buildConfigClass = Class.forName("com.ik.mboxlauncher.BuildConfig");
Field debugField = buildConfigClass.getField("MANUFACTURER");
return (String)debugField.get(null);
} catch (Exception e) {
return ALLWINNER_PLATFORM; // 默认值
}
}
}

View File

@@ -0,0 +1,30 @@
package com.android.api;
import java.util.Map;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.HeaderMap;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
/**
* Created by Administrator on 2018/6/9 0009.
*/
public interface ServerApi {
@Headers({"Content-type:application/json;charset=UTF-8"})
@POST(ServerInterface.POST_EVENTINFO_DEVICE)
Call<String> recoedDeviceEvent(@HeaderMap Map<String,String> headeMap, @Body RequestBody requestBody);
//获取广告接口
@Headers({"Content-type:application/json;charset=UTF-8"})
@POST(ServerInterface.POST_LAUNCHER_ADS)
Call<String> postLauncherAds(@Body RequestBody requestBody);
}

View File

@@ -0,0 +1,39 @@
package com.android.api;
import com.android.api.encrytion.UtilEncrypt;
import com.android.util.DeviceUtil;
import com.android.util.LogUtils;
public class ServerInterface {
public static final int SUCCESS = 200;
public static final String IP_ADDRESS="192.168.1.87";
/**心跳业务IP*/
public static final String SERVER_IP_ADDRESS="181b9296940b2b9787a4b781ce52c18f65cb2ae18cfbeb7fa4b6e99dded7f945";
/**其他业务IP*/
public static final String BUSINESS_IP_ADDRESS="e50cce9d2db6d36b3d13f60ef00e9c1a609e3f82a2fa708bb93b459b2939713c";
//获取launcher广告资源信息
public static final String POST_LAUNCHER_ADS="/app-api/launcher/getLauncher/ads";
/**上传事件信息*/
public static final String POST_EVENTINFO_DEVICE="/app-api/third/launcher/ad/play/callback";
private static final boolean USER_DEBUG=false;
public static String createHttpUrl(){
if(USER_DEBUG) {
LogUtils.loge("TEST MODEL");
return "http://" + IP_ADDRESS + ":8748";
}else {
LogUtils.loge("RUNING MODEL");
return "http://"+UtilEncrypt.decrypt(BUSINESS_IP_ADDRESS)+":8748";
}
}
}

View File

@@ -0,0 +1,87 @@
package com.android.api.biz;
import androidx.annotation.NonNull;
import com.android.api.ServerInterface;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* Created by Administrator on 2017/11/11 0011.
* 网络请求基类
*/
public class BaseBiz {
private Retrofit stringRetrofit;//返回字符串
private static final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
public BaseBiz() {
// stringRetrofit = new Retrofit.Builder().baseUrl(ServerInterface.BASE_URL)
// .addConverterFactory(ScalarsConverterFactory.create())
// .client(getClient())
// .build();
}
public BaseBiz(String baseUrl) {
stringRetrofit = new Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
.client(getClient())
.build();
}
protected Retrofit getStringRetrofit() {
return stringRetrofit;
}
public static OkHttpClient getClient() {
return new OkHttpClient.Builder()
.connectTimeout(30000, TimeUnit.MILLISECONDS)
.addInterceptor(new Interceptor() {
Request request;
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
// if (MyApplication.getUserBean() != null) {
// request = chain.request().newBuilder()
//// .addHeader("token", MyApplication.getUserBean().getToken())
// .build();
// } else {
request = chain.request().newBuilder().addHeader("d-time", String.valueOf(System.currentTimeMillis())).build();
// }
if (request.body() == null) {
} else {
}
return chain.proceed(request);
}
}).cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(CoreKeys.SESSIONID, cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(CoreKeys.SESSIONID);
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
}
}

View File

@@ -0,0 +1,27 @@
package com.android.api.biz;
import com.android.api.biz.OnBaseListener;
import com.android.database.lib.RecordEventBean;
import com.android.nebulasdk.bean.EventDataInfo;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2018/6/9 0009.
*/
@SuppressWarnings("all")
public interface Biz {
//获取广告接口
void postLauncherAds(Map<String ,String > map, OnBaseListener listener);
//记录设备事件的接口
void postEventData(List<EventDataInfo> recordEventBeans, OnBaseListener listener);
}

View File

@@ -0,0 +1,17 @@
package com.android.api.biz;
import android.os.Environment;
import java.io.File;
public class CoreKeys {
public static final String SESSIONID = "sessionid";
public static final String CONFIGDATABEAN="ConfigDataBean";
public static String local_file = Environment.getExternalStorageDirectory()
+ File.separator + Environment.DIRECTORY_DCIM
+ File.separator + "Camera" + File.separator;
public static String down_file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/atv-ota/";
}

View File

@@ -0,0 +1,15 @@
package com.android.api.biz;
public interface OnBaseListener {
/**
* 服务器响应
*/
void onResponse(String result);
/**
* 服务器未响应
*/
void onFailure(String e, int code);
}

View File

@@ -0,0 +1,114 @@
package com.android.api.biz.bizimpl;
import com.android.api.biz.Biz;
import com.android.nebulasdk.bean.EventDataInfo;
import com.google.gson.JsonObject;
import com.android.api.ServerApi;
import com.android.api.biz.BaseBiz;
import com.android.api.biz.OnBaseListener;
import com.android.database.lib.RecordEventBean;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Administrator on 2018/6/9 0009.
*/
public class BizImpl extends BaseBiz implements Biz {
public BizImpl(String httpUrl) {
super(httpUrl);
}
@Override
public void postLauncherAds(Map<String, String> map, OnBaseListener listener) {
{
JsonObject jsonObject =new JsonObject();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()){
String keyStr= it.next();
String valueStr= (String)map.get(keyStr);
jsonObject.addProperty(keyStr,valueStr);
}
RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),GsonUtil.GsonString(jsonObject));
getStringRetrofit().create(ServerApi.class).postLauncherAds(requestBody).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (call != null) {
if (response.body() != null) {
LogUtils.loge("postLauncherAds response==>" + GsonUtil.GsonString(response.body()));
if (response.isSuccessful()) {
listener.onResponse(response.body());
} else {
listener.onFailure(response.message(), response.raw().code());
}
} else {
listener.onFailure("The server is busy, please try again later", response.raw().code());
}
} else {
LogUtils.loge(">>>>>>>>>>>>>>>>>>call == null<<<<<<<<<<<<<<<<<<");
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
if (call.isExecuted()) {
call.cancel();
}
LogUtils.loge("postLauncherAds request fail==>" + GsonUtil.GsonString(t.getMessage()));
listener.onFailure("The server is busy, please try again later", 0);
}
});
}
}
@Override
public void postEventData(List<EventDataInfo> recordEventBeans, OnBaseListener listener) {
Map<String,String> heardMap = new HashMap<>();
RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), GsonUtil.GsonString(recordEventBeans));
getStringRetrofit().create(ServerApi.class).recoedDeviceEvent(heardMap,requestBody).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (call != null) {
if (response.body() != null) {
// LogUtils.loge("submit record events" + GsonUtil.GsonString(response.body()));
// String test="{\\\"code\\\": \\\"1000\\\",\\\"msg\\\": \\\"获取成功\\\",\\\"data\\\": [\\\"{\\\"picUrl\\\": \\\"www.baidu.com\\\",\\\"peopleName\\\": \\\"胡治银\\\",\\\"punchTime\\\": \\\"2018-12-12 8:30:00\\\",\\\"punchResult\\\": 迟到}\\\", \\\"{\\\"picUrl\\\": \\\"www.baidu.com\\\",\\\"peopleName\\\": \\\"杨荣香\\\",\\\"punchTime\\\": \\\"2018-12-12 7:30:00\\\",\\\"punchResult\\\": 正常}\\\", \\\"{\\\"picUrl\\\": \\\"www.baidu.com\\\",\\\"peopleName\\\": \\\"张三\\\",\\\"punchTime\\\": \\\"2018-12-12 15:03:01\\\",\\\"punchResult\\\": 迟到}\\\"]\n" +
// "}";
if (response.isSuccessful()) {
listener.onResponse(response.body());
} else {
listener.onFailure(response.message(), response.raw().code());
}
} else {
listener.onFailure("The server is busy, please try again later", response.raw().code());
}
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
if (call.isExecuted()) {
call.cancel();
}
LogUtils.loge("recoedDeviceEvent Biz服务器未响应请求失败==>" + GsonUtil.GsonString(t.getMessage()));
listener.onFailure("The server is busy, please try again later", 0);
}
});
}
}

View File

@@ -0,0 +1,59 @@
package com.android.api.encrytion;
public class AESUtil {
private static final String password="wwwwaaabbb";
/**
*
* @param dataStr
* @param key
* @return
*/
public static String encryptVerification(String dataStr){
if(dataStr==null||"".equals(dataStr)){
return "";
}
String headMsg="";
String endMag="";
String addendMag="";
if(dataStr.length()>3) {
headMsg = dataStr.substring(0,3);
}
if(dataStr.length()>4){
endMag=dataStr.substring(dataStr.length()-4,dataStr.length());
}
if(dataStr.length()>7){
addendMag=dataStr.substring(0,7);
}
String time=TimeUtil.getDateEND(System.currentTimeMillis());
String tmp=headMsg+time+addendMag+endMag;
String verification = MD5Utils.md5(tmp).substring(0,15);
return UtilEncrypt.encrypt(password,verification);
}
// /**
// * 测试
// *
// * @param args
// * @throws Exception
// */
// public static void main(String[] args) throws Exception {
//// String test= encryptVerification("8618665362153","123456");
//
// String test=UtilEncrypt.encrypt("test","123456");
// System.out.print(test);
// }
}

View File

@@ -0,0 +1,31 @@
package com.android.api.encrytion;
import java.security.MessageDigest;
/**
* Created by jzm on 2016/7/18.
*/
public class MD5Utils {
/**
* 使用md5的算法进行加密
*/
public static String md5(String encryptStr) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md5.digest(encryptStr.getBytes());
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
encryptStr = hexValue.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
return encryptStr.toLowerCase();
}
}

View File

@@ -0,0 +1,527 @@
package com.android.api.encrytion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 时间转换工具
*/
public class TimeUtil {
public static final long DAY_MILLSECONDS = 24 * 3600 * 1000;
private TimeUtil() {
}
public static String showMessageTime(long MessageTime) {
SimpleDateFormat format;
String showtimeString;
long startTime = MessageTime * 1000;
//获取当前年份
int current_year = Integer.parseInt(getYear(System.currentTimeMillis()));
//获取发消息的年份
int year = Integer.parseInt(getYear(startTime));
if (current_year > year) {
//不在同一年 显示完整的年月日
showtimeString = getDateEN(startTime);
} else {
if (newchajitian(startTime) == 0) {
//同一天 显示时分
format = new SimpleDateFormat("HH:mm");
showtimeString = format.format(new Date(startTime));
} else if (newchajitian(startTime) == 1) {
//相差一天 显示昨天
showtimeString = "昨天";
} else if (newchajitian(startTime) > 1 && newchajitian(startTime) < 7) {
//相差一天以上 七天之内 显示星期几
showtimeString = getWeek(startTime);
} else {
format = new SimpleDateFormat("MM-dd");
showtimeString = format.format(new Date(startTime));
}
}
return showtimeString;
}
public static String getLastM(int total, int value) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 设置为当前时间
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - (total - value));
date = calendar.getTime();
return dateFormat.format(date);
}
/**
* 根据用户生日计算年龄
*/
public static String getAgeByBirthday(Date birthday) {
Calendar cal = Calendar.getInstance();
if (cal.before(birthday)) {
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthday);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH) + 1;
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
// monthNow==monthBirth
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
// monthNow>monthBirth
age--;
}
}
return age + "";
}
//获取当前年月日生成的唯一标识码
public static String getTimeNumber(long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
return format.format(new Date(time));// 2012-10-03-23-41-31
}
//显示完整的年月日 时分秒
public static String getTime(long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(new Date(time));// 2012-10-03 23:41:31
}
//显示完整的年月日 时分秒
public static String getMinute(long time) {
SimpleDateFormat format = new SimpleDateFormat("mm:ss");
return format.format(new Date(time));// 2012-10-03 23:41:31
}
//显示完整的月日 时分
public static String getComTime(long time) {
SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
return format.format(new Date(time));// 2012-10-03 23:41:31
}
//显示完整的年月日
public static String getDateEN(long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(new Date(time));// 2012-10-03 23:41:31
}
//显示完整的年月日
public static String getDateEND(long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return format.format(new Date(time));// 2012-10-03 23:41:31
}
//显示完整的年月日
public static String getDateMon(long time) {
SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
return format.format(new Date(time));// 2012-10-03 23:41:31
}
// 获取当前年份
public static String getYear(Long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy");
return format.format(new Date(time));
}
public static long getDate(String timeStr) {
long time = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(timeStr);
time = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return time / 1000;
}
public static long getDateByString(String timeStr) {
long time = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = format.parse(timeStr);
time = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
public static String getTimeByString(String timeStr) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = null;
try {
date = sdf1.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return sdf2.format(date);
}
public static String getTimeByStr(String timeStr) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = null;
try {
date = sdf1.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
return sdf2.format(date);
}
public static String setTimeByString(String timeStr) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = null;
try {
date = sdf1.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddhhmmss");
return sdf2.format(date);
}
// 获取上午、下午时间
public static String getHour(Long time) {
String str;
final Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(time);
int apm = mCalendar.get(Calendar.AM_PM);
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
String hour = format.format(time);
if (apm == 0) {
str = "上午 " + hour;
} else {
str = "下午 " + hour;
}
return str;
}
public static long newchajitian(Long lstartTime) {
Calendar c1 = Calendar.getInstance();
int year = c1.get(Calendar.YEAR);
int yue = c1.get(Calendar.MONTH);
int ri = c1.get(Calendar.DATE);
c1.set(year, yue + 1, ri, 0, 0);
Calendar c2 = Calendar.getInstance();
int year_ = Integer.parseInt((getYear(lstartTime)));
int yue_ = getYue(lstartTime);
int ri_ = getDay(lstartTime);
c2.set(year_, yue_, ri_, 0, 0);
return getAbsDayDiff(c2, c1);
}
public static int getDay(long time) {
SimpleDateFormat format1 = new SimpleDateFormat("dd");
String date1 = format1.format(new Date(time));
return Integer.parseInt(date1);// 2012-10-03 23:41:31
}
public static int getYue(long time) {
SimpleDateFormat format1 = new SimpleDateFormat("MM");
String date1 = format1.format(new Date(time));
return Integer.parseInt(date1);// 2012-10-03 23:41:31
}
public static int getAbsDayDiff(Calendar calStart, Calendar calEnd) {
Calendar start = (Calendar) calStart.clone();
Calendar end = (Calendar) calEnd.clone();
start.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH),
start.get(Calendar.DATE), 0, 0, 0);
start.set(Calendar.MILLISECOND, 0);
end.set(end.get(Calendar.YEAR), end.get(Calendar.MONTH),
end.get(Calendar.DATE), 0, 0, 0);
end.set(Calendar.MILLISECOND, 0);
return (int) ((end.getTimeInMillis() - start.getTimeInMillis()) / DAY_MILLSECONDS);
}
//获取星期几
public static String getWeek(long timeStamp) {
int myDate;
String week = null;
Calendar cd = Calendar.getInstance();
cd.setTime(new Date(timeStamp));
myDate = cd.get(Calendar.DAY_OF_WEEK);
// 获取指定日期转换成星期几
if (myDate == 1) {
week = "星期日";
} else if (myDate == 2) {
week = "星期一";
} else if (myDate == 3) {
week = "星期二";
} else if (myDate == 4) {
week = "星期三";
} else if (myDate == 5) {
week = "星期四";
} else if (myDate == 6) {
week = "星期五";
} else if (myDate == 7) {
week = "星期六";
}
return week;
}
/**
* 时间转化为显示字符串
*
* @param timeStamp 单位为秒
*/
public static String getTimeStr(long timeStamp) {
if (timeStamp == 0) return "";
Calendar inputTime = Calendar.getInstance();
inputTime.setTimeInMillis(timeStamp * 1000);
Date currenTimeZone = inputTime.getTime();
Calendar calendar = Calendar.getInstance();
if (calendar.before(inputTime)) {
//当前时间在输入时间之前
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
return sdf.format(currenTimeZone);
}
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (calendar.before(inputTime)) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
return sdf.format(currenTimeZone);
}
calendar.add(Calendar.DAY_OF_MONTH, -1);
if (calendar.before(inputTime)) {
return "昨天";
} else {
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
if (calendar.before(inputTime)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
return sdf.format(currenTimeZone);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
return sdf.format(currenTimeZone);
}
}
}
/**
* 时间转化为聊天界面显示字符串
*
* @param timeStamp 单位为秒
*/
public static String getChatTimeStr(long timeStamp) {
if (timeStamp == 0) return "";
Calendar inputTime = Calendar.getInstance();
inputTime.setTimeInMillis(timeStamp * 1000);
Date currenTimeZone = inputTime.getTime();
Calendar calendar = Calendar.getInstance();
if (calendar.before(inputTime)) {
//当前时间在输入时间之前
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
return sdf.format(currenTimeZone);
}
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (calendar.before(inputTime)) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
return sdf.format(currenTimeZone);
}
calendar.add(Calendar.DAY_OF_MONTH, -1);
if (calendar.before(inputTime)) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
return "昨天 " + sdf.format(currenTimeZone);
} else {
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
if (calendar.before(inputTime)) {
SimpleDateFormat sdf = new SimpleDateFormat("M月d日" + " HH:mm");
return sdf.format(currenTimeZone);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" + " HH:mm");
return sdf.format(currenTimeZone);
}
}
}
public static int getYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
public static int getMonth() {
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
public static int getCurrentMonthDay() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* 将字符串转为时间戳
*/
public static long getStringToDate(String time) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
Date date = new Date();
try {
date = simpleDateFormat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date.getTime();
}
//获得当前日期与本周一相差的天数
public static int getMondayPlus() {
Calendar cd = Calendar.getInstance();
// 获得今天是一周的第几天,星期日是第一天,星期二是第二天......
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
return -6;
} else {
return 2 - dayOfWeek;
}
}
//获得本周星期一的日期
public static Calendar getCurrentMonday() {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus);
Date monday = currentDate.getTime();
Calendar c = Calendar.getInstance();
c.setTime(monday);
return c;
}
// 上/下 一月
public static String getLastOrNextMonth(String timeStr, int value) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月");
Date date = new Date();
if (!timeStr.equals("本月")) {
try {
date = dateFormat.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 设置为当前时间
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - value);
date = calendar.getTime();
return dateFormat.format(date);
}
// 上/下 一周
public static String getLastOrNextWeek(String timeStr, int value) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年");
Date date = new Date();
Calendar calendar = Calendar.getInstance();
if (!timeStr.equals("本周")) {
try {
date = dateFormat.parse(timeStr.substring(0, timeStr.indexOf("") + 1));
calendar.setTime(date); // 设置为当前时间
calendar.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(timeStr
.substring(timeStr.indexOf("") + 1, timeStr.indexOf(""))) - value);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
calendar.setTime(date); // 设置为当前时间
calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - value);
}
date = calendar.getTime();
if (calendar.get(Calendar.WEEK_OF_YEAR) > 9) {
return dateFormat.format(date) + calendar.get(Calendar.WEEK_OF_YEAR) + "";
} else {
return dateFormat.format(date) + "0" + calendar.get(Calendar.WEEK_OF_YEAR) + "";
}
}
// 上/下 一日
public static String getLastOrNextDay(String timeStr, int value) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
if (!timeStr.equals("今日")) {
try {
date = dateFormat.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 设置为当前时间
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - value);
date = calendar.getTime();
return dateFormat.format(date);
}
// 是否是今日
public static Boolean isToday(String timeStr) {
return getDateEN(System.currentTimeMillis()).equals(timeStr);
}
//
// // 是否是本周
// public static Boolean isTswk(String timeStr) {
//
// Calendar calendar = Calendar.getInstance();
// int year = Integer.parseInt(timeStr.substring(0, timeStr.indexOf("年")));
// int week = Integer.parseInt(timeStr
// .substring(timeStr.indexOf("年") + 1, timeStr.indexOf("周")));
//
// return calendar.get(Calendar.YEAR) == year && calendar.get(Calendar.WEEK_OF_YEAR) == week;
// }
// 是否是本月
public static Boolean isTsM(String timeStr) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月");
String nowTime = dateFormat.format(new Date(System.currentTimeMillis()));
return timeStr.equals(nowTime);
}
public static String getDisparity(String timeStamp) {
Long target = getDateByString(timeStamp);
Long now = System.currentTimeMillis();
if (target < now) {
return "已截止";
}
Long l = target - now;
long Minute = (l / (1000 * 60));
long day = (l / (1000 * 60 * 60 * 24));
long min = Minute - (day * 60 * 24);
long hour = min / 60;
long minute = min - (hour * 60);
return day + "" + hour + ":" + minute + "";
}
}

View File

@@ -0,0 +1,103 @@
package com.android.api.encrytion;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
public final class UtilEncrypt {
/**
* 默认密钥,实际项目中可配置注入或数据库读取
*/
private final static String DEFAULT_KEY = "asla01slajf1ALlsdaf0987654321";
/**
* 对字符串进行默认加密
*/
public static String encrypt(String str) {
return encrypt(str, DEFAULT_KEY);
}
/**
* 对字符串加密
*/
public static String decrypt(String str) {
return decrypt(str, DEFAULT_KEY);
}
/**
* 对字符串加密
*/
public static String encrypt(String plainText, String key) {
byte[] bytes = null;
try {
bytes = plainText.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
try {
byte[] encryptedBytes = getCipher(Cipher.ENCRYPT_MODE, key).doFinal(bytes);
return UtilHex.bytes2HexString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 对字符串解密
*/
public static String decrypt(String encryptedText, String key) {
byte[] arr = UtilHex.hexString2Bytes(encryptedText);
try {
byte[] decryptedBytes = getCipher(Cipher.DECRYPT_MODE, key).doFinal(arr);
return new String(decryptedBytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static Cipher getCipher(int mode, String key) {
// Security.addProvider(new com.sun.crypto.provider.SunJCE());
// Security.addProvider(new Provider.SunJCE());
if (key == null) {
key = DEFAULT_KEY;
}
byte[] arrBTmp = null;
try {
arrBTmp = key.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 创建一个空的length位字节数组默认值为0
byte[] arrB = new byte[16];
// 将原始字节数组转换为8位
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
// 生成密钥
Key theKey = new javax.crypto.spec.SecretKeySpec(arrB, "AES");
// 生成Cipher对象,指定其支持的DES算法
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, theKey);
return cipher;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String value = encrypt("heartbeat.akrdinfo.cn");
System.out.println(value);
// System.out.println(decrypt("7ae044016890d6862e2e343f9b735db1464f0b63c251cce2e9855af9c3c7f6be"));
}
}

View File

@@ -0,0 +1,47 @@
package com.android.api.encrytion;
/**
* 16进制转换工具
*
* @author wulh create on 2018/5/20.
*/
public final class UtilHex {
/**
* 16进制字符串转为字节数组
* @param hexStr 长度必须为偶数,每个字节用两个字符表达
* @return 对应字节数组
*/
public static byte[] hexString2Bytes(String hexStr) {
if(hexStr == null || hexStr.length() == 0 || hexStr.length() % 2 > 0) {
throw new IllegalArgumentException("参数长度必须为偶数");
}
byte[] bytes = new byte[hexStr.length() / 2];
for(int i = 0, len = bytes.length; i < len; i++) {
bytes[i] = (byte) (0xFF & Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16));
}
return bytes;
}
/**
* 16进制字符串转为字节数组
* @param hexStr 长度必须为偶数,每个字节用两个字符表达
* @return 对应字节数组
*/
public static String bytes2HexString(byte[] bytes) {
if(bytes == null || bytes.length == 0) {
throw new IllegalArgumentException("参数必须非空");
}
StringBuilder sb = new StringBuilder();
for(byte b : bytes) {
String s = Integer.toHexString(0xFF & b);
if(s.length() == 1) {
s = "0" + s;
}
sb.append(s);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,31 @@
package com.android.api.response;
import com.android.nebulasdk.bean.BaseValue;
import java.io.Serializable;
/**
* Created by Administrator on 2018/5/11 0011.
*/
public class BaseResponse implements Serializable {
public String msg;
public int code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}

View File

@@ -0,0 +1,14 @@
package com.android.api.response;
public class EventResponse extends BaseResponse {
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}

View File

@@ -0,0 +1,46 @@
package com.android.database;
import java.util.List;
public abstract class AbstractDaoMannager<T> {
abstract void insert(Class<T> tClass, T t);
abstract Long inserteq(Class<T> tClass, T t);
abstract void insert(Class<T> tClass, List<T> list);
abstract void insertnew(Class<T> tClass, List<T> list);
abstract void update(Class<T> tClass, T t);
abstract void update(Class<T> tClass, List<T> list);
abstract T query(Class<T> tClass, T key);
abstract List<T> queryList(Class<T> tClass);
abstract List<T> queryListIn(Class<T> tClass, String key, Object[] value);
abstract List<T> queryByKeyList(Class<T> tClass, String key, String value);
abstract List<T> queryByKeyListDesc(Class<T> tClass, String key, String value,String descStr);
abstract List<T> queryByKeyListAsc(Class<T> tClass, String key, String value,String ascStr);
abstract List<T> queryByValueList(Class<T> tClass, String[] key, String[] value);
abstract List<T> queryByValueListDesc(Class<T> tClass, String[] key, String[] value,String descStr);
abstract List<T> queryByValueListAsc(Class<T> tClass, String[] key, String[] value,String ascStr);
abstract List<T> queryByDateLt(Class<T> tClass, String key, long date);
abstract void delete(Class<T> tClass, T t);
abstract void deleteAll(Class<T> tClass);
abstract void deleteByKey(Class<T> tClass, Long keyValue);
abstract void deleteByList(Class<T> tClass, List<T> values);
}

View File

@@ -0,0 +1,299 @@
package com.android.database;
import android.content.Context;
import android.util.Log;
import com.android.util.LogUtils;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
public class DaoManager<T> extends AbstractDaoMannager<T> {
private static DaoManager mInstance;
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;
public static void initeDao(Context mContext) {
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(mContext, "sofa-db", null);
mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
mDaoSession = mDaoMaster.newSession();
}
private DaoManager() {
}
public DaoMaster getMaster() {
return mDaoMaster;
}
public DaoSession getSession() {
return mDaoSession;
}
public static DaoManager getInstance() {
if (mInstance == null) {
mInstance = new DaoManager();
}
return mInstance;
}
private AbstractDao<T, T> getDao(Class<T> tClass) {
try {
return (AbstractDao<T, T>) mDaoMaster.newSession().getDao(tClass);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public void insert(Class<T> tClass, T t) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null) {
// dao.delete(t);
long id= dao.insertOrReplace(t);
LogUtils.loge( "====insertOrReplace===>"+id);
}
}
@Override
public Long inserteq(Class<T> tClass, T t) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null) {
// dao.delete(t);
long id= dao.insertOrReplace(t);
Log.e("====", "insertOrReplace===>"+id);
return id;
}
return -1L;
}
@Override
public void insert(Class<T> tClass, List<T> list) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null) {
dao.deleteAll();
dao.insertOrReplaceInTx(list);
}
}
@Override
public void insertnew(Class<T> tClass, List<T> list) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null) {
dao.insertOrReplaceInTx(list);
}
}
@Override
public void update(Class<T> tClass, T t) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null)
dao.update(t);
}
@Override
public void update(Class<T> tClass, List<T> list) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null)
dao.updateInTx(list);
}
@Override
public T query(Class<T> tClass, T key) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null)
return dao.load(key);
return null;
}
@Override
public List<T> queryList(Class<T> tClass) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao != null)
return dao.loadAll();
return null;
}
@Override
public List<T> queryListIn(Class<T> tClass, String key,Object[] value) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
for (Property property : properties) {
if (property.name.equals(key)) {
return dao.queryBuilder().where(property.in(value)).build().list();
}
}
return null;
}
@Override
public List<T> queryByKeyList(Class<T> tClass, String key, String value) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
for (Property property : properties) {
if (property.name.equals(key)) {
return dao.queryBuilder().where(property.eq(value)).build().list();
}
}
return null;
}
@Override
public List<T> queryByKeyListDesc(Class<T> tClass, String key, String value, String descStr) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
for (Property property : properties) {
if (property.name.equals(key)) {
return dao.queryBuilder().where(property.eq(value)).orderRaw(descStr+" DESC").build().list();
}
}
return null;
}
@Override
public List<T> queryByKeyListAsc(Class<T> tClass, String key, String value, String ascStr) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
for (Property property : properties) {
if (property.name.equals(key)) {
return dao.queryBuilder().where(property.eq(value)).orderRaw(ascStr+" ASC").build().list();
}
}
return null;
}
@Override
public List<T> queryByValueList(Class<T> tClass, String[] key, String[] value) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
QueryBuilder queryBuilder =dao.queryBuilder();
for (Property property : properties) {
for (int i=0;i<key.length; i++){
if (property.name.equals(key[i])) {
queryBuilder.where(property.eq(value[i]));
}
}
}
return queryBuilder.build().list();
}
@Override
public List<T> queryByValueListDesc(Class<T> tClass, String[] key, String[] value, String descStr) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
QueryBuilder queryBuilder =dao.queryBuilder();
for (Property property : properties) {
for (int i=0;i<key.length; i++){
if (property.name.equals(key[i])) {
queryBuilder.where(property.eq(value[i]));
}
}
}
return queryBuilder.orderRaw(descStr+" DESC").build().list();
}
@Override
public List<T> queryByValueListAsc(Class<T> tClass, String[] key, String[] value, String ascStr) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
QueryBuilder queryBuilder =dao.queryBuilder();
for (Property property : properties) {
for (int i=0;i<key.length; i++){
if (property.name.equals(key[i])) {
queryBuilder.where(property.eq(value[i]));
}
}
}
return queryBuilder.orderRaw(ascStr+" ASC").build().list();
}
@Override
public List<T> queryByDateLt(Class<T> tClass, String key, long date) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return null;
Property[] properties = dao.getProperties();
if (properties == null || properties.length == 0) return null;
for (Property property : properties) {
if (property.name.equals(key)) {
return dao.queryBuilder().where(property.lt(date)).build().list();
}
}
return null;
}
@Override
public void delete(Class<T> tClass, T t) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return;
dao.delete(t);
}
@Override
public void deleteAll(Class<T> tClass) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return;
dao.deleteAll();
}
@Override
public void deleteByKey(Class<T> tClass, Long keyValue) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return;
dao.deleteByKey((T) keyValue);
}
@Override
public void deleteByList(Class<T> tClass, List<T> values) {
AbstractDao<T, T> dao = getDao(tClass);
if (dao == null)
return ;
dao.deleteInTx(values);
}
}

View File

@@ -0,0 +1,177 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
@Entity
public class AdsInfoBean {
@Id(autoincrement = true)
private Long resId;
//广告位id
private long adId;
//广告资源ID
private long adResourceId;
//广告文件大小
private long adSize;
//资源类型
private String adType;
//广告url
private String adUri;
//广告版本
private long adVersion;
//app大小
private long appSize;
//app下载地址
private String appUrl;
//app版本
private long appVersion;
//广告为索引
private int id;
//信息
private String info;
//展示状态1展示0取消展示
private int state;
//视频,图片本地存储文件地址
private String localFilePath;
/**apk 本地存储文件地址*/
private String apkFilePath;
@Generated(hash = 147188525)
public AdsInfoBean() {
}
@Generated(hash = 1166581755)
public AdsInfoBean(Long resId, long adId, long adResourceId, long adSize, String adType,
String adUri, long adVersion, long appSize, String appUrl, long appVersion,
int id, String info, int state, String localFilePath, String apkFilePath) {
this.resId = resId;
this.adId = adId;
this.adResourceId = adResourceId;
this.adSize = adSize;
this.adType = adType;
this.adUri = adUri;
this.adVersion = adVersion;
this.appSize = appSize;
this.appUrl = appUrl;
this.appVersion = appVersion;
this.id = id;
this.info = info;
this.state = state;
this.localFilePath = localFilePath;
this.apkFilePath = apkFilePath;
}
public long getAdId() {
return this.adId;
}
public void setAdId(long adId) {
this.adId = adId;
}
public long getAdResourceId() {
return this.adResourceId;
}
public void setAdResourceId(long adResourceId) {
this.adResourceId = adResourceId;
}
public long getAdSize() {
return this.adSize;
}
public void setAdSize(long adSize) {
this.adSize = adSize;
}
public String getAdType() {
return this.adType;
}
public void setAdType(String adType) {
this.adType = adType;
}
public String getAdUri() {
return this.adUri;
}
public void setAdUri(String adUri) {
this.adUri = adUri;
}
public long getAppSize() {
return this.appSize;
}
public void setAppSize(long appSize) {
this.appSize = appSize;
}
public String getAppUrl() {
return this.appUrl;
}
public void setAppUrl(String appUrl) {
this.appUrl = appUrl;
}
public long getAppVersion() {
return this.appVersion;
}
public void setAppVersion(long appVersion) {
this.appVersion = appVersion;
}
public int getId() {
return this.id;
}
public String getInfo() {
return this.info;
}
public void setInfo(String info) {
this.info = info;
}
public int getState() {
return this.state;
}
public void setState(int state) {
this.state = state;
}
public long getAdVersion() {
return this.adVersion;
}
public void setAdVersion(long adVersion) {
this.adVersion = adVersion;
}
public void setId(int id) {
this.id = id;
}
public Long getResId() {
return this.resId;
}
public void setResId(Long resId) {
this.resId = resId;
}
public String getLocalFilePath() {
return localFilePath;
}
public void setLocalFilePath(String localFilePath) {
this.localFilePath = localFilePath;
}
public String getApkFilePath() {
return this.apkFilePath;
}
public void setApkFilePath(String apkFilePath) {
this.apkFilePath = apkFilePath;
}
}

View File

@@ -0,0 +1,105 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class AppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
private int select;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 478075949)
public AppBean(Long id, String packageName, String appName, int category,
int index, int select, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.select = select;
this.itemType = itemType;
}
@Generated(hash = 285800313)
public AppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
public int getSelect() {
return this.select;
}
public void setSelect(int select) {
this.select = select;
}
}

View File

@@ -0,0 +1,136 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class AppConfigBean {
/**id*/
@Id(autoincrement = true)
private Long id;
/**任务ID*/
private long taskId;
@Unique
private String packageName;
private String versionName;
private int versionCode;
/**是否禁用该任务0:未禁用 1禁用*/
private int disable;
/**是否自动运行开机启动安装完成后启动0不需要 1需要*/
private int autoStart;
/***是否是系统app*/
private boolean systemPermissions;
/**安装路径*/
private String installFilePath;
@Generated(hash = 1214769517)
public AppConfigBean(Long id, long taskId, String packageName,
String versionName, int versionCode, int disable, int autoStart,
boolean systemPermissions, String installFilePath) {
this.id = id;
this.taskId = taskId;
this.packageName = packageName;
this.versionName = versionName;
this.versionCode = versionCode;
this.disable = disable;
this.autoStart = autoStart;
this.systemPermissions = systemPermissions;
this.installFilePath = installFilePath;
}
@Generated(hash = 1080388749)
public AppConfigBean() {
}
public long getTaskId() {
return taskId;
}
public void setTaskId(long taskId) {
this.taskId = taskId;
}
public int getDisable() {
return disable;
}
public void setDisable(int disable) {
this.disable = disable;
}
public int getAutoStart() {
return autoStart;
}
public void setAutoStart(int autoStart) {
this.autoStart = autoStart;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public int getVersionCode() {
return versionCode;
}
public void setVersionCode(int versionCode) {
this.versionCode = versionCode;
}
public boolean isSystemPermissions() {
return systemPermissions;
}
public void setSystemPermissions(boolean systemPermissions) {
this.systemPermissions = systemPermissions;
}
public String getInstallFilePath() {
return installFilePath;
}
public void setInstallFilePath(String installFilePath) {
this.installFilePath = installFilePath;
}
public boolean getSystemPermissions() {
return this.systemPermissions;
}
}

View File

@@ -0,0 +1,78 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
@Entity
public class AppMonitorBean {
/**id*/
@Id(autoincrement = true)
private Long id;
private String pname;
private int vcode;
private int duration;
private int openTime;
private String date;
private long createTime;
@Generated(hash = 71959374)
public AppMonitorBean(Long id, String pname, int vcode, int duration,
int openTime, String date, long createTime) {
this.id = id;
this.pname = pname;
this.vcode = vcode;
this.duration = duration;
this.openTime = openTime;
this.date = date;
this.createTime = createTime;
}
@Generated(hash = 1312243382)
public AppMonitorBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPname() {
return this.pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getVcode() {
return this.vcode;
}
public void setVcode(int vcode) {
this.vcode = vcode;
}
public int getDuration() {
return this.duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public int getOpenTime() {
return this.openTime;
}
public void setOpenTime(int openTime) {
this.openTime = openTime;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public long getCreateTime() {
return this.createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
}

View File

@@ -0,0 +1,261 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Transient;
@Entity
public class DownLoadTaskBean {
private String url;
private long start;
private long end;
private long total;
/**文件类型*/
protected String minType;
/**
* 任务类型
*/
private int taskType;
/**taskid*/
@Id(autoincrement = true)
private Long taskId;
private String fileName;
private String path;
private long currentProgress;
private int status = 0;//-1、未下载0、下载中1、下载完成
//@Transient表明这个字段不会被写入数据库只是作为一个普通的java类字段用来临时存储数据的不会被持久化
@Transient
private DownLoadListener listener;
@Generated(hash = 517545372)
public DownLoadTaskBean(String url, long start, long end, long total,
String minType, int taskType, Long taskId, String fileName, String path,
long currentProgress, int status) {
this.url = url;
this.start = start;
this.end = end;
this.total = total;
this.minType = minType;
this.taskType = taskType;
this.taskId = taskId;
this.fileName = fileName;
this.path = path;
this.currentProgress = currentProgress;
this.status = status;
}
public String getMinType() {
return minType;
}
public void setMinType(String minType) {
this.minType = minType;
}
@Generated(hash = 949446503)
public DownLoadTaskBean() {
}
public int getTaskType() {
return taskType;
}
public void setTaskType(int taskType) {
this.taskType = taskType;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public long getStart() {
return this.start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return this.end;
}
public void setEnd(long end) {
this.end = end;
}
public long getTotal() {
return this.total;
}
public void setTotal(long total) {
this.total = total;
}
public Long getTaskId() {
return this.taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public String getFileName() {
return this.fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public long getCurrentProgress() {
return this.currentProgress;
}
public void setCurrentProgress(long currentProgress) {
this.currentProgress = currentProgress;
}
public int getStatus() {
return this.status;
}
public void setStatus(int status) {
this.status = status;
}
public DownLoadListener getListener() {
return listener;
}
public void setListener(DownLoadListener listener) {
this.listener = listener;
}
public interface DownLoadListener {
void onStart(long totalSize);
void onError(String error);
void onProgress(String fileName,long taskId,long progress);
void onFinish(String minType,String dowanloadUrl,String filePath, int taskType);
}
}

View File

@@ -0,0 +1,79 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
/**
* 记录设备活跃
*/
@Entity
public class EventBean {
/**id*/
@Id(autoincrement = true)
private Long id;
/**0:google广告播放事件1:IK广告播放事件件2:app启动事件...*/
private int eventCode;
/**设备地址*/
private String mac;
/**设备地址*/
private String cpu;
/**数据内容*/
private String content;
/**记录时间戳*/
private long createTime;
@Generated(hash = 614184384)
public EventBean(Long id, int eventCode, String mac, String cpu, String content,
long createTime) {
this.id = id;
this.eventCode = eventCode;
this.mac = mac;
this.cpu = cpu;
this.content = content;
this.createTime = createTime;
}
@Generated(hash = 1783294599)
public EventBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public int getEventCode() {
return this.eventCode;
}
public void setEventCode(int eventCode) {
this.eventCode = eventCode;
}
public String getMac() {
return this.mac;
}
public void setMac(String mac) {
this.mac = mac;
}
public String getCpu() {
return this.cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public long getCreateTime() {
return this.createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
}

View File

@@ -0,0 +1,107 @@
package com.android.database.lib;
import com.android.nebulasdk.bean.BaseEvent;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
@Entity
public class GoogleADEvent extends BaseEvent {
@Id(autoincrement = true)
private Long id;
private long beginTime;
private long endTime;
private long adIndexId;
private long createTime;
private String packageName;
private long versionCode;
private String logInfo;
@Generated(hash = 1149013858)
public GoogleADEvent(Long id, long beginTime, long endTime, long adIndexId,
long createTime, String packageName, long versionCode, String logInfo) {
this.id = id;
this.beginTime = beginTime;
this.endTime = endTime;
this.adIndexId = adIndexId;
this.createTime = createTime;
this.packageName = packageName;
this.versionCode = versionCode;
this.logInfo = logInfo;
}
@Generated(hash = 792411939)
public GoogleADEvent() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public long getBeginTime() {
return this.beginTime;
}
public void setBeginTime(long beginTime) {
this.beginTime = beginTime;
}
public long getEndTime() {
return this.endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public long getAdIndexId() {
return this.adIndexId;
}
public void setAdIndexId(long adIndexId) {
this.adIndexId = adIndexId;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public long getCreateTime() {
return this.createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public String getLogInfo() {
return this.logInfo;
}
public void setLogInfo(String logInfo) {
this.logInfo = logInfo;
}
public long getVersionCode() {
return this.versionCode;
}
public void setVersionCode(long versionCode) {
this.versionCode = versionCode;
}
}

View File

@@ -0,0 +1,96 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class LocalAppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 1795278542)
public LocalAppBean(Long id, String packageName, String appName, int category,
int index, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.itemType = itemType;
}
@Generated(hash = 1999393273)
public LocalAppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}

View File

@@ -0,0 +1,94 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class MusicAppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 1846047209)
public MusicAppBean(Long id, String packageName, String appName, int category,
int index, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.itemType = itemType;
}
@Generated(hash = 1422413757)
public MusicAppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}

View File

@@ -0,0 +1,100 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class NetShortAppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 789419113)
public NetShortAppBean(Long id, String packageName, String appName,
int category, int index, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.itemType = itemType;
}
@Generated(hash = 1272755811)
public NetShortAppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}

View File

@@ -0,0 +1,94 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class RecommendAppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 573747348)
public RecommendAppBean(Long id, String packageName, String appName,
int category, int index, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.itemType = itemType;
}
@Generated(hash = 707094890)
public RecommendAppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}

View File

@@ -0,0 +1,79 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
/**
* 记录设备活跃
*/
@Entity
public class RecordEventBean {
/**id*/
@Id(autoincrement = true)
private Long id;
/**0:app下载,1:设备活跃,2:app运行日志*/
private int eventCode;
/**设备地址*/
private String mac;
/**设备地址*/
private String cpuid;
/**数据内容*/
private String content;
/**记录时间戳*/
private long createTime;
@Generated(hash = 704718972)
public RecordEventBean(Long id, int eventCode, String mac, String cpuid,
String content, long createTime) {
this.id = id;
this.eventCode = eventCode;
this.mac = mac;
this.cpuid = cpuid;
this.content = content;
this.createTime = createTime;
}
@Generated(hash = 662360005)
public RecordEventBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public int getEventCode() {
return this.eventCode;
}
public void setEventCode(int eventCode) {
this.eventCode = eventCode;
}
public String getMac() {
return this.mac;
}
public void setMac(String mac) {
this.mac = mac;
}
public String getCpuid() {
return this.cpuid;
}
public void setCpuid(String cpuid) {
this.cpuid = cpuid;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public long getCreateTime() {
return this.createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
}

View File

@@ -0,0 +1,96 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class ShortAppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 1174928473)
public ShortAppBean(Long id, String packageName, String appName, int category,
int index, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.itemType = itemType;
}
@Generated(hash = 1507386286)
public ShortAppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}

View File

@@ -0,0 +1,122 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
@Entity
public class TaskInfoBean {
/**id*/
@Id(autoincrement = true)
private Long id;
/**任务类型*/
private int taskType;
/**任务id*/
private long taskId;
/**任务版本号*/
private long taskVersionCode;
/**下载地址*/
private String file_url;
/**文件类型*/
private String mimeType;
/**状态0:未下载1:正在下载,2:已下载*/
private int status;
/**文件名*/
private String fileName;
/**文件大小*/
private long filesize;
public long getFilesize() {
return filesize;
}
public void setFilesize(long filesize) {
this.filesize = filesize;
}
@Generated(hash = 2066165430)
public TaskInfoBean() {
}
@Generated(hash = 1476161118)
public TaskInfoBean(Long id, int taskType, long taskId, long taskVersionCode,
String file_url, String mimeType, int status, String fileName,
long filesize) {
this.id = id;
this.taskType = taskType;
this.taskId = taskId;
this.taskVersionCode = taskVersionCode;
this.file_url = file_url;
this.mimeType = mimeType;
this.status = status;
this.fileName = fileName;
this.filesize = filesize;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getTaskType() {
return taskType;
}
public void setTaskType(int taskType) {
this.taskType = taskType;
}
public long getTaskId() {
return taskId;
}
public void setTaskId(long taskId) {
this.taskId = taskId;
}
public long getTaskVersionCode() {
return taskVersionCode;
}
public void setTaskVersionCode(long taskVersionCode) {
this.taskVersionCode = taskVersionCode;
}
public String getFile_url() {
return file_url;
}
public void setFile_url(String file_url) {
this.file_url = file_url;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}

View File

@@ -0,0 +1,95 @@
package com.android.database.lib;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity
public class VideoAppBean {
@Id(autoincrement = true)
private Long id;
@Unique
private String packageName;
private String appName;
//快捷栏 1videomusicRecommed,myapp,local
/**
* music0x00Recommed0x01video0x02local0x03myapps:0x04,快捷栏:0x05
*
*/
private int category;
private int index;
//0:添加新应用1:普通应用
private int itemType;
@Generated(hash = 1990287931)
public VideoAppBean(Long id, String packageName, String appName, int category,
int index, int itemType) {
this.id = id;
this.packageName = packageName;
this.appName = appName;
this.category = category;
this.index = index;
this.itemType = itemType;
}
@Generated(hash = 307452192)
public VideoAppBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getCategory() {
return this.category;
}
public void setCategory(int category) {
this.category = category;
}
public int getIndex() {
return this.index;
}
public void setIndex(int index) {
this.index = index;
}
public int getItemType() {
return this.itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}

View File

@@ -0,0 +1,8 @@
package com.android.device;
import com.android.util.NetworkType;
public interface MediaStateChangeObserver {
public void onMediaRecever(String action);
}

View File

@@ -0,0 +1,76 @@
package com.android.device;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import com.android.eventbaus.EventBusUtils;
import com.android.eventbaus.MessageEvent;
import com.android.util.LogUtils;
import com.android.util.NetworkType;
import com.android.util.NetworkUtil;
import java.util.ArrayList;
import java.util.List;
public class MediaStateChangeReceiver extends BroadcastReceiver {
private static class InstanceHolder {
private static final MediaStateChangeReceiver INSTANCE = new MediaStateChangeReceiver();
}
private List<MediaStateChangeObserver> mObservers = new ArrayList<>();
@Override
public void onReceive(Context context, Intent intent) {
String action =intent.getAction();
LogUtils.loge("MediaStateChangeReceiver:"+action);
if (Intent.ACTION_MEDIA_EJECT.equals(action) || Intent.ACTION_MEDIA_UNMOUNTED.equals(action) || Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_MEDIA_STATUS));
}
}
public static void registerReceiver(Context context) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addDataScheme("file");
context.registerReceiver(InstanceHolder.INSTANCE, intentFilter);
}
public static void unRegisterReceiver(Context context) {
context.unregisterReceiver(InstanceHolder.INSTANCE);
}
public static void registerObserver(MediaStateChangeObserver observer) {
if (observer == null) {
return;
}
if (!InstanceHolder.INSTANCE.mObservers.contains(observer)) {
InstanceHolder.INSTANCE.mObservers.add(observer);
}
}
public static void unRegisterObserver(MediaStateChangeObserver observer) {
if (observer == null) {
return;
}
if (InstanceHolder.INSTANCE.mObservers == null) {
return;
}
InstanceHolder.INSTANCE.mObservers.remove(observer);
}
private void notifyObservers(String action) {
for (MediaStateChangeObserver observer : mObservers) {
observer.onMediaRecever(action);
}
}
}

View File

@@ -0,0 +1,9 @@
package com.android.device;
import com.android.util.NetworkType;
public interface NetStateChangeObserver {
public void onNetDisconnected();
public void onNetConnected(NetworkType networkType);
}

View File

@@ -0,0 +1,98 @@
package com.android.device;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import com.android.util.LogUtils;
import com.android.util.NetUtil;
import com.android.util.NetworkType;
import com.android.util.NetworkUtil;
import java.util.ArrayList;
import java.util.List;
public class NetStateChangeReceiver extends BroadcastReceiver {
private static class InstanceHolder {
private static final NetStateChangeReceiver INSTANCE = new NetStateChangeReceiver();
}
private List<NetStateChangeObserver> mObservers = new ArrayList<>();
// private int lastEffectiveNetworkType = -1;
// @Override
// public void onReceive(Context context, Intent intent) {
// if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
// int currentNetState = NetUtil.getNetWorkState(context);
// int currentEffectiveType = NetUtil.getEffectiveNetworkType(currentNetState);
// if (currentEffectiveType == lastEffectiveNetworkType) {
// LogUtils.loge("NetStateChangeReceiver同类型网络波动跳过通知类型" +
// NetUtil.getTypeName(currentEffectiveType) + "");
// return;
// }
//
// //类型变更 通知观察者,并更新上次类型
// lastEffectiveNetworkType = currentEffectiveType;
// NetworkType networkType = NetworkUtil.getNetworkType(context);
// LogUtils.loge("NetStateChangeReceiver网络类型变更" +
// NetUtil.getTypeName(lastEffectiveNetworkType) + "),通知观察者");
// notifyObservers(networkType);
// }
// }
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
NetworkType networkType = NetworkUtil.getNetworkType(context);
LogUtils.loge("NetStateChangeReceiver:"+networkType.toString());
notifyObservers(networkType);
}
}
public static void registerReceiver(Context context) {
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(InstanceHolder.INSTANCE, intentFilter);
}
public static void unRegisterReceiver(Context context) {
context.unregisterReceiver(InstanceHolder.INSTANCE);
}
public static void registerObserver(NetStateChangeObserver observer) {
if (observer == null) {
return;
}
if (!InstanceHolder.INSTANCE.mObservers.contains(observer)) {
InstanceHolder.INSTANCE.mObservers.add(observer);
}
}
public static void unRegisterObserver(NetStateChangeObserver observer) {
if (observer == null) {
return;
}
if (InstanceHolder.INSTANCE.mObservers == null) {
return;
}
InstanceHolder.INSTANCE.mObservers.remove(observer);
}
private void notifyObservers(NetworkType networkType) {
if (networkType == NetworkType.NETWORK_NO) {
for (NetStateChangeObserver observer : mObservers) {
observer.onNetDisconnected();
}
} else {
for (NetStateChangeObserver observer : mObservers) {
observer.onNetConnected(networkType);
}
}
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.download;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Global executor pools for the whole application.
* <p>
* Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind
* webservice requests).
*/
public class AppExecutors {
private static AppExecutors appExecutors;
private final Executor diskIO;
private final Executor networkIO;
private final Executor mainThread;
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
this.diskIO = diskIO;
this.networkIO = networkIO;
this.mainThread = mainThread;
}
private AppExecutors() {
this(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3),
new MainThreadExecutor());
}
public static AppExecutors getAppExecutors() {
if (appExecutors == null)
return new AppExecutors();
else
return appExecutors;
}
public Executor diskIO() {
return diskIO;
}
public Executor networkIO() {
return networkIO;
}
public Executor mainThread() {
return mainThread;
}
private static class MainThreadExecutor implements Executor {
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
mainThreadHandler.post(command);
}
}
}

View File

@@ -0,0 +1,277 @@
package com.android.download;
import android.content.Context;
import android.text.TextUtils;
import com.android.database.DaoManager;
import com.android.database.lib.DownLoadTaskBean;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import java.io.File;
import java.util.List;
public class DownLoadManeger {
private static DownLoadManeger instance;
private boolean isAuto = false;
private DownloadListener mDownloadListener;
public void registerDownloadListener(DownloadListener downloadListener){
this.mDownloadListener = downloadListener;
}
public void unRegisterDownloadListener(DownloadListener downloadListener){
this.mDownloadListener = null;
}
private DownLoadManeger(Context context) {
DaoManager.initeDao(context);
}
public static DownLoadManeger init(Context context){
if (instance == null)
instance = new DownLoadManeger(context);
return instance;
}
public static DownLoadManeger getInstance() {
return instance;
}
/**添加新的下载任务*/
public void addDownloadTask(DownloadBuilder builder){
if (TextUtils.isEmpty(builder.url)){
return;
}
DownLoadTaskBean downLoadTaskBean = null;
if(!isExistTask(builder.url)){
downLoadTaskBean = createTaskBean(builder);
}else {
LogUtils.loge("该下载任务已存在无需下载:");
return;
}
//添加下载任务队列
if( !TaskQueue.getInstance().isExistTask(downLoadTaskBean)) {
TaskQueue.getInstance().add(new DownLoadTaskThread(downLoadTaskBean, observer));//添加到下载队列中
}else {
LogUtils.loge("该下载任务已存在:"+ GsonUtil.GsonString(downLoadTaskBean));
}
}
/**下载没有完成的任务管理*/
public void restDownloadTask(){
List<DownLoadTaskBean> list = DaoManager.getInstance().queryList(DownLoadTaskBean.class); //未完成下载的任务
if(list.size()>0){
LogUtils.loge("start download");
for (DownLoadTaskBean downLoadTaskBean:list){
//添加下载任务队列
if( !TaskQueue.getInstance().isExistTask(downLoadTaskBean)) {
TaskQueue.getInstance().add(new DownLoadTaskThread(downLoadTaskBean, observer));//添加到下载队列中
}
}
}else {
LogUtils.loge("no download task");
}
}
/**清除任务队列*/
public void clear(){
TaskQueue.getInstance().clear();
}
public boolean isExistTask(String url) {//判断是否存在下载任务
List<DownLoadTaskBean> downLoadTaskBeans = DaoManager.getInstance().queryByKeyList(DownLoadTaskBean.class,"url",url);
if(downLoadTaskBeans!=null&&downLoadTaskBeans.size()==1){
return true;
}
return false;
}
private DownLoadTaskBean createTaskBean(DownloadBuilder builder) {//创建下载任务bean和创建下载任务
DownLoadTaskBean bean = new DownLoadTaskBean();
bean.setFileName(builder.name);
bean.setPath(builder.path);
bean.setUrl(builder.url);
bean.setTaskId(System.currentTimeMillis());
bean.setListener(builder.listener);
bean.setTotal(builder.total);
bean.setMinType(builder.minType);
bean.setTaskType(builder.taskType);
DownLoadTaskThread task = new DownLoadTaskThread(bean, observer);
DaoManager.getInstance().insert(DownLoadTaskBean.class, bean);//保存到数据库
return bean;
}
//自动下载
public void setAutoDownLoad(boolean isAuto) {
this.isAuto = isAuto;
}
public void pauseAll() {//全部暂停
TaskQueue.getInstance().pause();
}
public void clearTaskInteruptQueueAndRestart() {
List<DownLoadTaskBean> list = DaoManager.getInstance().queryList(DownLoadTaskBean.class);
for (DownLoadTaskBean downLoadTaskBean:list) {
if(!TextUtils.isEmpty(downLoadTaskBean.getUrl())&&!TextUtils.isEmpty(downLoadTaskBean.getFileName())&&!TextUtils.isEmpty(downLoadTaskBean.getPath())){
File file = new File(downLoadTaskBean.getPath()+downLoadTaskBean.getFileName()+"-tmp");
if(file.exists()&&downLoadTaskBean.getCurrentProgress()==file.length()&&file.length()<=downLoadTaskBean.getTotal()){
TaskQueue.getInstance().remove(downLoadTaskBean);
TaskQueue.getInstance().add(new DownLoadTaskThread(downLoadTaskBean, observer));
}
}
}
}
public void updateDownloadTaskBeanTable() {
List<DownLoadTaskBean> list = DaoManager.getInstance().queryList(DownLoadTaskBean.class);
for (DownLoadTaskBean downLoadTaskBean:list) {
if(downLoadTaskBean.getCurrentProgress()==0&&!TextUtils.isEmpty(downLoadTaskBean.getUrl())&&!TextUtils.isEmpty(downLoadTaskBean.getFileName())&&!TextUtils.isEmpty(downLoadTaskBean.getPath())){
File file = new File(downLoadTaskBean.getPath()+downLoadTaskBean.getFileName()+"-tmp");
if(file.exists()&&file.length()>0&&file.length()<=downLoadTaskBean.getTotal()){
downLoadTaskBean.setCurrentProgress(file.length());
DaoManager.getInstance().update(DownLoadTaskBean.class,downLoadTaskBean);
}
}else if(downLoadTaskBean.getCurrentProgress()!=0&&!TextUtils.isEmpty(downLoadTaskBean.getUrl())&&!TextUtils.isEmpty(downLoadTaskBean.getFileName())&&!TextUtils.isEmpty(downLoadTaskBean.getPath())){
File file = new File(downLoadTaskBean.getPath()+downLoadTaskBean.getFileName()+"-tmp");
if(file.exists()&&file.length()>downLoadTaskBean.getCurrentProgress()&&file.length()<=downLoadTaskBean.getTotal()){
downLoadTaskBean.setCurrentProgress(file.length());
DaoManager.getInstance().update(DownLoadTaskBean.class,downLoadTaskBean);
}
}
}
}
public static class DownloadBuilder {//构造器
protected String url;//下载地址
protected String path;//下载路径
protected String name;//文件名字
protected long total;//现在总进度
/**文件类型*/
protected String minType;
/**任务类型*/
protected int taskType;
protected DownLoadTaskBean.DownLoadListener listener;//下载监听
public DownloadBuilder setMinType(String minType) {
this.minType = minType;
return this;
}
public DownloadBuilder url(String url) {
this.url = url;
return this;
}
public DownloadBuilder filePath(String path) {
this.path = path;
return this;
}
public DownloadBuilder listener(DownLoadTaskBean.DownLoadListener listener) {
this.listener = listener;
return this;
}
public DownloadBuilder fileName(String name) {
this.name = name;
return this;
}
public DownloadBuilder taskType(int taskType) {
this.taskType = taskType;
return this;
}
public DownloadBuilder fileTotal(long fileSize){
this.total =fileSize;
return this;
}
}
public interface DownloadListener{
public void onStart(DownLoadTaskBean bean, long taskId);
public void onError(DownLoadTaskBean bean, long taskId, String erroMsg);
public void onProgress(DownLoadTaskBean bean, long taskId, long progress);
public void onFinish(DownLoadTaskBean bean, long taskId);
}
//下载线程的观察者
private DownLoadTaskThread.DownloadTaskObserver observer = new DownLoadTaskThread.DownloadTaskObserver() {
@Override
protected void onStart(DownLoadTaskBean bean, long taskId) {//下载开始,回调总进度给监听,方便设置进度大小
LogUtils.loge("taskId=" + taskId + ">>>>>" + bean.getTotal());
bean.setStatus(0);
AppExecutors.getAppExecutors().mainThread().execute(() -> {//切换到主线程
if (bean.getListener() != null) {
bean.getListener().onStart(bean.getTotal());
}
});
}
@Override
protected void onProgress(DownLoadTaskBean bean, long taskId, long progress) {//进度调用
synchronized (this) {//这里必须加同步代码块,因为这共用进度等变量
if(mDownloadListener!=null){
mDownloadListener.onProgress(bean,taskId,progress);
}
}
}
@Override
protected void onFinish(DownLoadTaskBean bean, long taskId, long lastProgress) {
synchronized (this) {
LogUtils.loge("download Exception===>sleeping finish");
TaskQueue.getInstance().remove(bean);//单个任务完成删除
DaoManager.getInstance().delete(DownLoadTaskBean.class, bean);
if(mDownloadListener!=null){
mDownloadListener.onFinish(bean,taskId);
}
}
}
@Override
protected void onPause(DownLoadTaskBean bean, long taskId, long currentProgress) {
synchronized (this) {//暂停这里必须加上同步,不然会出现实际进度跟显示进度不一致问题,其实也就是缓存没存进去,第二个线程又来了
// DaoManager.getInstance().update(DownLoadTaskBean.class, bean);//更新数据库退出app再进来就不会从头下载
}
}
@Override
protected void onError(DownLoadTaskBean bean, long taskId, String erroMsg) {//错误提示
if(mDownloadListener!=null){
mDownloadListener.onError(bean,taskId,erroMsg);
TaskQueue.getInstance().remove(bean);
// DaoManager.getInstance().delete(DownLoadTaskBean.class, bean);//删除数据库缓存
}
}
};
}

View File

@@ -0,0 +1,187 @@
package com.android.download;
import com.android.database.lib.DownLoadTaskBean;
import com.android.util.LogUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoadTaskThread implements Runnable {
private boolean pause;
private DownLoadTaskBean bean;
private long currentTotal = 0;
private DownloadTaskObserver observer;
public DownLoadTaskThread(DownLoadTaskBean bean, DownloadTaskObserver observer) {
this.bean = bean;
this.observer = observer;
}
@Override
public void run() {
HttpURLConnection urlConnection=null;
RandomAccessFile randomFile=null;
InputStream inputStream =null;
try {
URL url = new URL(bean.getUrl());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(20000); //设置连接超时事件为20秒
urlConnection.setRequestMethod("GET"); //设置请求方式为GET
//设置用户端可以接收的媒体类型
urlConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, " +
"image/pjpeg, application/x-shockwave-flash, application/xaml+xml, " +
"application/vnd.ms-xpsdocument, application/x-ms-xbap," +
" application/x-ms-application, application/vnd.ms-excel," +
" application/vnd.ms-powerpoint, application/msword, */*");
urlConnection.setRequestProperty("Accept-Language", "zh-CN"); //设置用户语言
urlConnection.setRequestProperty("Charset", "UTF-8"); //设置客户端编码
//设置用户代理
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; " +
"Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727;" +
" .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
File dataFile = new File(bean.getPath(), bean.getFileName());
if(dataFile.exists()&&dataFile.length()==bean.getTotal()){ //判断该文件已下载无需再下载
observer.onFinish(bean, bean.getTaskId(), dataFile.length());
return;
}
//设置文件写入位置
File file = new File(bean.getPath(), bean.getFileName()+"-tmp");
if(!file.exists()){
file.createNewFile();
}
currentTotal = file.length();
LogUtils.loge(bean.getStart() + "start------" + currentTotal + ">>>>" + bean.getTotal());
if(currentTotal==bean.getTotal()){
File targFile = new File(bean.getPath(), bean.getFileName());
file.renameTo(targFile);//重命名
file.delete();//删除临时文件
Thread.sleep(5000);
observer.onFinish(bean, bean.getTaskId(), currentTotal);
return;
}
//设置下载位置
urlConnection.setRequestProperty("Range", "bytes=" + currentTotal + "-");
randomFile = new RandomAccessFile(file, "rwd");
randomFile.seek(currentTotal);
urlConnection.connect();
if (observer != null) {
observer.onStart(bean, bean.getTaskId());
}
//获得文件流
inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024*10];
int len;
long time = System.currentTimeMillis();
while ( (currentTotal!=bean.getTotal())&&(len = inputStream.read(buffer)) != -1) {
//写入文件
randomFile.write(buffer, 0, len);
currentTotal += len;
//时间间隔大于500ms再发
if (System.currentTimeMillis() - time > 500) {
time = System.currentTimeMillis();
observer.onProgress(bean, bean.getTaskId(), currentTotal);
}
//判断是否是暂停状态.保存断点
if (observer != null && pause) {
break;
}
}
urlConnection.disconnect();
urlConnection=null;
randomFile.close();
randomFile=null;
inputStream.close();
inputStream=null;
observer.onProgress(bean, bean.getTaskId(), currentTotal);
if (observer != null && !pause) {
if(currentTotal == bean.getTotal()) {
LogUtils.loge("下载完成");
LogUtils.loge("download Exception===>sleeping before");
File targFile = new File(bean.getPath(), bean.getFileName());
file.renameTo(targFile);//重命名
file.delete();//删除临时文件
Thread.sleep(5000);
LogUtils.loge("download Exception===>sleeping after");
observer.onFinish(bean, bean.getTaskId(), currentTotal);
}else {
LogUtils.loge("下载失败");
if (observer != null) {
observer.onError(bean, bean.getTaskId(), "下载失败");
}
}
}
} catch (Exception e) {
e.printStackTrace();
LogUtils.loge("download Exception===>"+e.getMessage());
if (observer != null) {
observer.onError(bean, bean.getTaskId(), e.getMessage());
}
}finally {
if(urlConnection!=null) {
urlConnection.disconnect();
urlConnection=null;
}
try {
if(randomFile!=null) {
randomFile.close();
randomFile=null;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(inputStream!=null) {
inputStream.close();
inputStream=null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public DownLoadTaskBean getBean() {
return bean;
}
public void setBean(DownLoadTaskBean bean) {
this.bean = bean;
}
public void setPause(boolean pause) {
this.pause = pause;
}
protected static abstract class DownloadTaskObserver {
protected abstract void onStart(DownLoadTaskBean bean, long taskId);
protected abstract void onProgress(DownLoadTaskBean bean, long taskId, long progress);
protected abstract void onFinish(DownLoadTaskBean bean, long taskId, long lastProgress);
protected abstract void onPause(DownLoadTaskBean bean, long taskId, long currentProgress);
protected abstract void onError(DownLoadTaskBean bean, long taskId, String erroMsg);
}
}

View File

@@ -0,0 +1,160 @@
package com.android.download;
import android.content.Context;
import com.android.util.FileUtil;
import com.android.util.LogUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadAppTask extends Thread{
public static int threadCount = 3;
public static int runningThread = 3;
private String downurl;
private Context mContext;
/**存储路径*/
private String FILEPATH_STORAGE;
/**临时文件名称*/
public static String FILENAME_TMP="Nebula-app.bak";
/**正是文件名称*/
private static String FILENAME_APK="Nebula-app.apk";
private DownLoadAppListener mDownLoadAppListener;
private long startIndex = 0;
private long totalSize = 0;
public DownloadAppTask(Context context,String versionCode,String url,long fileSize,DownLoadAppListener downLoadAppListener){
mContext = context;
this.downurl = url;
this.totalSize = fileSize;
this.mDownLoadAppListener = downLoadAppListener;
this.FILEPATH_STORAGE = FileUtil.getBakPath(mContext,1) ;
FILENAME_APK=versionCode+"-"+FILENAME_APK;
}
@Override
public void run() {
super.run();
try {
File tempfile =new File(FILEPATH_STORAGE,FILENAME_TMP);
if(tempfile.exists()){
startIndex = tempfile.length();
}else {
tempfile.createNewFile();
}
HttpURLConnection urlConnection;
URL url = new URL(downurl);
// URL url = new URL(" https://ik-cos-1258208609.cos.ap-guangzhou.myqcloud.com/Chrome.apk");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(2000*10); //设置连接超时事件为5秒
urlConnection.setRequestMethod("GET"); //设置请求方式为GET
//设置用户端可以接收的媒体类型
urlConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, " +
"image/pjpeg, application/x-shockwave-flash, application/xaml+xml, " +
"application/vnd.ms-xpsdocument, application/x-ms-xbap," +
" application/x-ms-application, application/vnd.ms-excel," +
" application/vnd.ms-powerpoint, application/msword, */*");
urlConnection.setRequestProperty("Accept-Language", "zh-CN"); //设置用户语言
urlConnection.setRequestProperty("Charset", "UTF-8"); //设置客户端编码
//设置用户代理
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; " +
"Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727;" +
" .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
//设置下载位置
urlConnection.setRequestProperty("Range", "bytes=" + startIndex + "-" + (totalSize-1));
LogUtils.loge("totalSize:"+totalSize+"");
LogUtils.loge("getResponseCode:"+urlConnection.getResponseCode()+"");
InputStream in = urlConnection.getInputStream();
RandomAccessFile raf = new RandomAccessFile(tempfile.getPath(), "rwd");
raf.seek(startIndex);
int len = 0;
int progress=0;
byte buf[] =new byte[1024];
while((len = in.read(buf))!=-1){
raf.write(buf, 0, len);
progress+=len;
LogUtils.loge("downlaod progress:"+progress);
}
in.close();
raf.close();
File apkFile = new File(FILEPATH_STORAGE,FILENAME_APK);
LogUtils.loge("downlaod:"+tempfile.length());
if(tempfile.length()==totalSize){
tempfile.renameTo(apkFile);
tempfile.delete();
//下载完成
if(mDownLoadAppListener!=null){
mDownLoadAppListener.onDowanlaodResult(0,apkFile.getPath());
}
}else {
if(mDownLoadAppListener!=null){
mDownLoadAppListener.onDowanlaodResult(-1,null);
}
}
} catch (Exception e) {
e.printStackTrace();
if(mDownLoadAppListener!=null){
mDownLoadAppListener.onDowanlaodResult(-1,null);
}
}
}
// public boolean executeAppInstall(String apkPath){
// boolean result = false;
// try {
// Runtime.getRuntime().exec("su");
// String command = "pm install -r " + apkPath + "\n";
// Process process = Runtime.getRuntime().exec(command);
// BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String msg = "";
// String line;
// while ((line = errorStream.readLine()) != null) {
// msg += line;
// }
// if (!msg.contains("Failure")) {
// result = true;
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// }
// return result;
// }
public interface DownLoadAppListener{
public void onDowanlaodResult(int status,String filePath);
}
}

View File

@@ -0,0 +1,192 @@
package com.android.download;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
import com.android.api.biz.CoreKeys;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadService {
/**
* 是否正在下载
*/
private boolean isDownloading=false;
public static int progress;
private String dowUrl = null;
//下载状态
private int status = -1;
private int fileSize;
private int readSize;
private int downSize;
private File downFile;
private static DownloadService mInstance = null;
private DownlaodProgressCallBack mDownlaodProgressCallBack;
/**下载完成状态*/
public static final int DOWNLOAD_COMPLETE=0;
/**下载完成状态*/
public static final int DOWNLOAD_ERROR=-1;
public static final String FEATURE_PATH = CoreKeys.down_file+"atv.apk";
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
// //更新下载进度
if(mDownlaodProgressCallBack!=null){
int progress = (int) ((double) downSize / (double) fileSize * 100);
mDownlaodProgressCallBack.onDownlaodProgress(progress);
}
break;
case 1:
//下载完成进度
mDownlaodProgressCallBack.onDownlaodStatus(DOWNLOAD_COMPLETE);
break;
case 2:
//下载异常
mDownlaodProgressCallBack.onDownlaodStatus(DOWNLOAD_ERROR);
break;
}
}
};
private DownloadService(){
}
public static DownloadService initDownloadService(){
if(mInstance ==null){
mInstance = new DownloadService();
}
return mInstance;
}
public static DownloadService getInstance(){
return mInstance;
}
public void initDownLoadUrl(String downloadUrl){
dowUrl = downloadUrl;
}
public void setDownlaodProgressCallBack(DownlaodProgressCallBack downlaodProgressCallBack){
this.mDownlaodProgressCallBack = downlaodProgressCallBack;
}
public void startService(){
if(isDownloading){
return;
}
new Thread(startDownload).start();
}
public void stopService(){
isDownloading = true;
}
/**
* 下载模块
*/
private Runnable startDownload = new Runnable() {
@Override
public void run() {
fileSize = 0;
readSize = 0;
downSize = 0;
progress = 0;
InputStream is = null;
FileOutputStream fos = null;
Log.e("downUrl", dowUrl);
try {
URL myURL = new URL(dowUrl);
URLConnection conn = myURL.openConnection();
conn.connect();
fileSize = conn.getContentLength();
is = conn.getInputStream();
if (is == null) {
Log.d("tag", "error");
throw new RuntimeException("stream is null");
}
File dir = new File(CoreKeys.down_file);
if (!dir.exists()) {
dir.mkdirs();
}
downFile = new File(FEATURE_PATH);
fos = new FileOutputStream(downFile);
byte buf[] = new byte[1024 * 1024];
isDownloading = true;
while ((readSize = is.read(buf)) > 0) {
if(!isDownloading){
return;
}
fos.write(buf, 0, readSize);
downSize += readSize;
Log.e("downSize", downSize+"");
sendMessage(0,downSize);
}
sendMessage(1);
isDownloading = false;
} catch (Exception e) {
sendMessage(2);
} finally {
try {
if (null != fos) fos.close();
if (null != is) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
private void sendMessage(int code){
handler.sendEmptyMessage(code);
}
private void sendMessage(int code,int progress){
Message message = new Message();
message.what=code;
message.arg1 = progress;
handler.sendMessage(message);
}
/**
* 获取进度
*/
public int getProgress() {
return progress;
}
public interface DownlaodProgressCallBack{
public void onDownlaodProgress(int progress);
public void onDownlaodStatus(int status);
}
}

View File

@@ -0,0 +1,88 @@
package com.android.download;
import com.android.database.lib.DownLoadTaskBean;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TaskQueue {
private static TaskQueue instance;
private List<DownLoadTaskThread> mTaskQueue;
private ExecutorService downloadThreadCache = Executors.newFixedThreadPool(3);//这里是写死最多5个线程
private TaskQueue() {
mTaskQueue = new ArrayList<>();
}
public int size() {
return mTaskQueue.size();
}
public static TaskQueue getInstance() {
if (instance == null)
instance = new TaskQueue();
return instance;
}
public List<DownLoadTaskThread> getAllTask() {
return mTaskQueue;
}
public void add(DownLoadTaskThread task) {
mTaskQueue.add(task);
downloadThreadCache.execute(task);
}
public void clear(){
mTaskQueue.clear();
}
public void remove(DownLoadTaskBean p) {
for (int i = 0; i < mTaskQueue.size(); i++) {
DownLoadTaskThread task = mTaskQueue.get(i);
if (task.getBean().getUrl().equals(p.getUrl())) {
mTaskQueue.remove(i);
break;
}
}
}
public boolean isExistTask(DownLoadTaskBean p) {
for (DownLoadTaskThread task : mTaskQueue) {
if (task.getBean().getUrl().equals(p.getUrl()))
return true;
}
return false;
}
public void pause(String url) {
for (DownLoadTaskThread task : mTaskQueue) {
if (task.getBean().getUrl().equals(url)) {
task.setPause(true);
}
}
}
public void pause() {
for (DownLoadTaskThread task : mTaskQueue) {
task.setPause(true);
}
}
public void start(String url) {
for (DownLoadTaskThread task : mTaskQueue) {
if (task.getBean().getUrl().equals(url)) {
task.setPause(false);
}
}
}
}

View File

@@ -0,0 +1,33 @@
package com.android.eventbaus;
import org.greenrobot.eventbus.EventBus;
public class EventBusUtils {
public static void registerEventBus(Object subscriber){
if(!EventBus.getDefault().isRegistered(subscriber)){
EventBus.getDefault().register(subscriber);
}
}
public static void unRegisterEventBus(Object subscriber){
if(EventBus.getDefault().isRegistered(subscriber)){
EventBus.getDefault().unregister(subscriber);
}
}
public static void postMsg(MessageEvent meshMsgEvent){
EventBus.getDefault().post(meshMsgEvent);
}
public static void postSticky(MessageEvent meshMsgEvent){
EventBus.getDefault().postSticky(meshMsgEvent);
}
public static void removeStickEvent(MessageEvent meshMsgEvent){
EventBus.getDefault().removeStickyEvent(meshMsgEvent);
}
}

View File

@@ -0,0 +1,33 @@
package com.android.eventbaus;
public class MessageEvent<T> {
public static final String ACTION_UPADATE_DATA_SOURCE="com.mxq.update.appinfo";
public static final String ACTION_UPADATE_APPS_SOURCE="com.mxq.update.apps";
public static final String ACTION_UPADATE_MEDIA_STATUS="com.ik.mxq.update.media_status";
public int msgType;
public String action;
public T objectBean;
public MessageEvent(){
}
public MessageEvent(int msgType, String action, T msgBean) {
this.msgType = msgType;
this.action = action;
this.objectBean = msgBean;
}
public MessageEvent(String action, T msgBean) {
this.action = action;
this.objectBean = msgBean;
}
public MessageEvent(String action) {
this.action = action;
}
}

View File

@@ -0,0 +1,71 @@
package com.android.monitor;
import android.content.Context;
import com.android.database.DaoManager;
import com.android.monitor.impl.EventFactory;
import com.android.util.LogManager;
import com.android.util.LogUtils;
public class DataBeeObserver {
private static DataBeeObserver mInstance =null;
private Context mContext;
private DataBeeObserver(Context context){
mContext = context;
LogManager.init(mContext);
DaoManager.initeDao(mContext);
// MonitorManager.init(mContext);
EventFactory.create().createEventImpls();
// MonitorManager.getmInstance().startMonitor();
LogUtils.loge("Data Bee init...");
}
public static void init(Context context){
if(mInstance==null){
mInstance = new DataBeeObserver(context);
}
}
public static DataBeeObserver getInstance(){
return mInstance;
}
public void recordEventMsg(int eventCode){
EventFactory.create().getEventInterface(eventCode).recordEventMsg(mContext);
}
public void recordEventMsg(int eventCode,long beginTime){
EventFactory.create().getEventInterface(eventCode).recordEventMsg(mContext,beginTime);
}
public void recordEventMsg(int eventCode,long beginTime,long endTime){
EventFactory.create().getEventInterface(eventCode).recordEventMsg(mContext,beginTime,endTime);
}
public void recordEventMsg(int eventCode,int adIndexId,long beginTime,long endTime,String msg){
EventFactory.create().getEventInterface(eventCode).recordEventMsg(mContext,adIndexId,beginTime,endTime,msg);
}
public void destroy(){
MonitorManager.getmInstance().destroy();
EventFactory.create().destroy();
}
}

View File

@@ -0,0 +1,115 @@
package com.android.monitor;
import android.content.Context;
import com.android.database.DaoManager;
import com.android.database.lib.EventBean;
import com.android.nebulasdk.bean.EventDataInfo;
import com.android.monitor.impl.EventFactory;
import com.android.nebulasdk.presenter.DataBeePresenter;
import com.android.nebulasdk.presenter.callback.NetCallback;
import com.android.util.LogUtils;
import com.android.util.NetUtil;
import java.util.List;
public class MonitorManager implements NetCallback {
Context mContext;
private DataBeePresenter mDataBeePresenter;
private MonitorThread mMonitorThread;
private static MonitorManager mInstance=null;
private MonitorManager(Context context){
this.mContext = context;
mDataBeePresenter = new DataBeePresenter(mContext,this);
}
public static void init(Context context){
if(mInstance==null){
mInstance = new MonitorManager(context);
}
}
public static MonitorManager getmInstance(){
return mInstance;
}
@Override
public void onViewFailureString(int code, String message) {
LogUtils.loge("onViewFailureString==>"+message);
}
@Override
public void onExceptionFailure(String message) {
LogUtils.loge("onExceptionFailure==>"+message);
}
@Override
public void onServerFailure(int code, String message) {
LogUtils.loge("onServerFailure==>"+message);
}
@Override
public void onNetWorkResult(int code) {
if(code==0){
deleteEvents();
}
}
public void submit(Context context){
int netWorkState = NetUtil.getNetWorkState(context);
if (netWorkState == NetUtil.NETWORK_MOBILE || netWorkState == NetUtil.NETWORK_WIFI || netWorkState == NetUtil.NETWORK_ETHERNET) {
LogUtils.loge("有可用网络");
List<EventBean> recordEventBeanList = DaoManager.getInstance().queryList(EventBean.class);
if(recordEventBeanList!=null&&recordEventBeanList.size()>0) {
List<EventDataInfo> eventDataInfoList = EventFactory.create().packageData(recordEventBeanList);
mDataBeePresenter.postEventData(eventDataInfoList);
}else {
LogUtils.loge("无提交事件记录");
}
} else {
LogUtils.loge("没有可用网络,无法提交数据");
}
}
public void postEventMsg(Context context){
EventFactory.create().postEventMsg(context);
}
private void deleteEvents(){
LogUtils.loge("deleteEvents===>");
DaoManager.getInstance().deleteAll(EventBean.class);
}
public void startMonitor(){
if(mMonitorThread==null){
mMonitorThread=new MonitorThread(mContext);
}
if(!mMonitorThread.isRunning()) {
mMonitorThread.startThread();
}
}
public void destroy(){
// mMonitorThread.stopThread();
//mMonitorThread=null;
mInstance =null;
}
}

View File

@@ -0,0 +1,68 @@
package com.android.monitor;
import android.content.Context;
import com.android.util.LogUtils;
/**
* 监控线程
*/
public class MonitorThread extends Thread {
private Context mContext;
private boolean isStart = false;
private static final long MONITORTIME = 1000 * 60*5;
public MonitorThread(Context context){
this.mContext = context;
}
/**
* 开启线程
*/
public void startThread() {
LogUtils.loge("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA========================");
this.isStart = true;
this.start();
}
/**
* 关闭线程
*/
public void stopThread() {
this.isStart = false;
}
@Override
public void run() {
super.run();
// while (isStart){
// try {
// LogUtils.loge("start monitorINTERVAL_TIME IS "+(MONITORTIME/1000/60)+" MINUTE");
// MonitorManager.getmInstance().postEventMsg(mContext);
// MonitorManager.getmInstance().submit(mContext);
// LogUtils.loge("end monitor ");
// } catch (Exception e) {
// e.printStackTrace();
// }
// try {
// sleep(MONITORTIME);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// isStart =false;
// LogUtils.loge("The Monitor is end");
}
public boolean isRunning() {
return isStart;
}
}

View File

@@ -0,0 +1,100 @@
package com.android.monitor.impl;
import android.content.Context;
import com.android.database.lib.EventBean;
import com.android.database.lib.GoogleADEvent;
import com.android.nebulasdk.bean.EventDataInfo;
import com.android.util.GsonUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class EventFactory {
/**0:google广告播放事件1:IK广告播放事件件2:其他事件...*/
public static final int EVENT_GOOGLE_AD=0;
public static final int EVENT_IK_AD=1;
public static final int EVENT_OTHER=2;
private static EventFactory mInstance = null;
private Map<Integer, EventInterface> interfaceMap = new HashMap<>();
private EventFactory(){
}
public static EventFactory create(){
if(mInstance==null){
mInstance = new EventFactory();
}
return mInstance;
}
public void createEventImpls(){
interfaceMap.put(EVENT_GOOGLE_AD,new GoogleEventImpl());
// interfaceMap.put(EVENT_GOOGLE_AD,new GoogleEventImpl()); 后续扩展
// interfaceMap.put(EVENT_GOOGLE_AD,new GoogleEventImpl()); 后续扩展
}
public EventInterface getEventInterface(int eventCode){
return interfaceMap.get(eventCode);
}
public void postEventMsg(Context context){
Iterator it= interfaceMap.keySet().iterator();
while (it.hasNext()){
EventInterface eventInterface = interfaceMap.get(it.next());
if(eventInterface!=null){
eventInterface.postEventMsg(context);
}
}
}
public List<EventDataInfo> packageData(List<EventBean> recordEventBeans) {
List<EventDataInfo> eventDataInfoList =new ArrayList<>();
for (EventBean eventBean:recordEventBeans){
EventDataInfo eventDataInfo =new EventDataInfo();
eventDataInfo.setCreateTime(eventBean.getCreateTime());
eventDataInfo.setEventCode(eventBean.getEventCode());
eventDataInfo.setCpu(eventBean.getCpu());
eventDataInfo.setMac(eventBean.getMac());
List<GoogleADEvent> googleADEventList = GsonUtil.GsonToList(eventBean.getContent(),GoogleADEvent.class);
eventDataInfo.setContent(googleADEventList);
eventDataInfoList.add(eventDataInfo);
}
return eventDataInfoList;
}
public void destroy(){
Iterator it= interfaceMap.keySet().iterator();
while (it.hasNext()){
EventInterface eventInterface = interfaceMap.get(it.next());
if(eventInterface!=null){
eventInterface=null;
}
}
interfaceMap.clear();
interfaceMap=null;
mInstance=null;
}
}

View File

@@ -0,0 +1,18 @@
package com.android.monitor.impl;
import android.content.Context;
public interface EventInterface {
public void recordEventMsg(Context context);
public void recordEventMsg(Context context,long beginTime);
public void recordEventMsg(Context context,long beginTime,long endTime);
public void recordEventMsg(Context context,int adIndexId,long beginTime,long endTime,String msg);
public void postEventMsg(Context context);
}

View File

@@ -0,0 +1,84 @@
package com.android.monitor.impl;
import android.content.Context;
import com.android.MXQConfig;
import com.android.database.DaoManager;
import com.android.database.lib.EventBean;
import com.android.database.lib.GoogleADEvent;
import com.android.util.AppInstallUtil;
import com.android.util.DateUtil;
import com.android.util.DeviceUtil;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.android.util.RKDeviceUtil;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class GoogleEventImpl implements EventInterface {
@Override
public void recordEventMsg(Context context) {
recordEventMsg( context, System.currentTimeMillis());
}
@Override
public void recordEventMsg(Context context ,long beginTime) {
recordEventMsg(context,beginTime,System.currentTimeMillis());
}
@Override
public void recordEventMsg(Context context,long beginTime, long endTime) {
recordEventMsg(context,100,beginTime,endTime,"");
}
@Override
public void recordEventMsg(Context context, int adIndexId, long beginTime, long endTime, String msg) {
Calendar calendar= Calendar.getInstance();
GoogleADEvent googleADEvent = new GoogleADEvent(null,beginTime,endTime,adIndexId,getDayTime(calendar.getTime()),context.getPackageName(), AppInstallUtil.getAppVersion(context),msg);
LogUtils.loge("record event msg :"+ GsonUtil.GsonString(googleADEvent));
// DaoManager.getInstance().insert(GoogleADEvent.class,googleADEvent);
}
@Override
public void postEventMsg(Context context) {
//获取当前日期
Calendar calendar= Calendar.getInstance();
// 将日期增加一天,测试用
// calendar.add(Calendar.DAY_OF_MONTH,1);
List<GoogleADEvent> googleADEventList =DaoManager.getInstance().queryByDateLt(GoogleADEvent.class,"createTime", getDayTime(calendar.getTime()));
// LogUtils.loge("YesterDay size is :"+googleADEventList==null?"null":googleADEventList.size()+"");
if(googleADEventList!=null&&googleADEventList.size()>0) {
EventBean eventBean = new EventBean();
eventBean.setEventCode(EventFactory.EVENT_GOOGLE_AD);
if(MXQConfig.ALLWINNER_PLATFORM.equalsIgnoreCase(MXQConfig.getManufacturer())){
eventBean.setCpu(DeviceUtil.getCpu());
}else {
eventBean.setCpu(RKDeviceUtil.getCpu());
}
eventBean.setMac(DeviceUtil.getEthernetMac());
eventBean.setContent(GsonUtil.GsonString(googleADEventList));
eventBean.setCreateTime(System.currentTimeMillis());
//DaoManager.getInstance().insert(EventBean.class,eventBean);
// DaoManager.getInstance().deleteByList(GoogleADEvent.class,googleADEventList);
}else {
LogUtils.loge("没有可记录的数据");
}
}
private long getDayTime(Date date) {
LogUtils.loge("DateUtil.gettoDayDate()1:"+ DateUtil.format(date));
return DateUtil.parse(DateUtil.format(date, DateUtil.FORMAT_LONOGRAM), DateUtil.FORMAT_LONOGRAM).getTime();
}
}

View File

@@ -0,0 +1,460 @@
package com.android.nebulasdk;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import com.android.database.AdsInfoBeanDao;
import com.android.database.DaoManager;
import com.android.database.lib.AdsInfoBean;
import com.android.database.lib.DownLoadTaskBean;
import com.android.database.lib.NetShortAppBean;
import com.android.database.lib.ShortAppBean;
import com.android.download.DownLoadManeger;
import com.android.eventbaus.EventBusUtils;
import com.android.eventbaus.MessageEvent;
import com.android.nebulasdk.bean.ADInfo;
import com.android.util.FileUtil;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.android.util.PakageInstallUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import kotlin.jvm.internal.MagicApiIntrinsics;
public class ADManager implements DownLoadManeger.DownloadListener {
private static ADManager mInstance = null;
private Context mContext;
private Handler handler = new Handler();
/**广告类型-图片*/
public static final String ADTYPE_IMAGE="image";
/**广告类型-视频*/
public static final String ADTYPE_VIDEO="video";
/**广告类型-文本*/
public static final String ADTYPE_TEXT="text";
/**广告类型-收藏*/
public static final String ADTYPE_FAV="fav";
private ADManager(Context context){
this.mContext = context;
DownLoadManeger.init(context);
DownLoadManeger.getInstance().registerDownloadListener(this);
}
public static void init(Context context){
if(mInstance==null){
mInstance = new ADManager(context);
}
}
public static ADManager getInstance(){
return mInstance;
}
/**
* 更新广告展位信息
* @param adInfoList
*/
public void updateADInfo(List<ADInfo> adInfoList){
LogUtils.loge("start updateADInfo"+GsonUtil.GsonString(adInfoList));
List<AdsInfoBean> oldAdsInfoBeanList = DaoManager.getInstance().queryList(AdsInfoBean.class);
for (AdsInfoBean adsInfoBean:oldAdsInfoBeanList){
boolean flag=false;
for (int i=0;i<adInfoList.size();i++){
ADInfo newADInfo= adInfoList.get(i);
if(adsInfoBean.getId()==newADInfo.getId()){
flag=true; //广告任务还存在
LogUtils.loge(adsInfoBean.getId()+" 广告任务还存在");
break;
}
}
if(!flag){ //广告任务不存在了
LogUtils.loge(adsInfoBean.getId()+" 广告任务不存在了");
adsInfoBean.setState(0);//更新任务为关闭状态,暂时不删除数据
DaoManager.getInstance().update(AdsInfoBean.class,adsInfoBean);
// DaoManager.getInstance().delete(AdsInfoBean.class,adsInfoBean);
// if(adsInfoBean.getLocalFilePath()!=null) {//存在本地文件
// File file = new File(adsInfoBean.getLocalFilePath());
// if (file.exists()) {
// file.delete();
// }
// }
if(adsInfoBean.getId()==12){ //删除收藏数据
DaoManager.getInstance().delete(AdsInfoBean.class,adsInfoBean);
DaoManager.getInstance().deleteAll(NetShortAppBean.class);
List<NetShortAppBean> netShortAppBeanList = DaoManager.getInstance().queryList(NetShortAppBean.class);
if(netShortAppBeanList==null){
LogUtils.loge("NetShortAppBean size: 0");
}else {
LogUtils.loge("NetShortAppBean size: "+netShortAppBeanList.size());
}
}
}
}
for (ADInfo aDInfo:adInfoList){
if(aDInfo.getAdVersion()==null||"".equals(aDInfo.getAdVersion())||"null".equals(aDInfo.getAdVersion())){ //ADVersion 不存在时该数据为非法数据
LogUtils.loge("AdVersion is "+aDInfo.getAdVersion()+", 非法数据");
continue;
}
List<AdsInfoBean> adsInfoBeanList =DaoManager.getInstance().queryByKeyList(AdsInfoBean.class,"id",aDInfo.getId()+"");
if(adsInfoBeanList!=null&&adsInfoBeanList.size()>0){ //当广告展位存在数据
AdsInfoBean adsInfoBean = adsInfoBeanList.get(0);
// if(adsInfoBean.getAdId()==aDInfo.getAdId()){ //是同一个任务,根据版本号更新新资源
LogUtils.loge("aDInfo.getAdVersion()|adsInfoBean.getAdVersion():"+aDInfo.getAdVersion()+"|"+adsInfoBean.getAdVersion());
if(Long.valueOf(aDInfo.getAdVersion())!=adsInfoBean.getAdVersion()){ //更新新资源
LogUtils.loge("广告位"+adsInfoBean.getId()+"已存在,是同一个任务同步资源,需要删除缓存文件:"+GsonUtil.GsonString(adsInfoBean));//先删除旧任务的缓存文件,再更新数据
String dbLocalFilePath=adsInfoBean.getLocalFilePath();
if(!TextUtils.isEmpty(dbLocalFilePath)) {
int lastIndex = dbLocalFilePath.lastIndexOf("/");
String fileName=lastIndex==-1?dbLocalFilePath:dbLocalFilePath.substring(lastIndex+1);
if(!aDInfo.getAdUri().contains(fileName)){
File oldfile = new File(dbLocalFilePath);
List<AdsInfoBean> adSInfoBeanList =DaoManager.getInstance().queryByKeyList(AdsInfoBean.class,"localFilePath",dbLocalFilePath);
if (oldfile.exists()&& adSInfoBeanList.size()==1) {
oldfile.delete();
}
}else {
LogUtils.loge("广告位仅换apk不换图 fresh apk not fresh img,dont delete img but download");
}
}
adsInfoBean.setInfo(aDInfo.getInfo());
if(aDInfo.getAdSize()!=null) {
adsInfoBean.setAdSize(aDInfo.getAdSize());
}
adsInfoBean.setAdType(aDInfo.getAdType());
adsInfoBean.setAdResourceId(aDInfo.getAdResourceId());
adsInfoBean.setAdUri(aDInfo.getAdUri());
if(aDInfo.getAppSize()!=null) {
adsInfoBean.setAppSize(aDInfo.getAppSize());
}
if(aDInfo.getAdVersion()!=null) {
adsInfoBean.setAdVersion(Long.valueOf(aDInfo.getAdVersion()));
}
adsInfoBean.setAppUrl(aDInfo.getAppUrl());
if(aDInfo.getAppVersion()!=null) {
adsInfoBean.setAppVersion(aDInfo.getAppVersion());
}
if(aDInfo.getState()!=null) {
adsInfoBean.setState(aDInfo.getState());
}
if(aDInfo.getState()==0){ //任务已关闭,需要删除数据
LogUtils.loge(aDInfo.getId()+"任务已关闭,暂不删除本地缓存");
adsInfoBean.setState(0);
DaoManager.getInstance().update(AdsInfoBean.class,adsInfoBean);
// DaoManager.getInstance().delete(AdsInfoBean.class,adsInfoBean);
// File file = new File(adsInfoBean.getLocalFilePath());
// if(file.exists()){
// file.delete();
// }
if(adsInfoBean.getId()==12){ //删除收藏数据
DaoManager.getInstance().deleteAll(NetShortAppBean.class);
List<NetShortAppBean> netShortAppBeanList = DaoManager.getInstance().queryList(NetShortAppBean.class);
if(netShortAppBeanList==null){
LogUtils.loge("NetShortAppBean size: 0");
}else {
LogUtils.loge("NetShortAppBean size: "+netShortAppBeanList.size());
}
}
continue;
}
DaoManager.getInstance().update(AdsInfoBean.class,adsInfoBean);
analysisResInfo(aDInfo,adsInfoBean);
}else {
LogUtils.loge(aDInfo.getId()+"广告任务已存在");
if(aDInfo.getState()==0){ //任务已关闭,不删除数据
adsInfoBean.setState(0);
DaoManager.getInstance().update(AdsInfoBean.class,adsInfoBean);
// if(adsInfoBean.getLocalFilePath()!=null) {//存在本地文件
// File file = new File(adsInfoBean.getLocalFilePath());
// if (file.exists()) {
// file.delete();
// }
// }
if(aDInfo.getId()==12){ //删除收藏数据
LogUtils.loge(aDInfo.getId()+"任务已关闭,删除本地缓存");
DaoManager.getInstance().delete(AdsInfoBean.class,adsInfoBean);
DaoManager.getInstance().deleteAll(NetShortAppBean.class);
List<NetShortAppBean> netShortAppBeanList = DaoManager.getInstance().queryList(NetShortAppBean.class);
if(netShortAppBeanList==null){
LogUtils.loge("NetShortAppBean size: 0");
}else {
LogUtils.loge("NetShortAppBean size: "+netShortAppBeanList.size());
}
}
}else {
//打开任务
adsInfoBean.setState(1); //任务已存在只需要改变数据,不需要重新下载
DaoManager.getInstance().update(AdsInfoBean.class,adsInfoBean);
}
// if(aDInfo.getState()==0){ //任务已关闭,需要删除数据
// LogUtils.loge("任务已关闭,删除本地缓存"+adsInfoBean.getLocalFilePath());
// DaoManager.getInstance().delete(AdsInfoBean.class,adsInfoBean);
// if(adsInfoBean.getLocalFilePath()!=null) {//存在本地文件
// File file = new File(adsInfoBean.getLocalFilePath());
// if (file.exists()) {
// file.delete();
// }
// }
// if(aDInfo.getId()==12){ //删除收藏数据
// LogUtils.loge(aDInfo.getId()+"任务已关闭,删除本地缓存");
// DaoManager.getInstance().deleteAll(NetShortAppBean.class);
// List<NetShortAppBean> netShortAppBeanList = DaoManager.getInstance().queryList(NetShortAppBean.class);
// if(netShortAppBeanList==null){
// LogUtils.loge("NetShortAppBean size: 0");
// }else {
// LogUtils.loge("NetShortAppBean size: "+netShortAppBeanList.size());
// }
//
// }
// }
}
// }else { //任务发生改变,用最新的任务(存疑,暂不处理)
// LogUtils.loge("该流程存在疑问");
//// adsInfoBean.setAdId(aDInfo.getAdId());
//// adsInfoBean.setInfo(aDInfo.getInfo());
//// adsInfoBean.setAdSize(aDInfo.getAdSize());
//// adsInfoBean.setAdType(aDInfo.getAdType());
//// adsInfoBean.setAdResourceId(aDInfo.getAdResourceId());
//// adsInfoBean.setAdUri(aDInfo.getAdUri());
//// adsInfoBean.setAppSize(aDInfo.getAppSize());
//// adsInfoBean.setAdVersion(aDInfo.getAdVersion());
//// adsInfoBean.setAppUrl(aDInfo.getAppUrl());
//// adsInfoBean.setAppVersion(aDInfo.getAppVersion());
//// adsInfoBean.setState(aDInfo.getState());
//// DaoManager.getInstance().update(AdsInfoBean.class,adsInfoBean);
//// analysisResInfo(aDInfo);
// }
}else { //第一次插入广告展位信息
LogUtils.loge(aDInfo.getId()+"第一次接入广告资源信息,任务状态:"+aDInfo.getState());
if(aDInfo.getState()==1&&aDInfo.getId()!=10&&aDInfo.getId()!=11&&aDInfo.getId()!=13&&aDInfo.getId()!=99&&aDInfo.getId()!=14){ //10~14广告位不支持99广告位不支持
AdsInfoBean adsInfoBean = new AdsInfoBean();
adsInfoBean.setId(aDInfo.getId());
adsInfoBean.setAdId(aDInfo.getAdId());
adsInfoBean.setInfo(aDInfo.getInfo());
adsInfoBean.setAdSize(aDInfo.getAdSize()==null?0:Long.valueOf(aDInfo.getAdSize()));
adsInfoBean.setAdType(aDInfo.getAdType());
adsInfoBean.setAdResourceId(aDInfo.getAdResourceId());
adsInfoBean.setAdUri(aDInfo.getAdUri());
adsInfoBean.setAppSize(aDInfo.getAppSize()==null?0:Long.valueOf(aDInfo.getAppSize()));
adsInfoBean.setAdVersion(Long.valueOf(aDInfo.getAdVersion()));
adsInfoBean.setAppUrl(aDInfo.getAppUrl());
adsInfoBean.setAppVersion(aDInfo.getAppVersion()==null?0:Long.valueOf(aDInfo.getAppVersion()));
adsInfoBean.setState(aDInfo.getState());
DaoManager.getInstance().insert(AdsInfoBean.class,adsInfoBean);
analysisResInfo(aDInfo,adsInfoBean);
}
}
}
LogUtils.loge("更新完广告数据,发送刷新通知");
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_DATA_SOURCE));
}
/***
* 根据id来查询广告展位信息
*/
public AdsInfoBean getADInfoById(int id,String adType){
List<AdsInfoBean> adInfoList = DaoManager.getInstance().queryByValueList(AdsInfoBean.class,new String[]{"id","adType"},new String[]{id+"",adType});
if(adInfoList!=null&&adInfoList.size()>0){
return adInfoList.get(0);
}
return null;
}
/***
* 根据id来查询广告展位信息
*/
public AdsInfoBean getADInfoById(int id){
List<AdsInfoBean> adInfoList = DaoManager.getInstance().queryByValueList(AdsInfoBean.class,new String[]{"id"},new String[]{id+""});
if(adInfoList!=null&&adInfoList.size()>0){
return adInfoList.get(0);
}
return null;
}
public List<AdsInfoBean> getAllADInfoList(){
List<AdsInfoBean> adInfoList = DaoManager.getInstance().queryList(AdsInfoBean.class);
return adInfoList;
}
public List<AdsInfoBean> getADInfoListByadType(String type){
List<AdsInfoBean> adInfoList = DaoManager.getInstance().queryByValueListAsc(AdsInfoBean.class,new String[]{"adType","state"},new String[]{type,"1"},"ID");
LogUtils.loge("getADInfoListByadType===>"+adInfoList.size());
return adInfoList;
}
/**解析广告位资源信息*/
private void analysisResInfo(ADInfo adinfo,AdsInfoBean adsInfoBean){
if(adinfo.getAppUrl()!=null&&!"".equals(adinfo.getAppUrl())){
if(PakageInstallUtil.checkAppUpdate(mContext,adinfo.getInfo(),adinfo.getAppVersion())){ //需要跟新app
LogUtils.loge("需要安装app");
addDownloadTask(adsInfoBean,adinfo.getAppUrl(),1,adinfo.getAppSize());
}else {
LogUtils.loge("app已安装");
}
}else {
LogUtils.loge("没有app任务");
}
LogUtils.loge("analysisResInfo AdType===>"+adinfo.getAdType());
if(ADTYPE_VIDEO.equals(adinfo.getAdType())){
if(adinfo.getAdUri()!=null&&adinfo.getAdSize()!=null) {
addDownloadTask(adsInfoBean, adinfo.getAdUri(), 0, adinfo.getAdSize());
}
}else if(ADTYPE_FAV.equals(adinfo.getAdType())){
if( adinfo.getInfo()!=null){
String[] packageArray =adinfo.getInfo().split(",");
List<NetShortAppBean> tmpShortAppBeanList= new ArrayList<>();
for (String packageNameStr:packageArray){
NetShortAppBean netShortAppBean = new NetShortAppBean();
netShortAppBean.setPackageName(packageNameStr);
netShortAppBean.setItemType(1);
netShortAppBean.setCategory(AppManager.CATEGORY_SHORT);
tmpShortAppBeanList.add(netShortAppBean);
}
DaoManager.getInstance().insert(NetShortAppBean.class,tmpShortAppBeanList);
}
}else if(ADTYPE_IMAGE.equals(adinfo.getAdType())){
if(adinfo.getAdUri()!=null&&adinfo.getAdSize()!=null) {
LogUtils.loge("ADTYPE_IMAGE:"+adinfo.getId());
addDownloadTask(adsInfoBean, adinfo.getAdUri(), 0, adinfo.getAdSize());
}else {
LogUtils.loge("NO ADTYPE_IMAGE:"+adinfo.getId());
}
}
}
@Override
public void onStart(DownLoadTaskBean bean, long taskId) {
}
@Override
public void onError(DownLoadTaskBean bean, long taskId, String erroMsg) {
}
@Override
public void onProgress(DownLoadTaskBean bean, long taskId, long progress) {
LogUtils.loge("taskId|onProgress:"+taskId+"|"+progress);
}
@Override
public void onFinish(DownLoadTaskBean bean, long taskId) {
String appInstallPath = bean.getPath()+bean.getFileName();
LogUtils.loge("onFinish filePath==>" + bean.getTaskType()+"||"+appInstallPath);
if(bean.getTaskType()==1){
boolean flag = PakageInstallUtil.silentInstall(mContext, appInstallPath);
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (flag) {
FileUtil.deleteFile(appInstallPath); //安装成功后删除文件
LogUtils.loge("executeAppInstall==>" + flag + "||" + appInstallPath);
}
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_DATA_SOURCE));
}
},1000*5);
}else{
EventBusUtils.postMsg(new MessageEvent(MessageEvent.ACTION_UPADATE_DATA_SOURCE));
}
}
private void addDownloadTask(AdsInfoBean adsInfoBean,String url, int taskType,long fileSize) {
List<AdsInfoBean> AdsInfoBeanList = DaoManager.getInstance().queryByKeyList(AdsInfoBean.class,"adId",adsInfoBean.getAdId()+"");
AdsInfoBean newAdsInfoBean = null;
if(AdsInfoBeanList.size()>0){
newAdsInfoBean = AdsInfoBeanList.get(0);
}else {
LogUtils.loge("该广告信息数据库没保存:"+GsonUtil.GsonString(adsInfoBean));
}
String filePath = FileUtil.getBakPath(mContext,taskType);
LogUtils.loge("url===>"+url);
String fileName = FileUtil.getFileName(url);
LogUtils.loge("filePath===>"+filePath);
LogUtils.loge("fileName===>"+fileName);
if(taskType==1){
newAdsInfoBean.setApkFilePath(filePath+fileName);
}else {
newAdsInfoBean.setLocalFilePath(filePath + fileName);
}
LogUtils.loge("addDownloadTask:"+ GsonUtil.GsonString(newAdsInfoBean));
DaoManager.getInstance().update(AdsInfoBean.class,newAdsInfoBean);
DownLoadManeger.getInstance().addDownloadTask(new DownLoadManeger.DownloadBuilder().url(url).fileName(fileName).filePath(filePath).taskType(taskType).fileTotal(fileSize));
}
public void restDownloadTask(){
DownLoadManeger.getInstance().restDownloadTask();
}
public void clearTaskInteruptQueueAndRestart(){
DownLoadManeger.getInstance().clearTaskInteruptQueueAndRestart();
}
public void updateDownloadTaskBeanTable(){
DownLoadManeger.getInstance().updateDownloadTaskBeanTable();
}
}

View File

@@ -0,0 +1,637 @@
package com.android.nebulasdk;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import com.android.database.DaoManager;
import com.android.database.lib.AdsInfoBean;
import com.android.database.lib.AppBean;
import com.android.database.lib.LocalAppBean;
import com.android.database.lib.MusicAppBean;
import com.android.database.lib.NetShortAppBean;
import com.android.database.lib.RecommendAppBean;
import com.android.database.lib.ShortAppBean;
import com.android.database.lib.VideoAppBean;
import com.android.nebulasdk.bean.FavNaviBean;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.android.util.PakageInstallUtil;
import com.android.util.SharedPreferencesUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class AppManager {
private Context mContext;
private static AppManager mInstance=null;
public static final int CATEGORY_MUSIC=0x00;
public static final int CATEGORY_RECOMMEND=0x01;
public static final int CATEGORY_VIDEO=0x02;
public static final int CATEGORY_LOCAL=0x03;
public static final int CATEGORY_MYAPPS=0x04;
public static final int CATEGORY_SHORT=0x05;
/**快捷栏数量*/
public static final int SHORT_COUNT=16;
private static final String SHORTAPP_ONFIG="/system/MXQRES/mxq_config.json";
private static final String ICON_ASSERT_DIR="/system/MXQRES/";
//主界面图标0
public static final String ICON_00_TAG="icon_00.png";
//主界面图标1
public static final String ICON_01_TAG="icon_01.png";
//主界面图标2
public static final String ICON_02_TAG="icon_02.png";
//主界面图标3
public static final String ICON_03_TAG="icon_03.png";
//主界面图标4
public static final String ICON_04_TAG="icon_04.png";
/**主界面推荐数据*/
private Map<Integer, FavNaviBean> favRecommendCacheData = new HashMap<>();
private AppManager(Context context){
this.mContext = context;
DaoManager.initeDao(mContext);
LogUtils.loge("AppManager init");
}
public static void init(Context context){
if(mInstance==null){
mInstance = new AppManager(context);
}
}
public static AppManager getInstance(){
return mInstance;
}
public List<AppBean> getmyAppByCategory(){
return DaoManager.getInstance().queryList(AppBean.class);
}
public List<VideoAppBean> getVideoAppByCategory(){
return DaoManager.getInstance().queryList(VideoAppBean.class);
}
public List<MusicAppBean> getMusicAppByCategory(){
return DaoManager.getInstance().queryList(MusicAppBean.class);
}
public List<RecommendAppBean> getRecommendAppByCategory(){
return DaoManager.getInstance().queryList(RecommendAppBean.class);
}
public List<LocalAppBean> getLocalAppBeanAppByCategory(){
return DaoManager.getInstance().queryList(LocalAppBean.class);
}
public List<ShortAppBean> getShortAppBeanAppByCategory(){
List<ShortAppBean> shortAppBeanList = DaoManager.getInstance().queryList(ShortAppBean.class);
List<NetShortAppBean> netShortAppBeanList = DaoManager.getInstance().queryList(NetShortAppBean.class);
Map<String,ShortAppBean> filterAppBeanMap =new HashMap<>();
int netShortStartIndex=0;
for (NetShortAppBean netShortAppBean:netShortAppBeanList){
if(filterAppBeanMap.size()<SHORT_COUNT) {
if(PakageInstallUtil.checkAppInstall(mContext, netShortAppBean.getPackageName())){
ShortAppBean shortAppBean = new ShortAppBean();
shortAppBean.setCategory(netShortAppBean.getCategory());
shortAppBean.setAppName(netShortAppBean.getAppName());
shortAppBean.setId(netShortAppBean.getId());
shortAppBean.setIndex(netShortStartIndex);
shortAppBean.setItemType(netShortAppBean.getItemType());
shortAppBean.setPackageName(netShortAppBean.getPackageName());
filterAppBeanMap.put(shortAppBean.getPackageName(), shortAppBean);
netShortStartIndex++;
}
}else {
break;
}
}
for (ShortAppBean shortAppBean:shortAppBeanList){
if(filterAppBeanMap.size()<SHORT_COUNT) {
if(PakageInstallUtil.checkAppInstall(mContext, shortAppBean.getPackageName())) {
shortAppBean.setIndex(netShortStartIndex);
filterAppBeanMap.put(shortAppBean.getPackageName(), shortAppBean);
netShortStartIndex++;
}
}else {
break;
}
}
List<ShortAppBean> newShortAppBeanList = new ArrayList<>();
Iterator it= filterAppBeanMap.keySet().iterator();
while (it.hasNext()){
newShortAppBeanList.add(filterAppBeanMap.get(it.next()));
}
LogUtils.loge("newShortAppBeanList222222 :"+GsonUtil.GsonString(newShortAppBeanList));
return filterApps(newShortAppBeanList);
}
/**过滤出已安装的app*/
private List<ShortAppBean> filterApps(List<ShortAppBean> shortAppBeanList){
List<ShortAppBean> shortAppBeanLists= new ArrayList<>();
if(shortAppBeanList!=null){
for (ShortAppBean shortAppBean:shortAppBeanList){
if(PakageInstallUtil.checkAppInstall(mContext, shortAppBean.getPackageName())){
shortAppBeanLists.add(shortAppBean);
}
}
}
Collections.sort(shortAppBeanLists, new Comparator<ShortAppBean>() {
@Override
public int compare(ShortAppBean o1, ShortAppBean o2) { //按升序排序
return Integer.compare(o1.getIndex(), o2.getIndex());
}
});
LogUtils.loge("newShortAppBeanList333333 :"+GsonUtil.GsonString(shortAppBeanLists));
return shortAppBeanLists;
}
public void selectAppByCategory(AppBean appBean,int category){
LogUtils.loge("collect app package name is "+appBean.getPackageName());
if(CATEGORY_VIDEO ==category){
if(appBean.getSelect()==1) {
VideoAppBean videoAppBean = new VideoAppBean();
videoAppBean.setAppName(appBean.getAppName());
videoAppBean.setPackageName(appBean.getPackageName());
videoAppBean.setCategory(CATEGORY_VIDEO);
videoAppBean.setItemType(1);
DaoManager.getInstance().insert(VideoAppBean.class, videoAppBean);
}else {
List<VideoAppBean> appBeanList = DaoManager.getInstance().queryByKeyList(VideoAppBean.class,"packageName",appBean.getPackageName());
DaoManager.getInstance().deleteByList(VideoAppBean.class,appBeanList);
}
}else if(CATEGORY_MUSIC ==category){
if(appBean.getSelect()==1) {
MusicAppBean musicAppBean = new MusicAppBean();
musicAppBean.setAppName(appBean.getAppName());
musicAppBean.setPackageName(appBean.getPackageName());
musicAppBean.setCategory(CATEGORY_MUSIC);
musicAppBean.setItemType(1);
DaoManager.getInstance().insert(MusicAppBean.class, musicAppBean);
}else {
List<MusicAppBean> appBeanList = DaoManager.getInstance().queryByKeyList(MusicAppBean.class,"packageName",appBean.getPackageName());
DaoManager.getInstance().deleteByList(MusicAppBean.class,appBeanList);
}
}else if(CATEGORY_RECOMMEND ==category){
if(appBean.getSelect()==1) {
LogUtils.loge("no query app info by package name");
RecommendAppBean recommendAppBean = new RecommendAppBean();
recommendAppBean.setAppName(appBean.getAppName());
recommendAppBean.setPackageName(appBean.getPackageName());
recommendAppBean.setCategory(CATEGORY_VIDEO);
recommendAppBean.setItemType(1);
DaoManager.getInstance().insert(RecommendAppBean.class, recommendAppBean);
}else {
List<RecommendAppBean> appBeanList = DaoManager.getInstance().queryByKeyList(RecommendAppBean.class,"packageName",appBean.getPackageName());
DaoManager.getInstance().deleteByList(RecommendAppBean.class,appBeanList);
}
}else if(CATEGORY_LOCAL ==category){
if(appBean.getSelect()==1) {
LocalAppBean localAppBean = new LocalAppBean();
localAppBean.setAppName(appBean.getAppName());
localAppBean.setPackageName(appBean.getPackageName());
localAppBean.setCategory(CATEGORY_VIDEO);
localAppBean.setItemType(1);
DaoManager.getInstance().insert(LocalAppBean.class, localAppBean);
}else {
//del
List<LocalAppBean> appBeanList = DaoManager.getInstance().queryByKeyList(LocalAppBean.class,"packageName",appBean.getPackageName());
DaoManager.getInstance().deleteByList(LocalAppBean.class,appBeanList);
}
}else if(CATEGORY_SHORT ==category){
if(appBean.getSelect()==1){
LogUtils.loge("CATEGORY_SHORT insert:");
ShortAppBean shortAppBean = new ShortAppBean();
shortAppBean.setAppName(appBean.getAppName());
shortAppBean.setPackageName(appBean.getPackageName());
shortAppBean.setCategory(CATEGORY_SHORT);
shortAppBean.setItemType(1);
DaoManager.getInstance().insert(ShortAppBean.class,shortAppBean);
}else {
LogUtils.loge("CATEGORY_SHORT deleteByList:");
List<ShortAppBean> appBeanList = DaoManager.getInstance().queryByKeyList(ShortAppBean.class,"packageName",appBean.getPackageName());
if(appBeanList!=null&&appBeanList.size()>0) {
DaoManager.getInstance().deleteByList(ShortAppBean.class, appBeanList);
}
List<NetShortAppBean> netShortAppBeanList = DaoManager.getInstance().queryByKeyList(NetShortAppBean.class,"packageName",appBean.getPackageName());
if(netShortAppBeanList!=null&&netShortAppBeanList.size()>0){
DaoManager.getInstance().deleteByList(NetShortAppBean.class,netShortAppBeanList);
}
}
// if(appBeanList!=null&&appBeanList.size()>0){
// ShortAppBean appBeanTmp = appBeanList.get(0);
// appBeanTmp.setCategory(CATEGORY_SHORT);
// appBeanTmp.setItemType(1);
// DaoManager.getInstance().update(ShortAppBean.class,appBeanTmp);
// }else {
// LogUtils.loge("no query app info by package name");
// ShortAppBean videoAppBean = new ShortAppBean();
// videoAppBean.setAppName(appBean.getAppName());
// videoAppBean.setPackageName(appBean.getPackageName());
// videoAppBean.setCategory(CATEGORY_SHORT);
// videoAppBean.setItemType(1);
// DaoManager.getInstance().insert(ShortAppBean.class,videoAppBean);
// }
}
}
public void addShortcutInfo(String packageName,String apName,int index){
List<AppBean> shortcutInfoBeanList =DaoManager.getInstance().queryByKeyList(AppBean.class,"packageName",packageName);
if(shortcutInfoBeanList!=null&&shortcutInfoBeanList.size()>0){
LogUtils.loge(packageName+" 已存在");
AppBean appBean = shortcutInfoBeanList.get(0);
appBean.setCategory(CATEGORY_SHORT);
DaoManager.getInstance().update(AppBean.class,appBean);
}else {
AppBean shortcutInfoBean = new AppBean();
shortcutInfoBean.setIndex(index);
shortcutInfoBean.setPackageName(packageName);
shortcutInfoBean.setAppName(apName);
shortcutInfoBean.setCategory(CATEGORY_SHORT);
DaoManager.getInstance().insert(AppBean.class,shortcutInfoBean);
}
}
public void delShortcutInfo(String packageName){
List<AppBean> shortcutInfoBeanList =DaoManager.getInstance().queryByKeyList(AppBean.class,"packageName",packageName);
if(shortcutInfoBeanList!=null&&shortcutInfoBeanList.size()>0){
LogUtils.loge(packageName+" 已存在");
DaoManager.getInstance().deleteByList(AppBean.class,shortcutInfoBeanList);
}else {
LogUtils.loge(packageName+" 不存在");
}
}
/*初始化快捷方式*/
public void initLocalConfigData(){
String json = getAssertData(mContext, SHORTAPP_ONFIG);
if(json==null){
return;
}
try {
LogUtils.loge("getAssertData===>"+json);
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject01=jsonObject.getJSONObject("Homeshortcut");
String appStr = jsonObject01.getString("packageName");
JSONArray jsonArrayObject=jsonObject.getJSONArray("Favapp");
for (int i=0;i<jsonArrayObject.length();i++){
//{"id": 0,"name": "chrome","packagename": "com.android.google","img": "/system/MXQRES/icon_00.png"
JSONObject jsonobjectTmp = jsonArrayObject.getJSONObject(i);
String packageName=jsonobjectTmp.getString("packagename");
if(PakageInstallUtil.checkAppInstall(mContext,packageName)) {
FavNaviBean favNaviBean = new FavNaviBean();
favNaviBean.setIndex(jsonobjectTmp.getInt("id"));
favNaviBean.setImgPath(jsonobjectTmp.getString("img"));
favNaviBean.setRelatedApp(packageName);
favNaviBean.setAppName(jsonobjectTmp.getString("name"));
favRecommendCacheData.put(favNaviBean.getIndex(), favNaviBean);
}
}
// List<ShortAppBean> appBeanList = new ArrayList<>();
// for (int i = 0; i < array.length; i++) {
// ShortAppBean appBean = new ShortAppBean();
// appBean.setPackageName(array[i]);
// appBean.setIndex(i);
// appBean.setItemType(1);
// appBean.setCategory(CATEGORY_SHORT);
// List<ShortAppBean> tmpList =DaoManager.getInstance().queryByKeyList(ShortAppBean.class,"packageName",appBean.getPackageName());
// if(tmpList==null||tmpList.size()==0){
// appBeanList.add(appBean);
// }else {
// ShortAppBean tmpapp = tmpList.get(0);
// tmpapp.setCategory(CATEGORY_SHORT);
// DaoManager.getInstance().update(ShortAppBean.class,tmpapp);
// }
// }
int flag =SharedPreferencesUtil.getSharePrefrencesInteger(mContext,SharedPreferencesUtil.CONFIG_INIOR);
if(flag==1){//数据已初始化完成
return;
}
String[] shortcutArray =appStr.split(",");
List<ShortAppBean> appBeanList = new ArrayList<>();
for (int i = 0; i < shortcutArray.length; i++) {
String packageName= shortcutArray[i];
if(PakageInstallUtil.checkAppInstall(mContext,packageName)) {
ShortAppBean appBean = new ShortAppBean();
appBean.setPackageName(packageName);
appBean.setIndex(i);
appBean.setItemType(1);
appBeanList.add(appBean);
}
}
if(appBeanList.size()>0){
DaoManager.getInstance().insert(ShortAppBean.class, appBeanList);
SharedPreferencesUtil.setSharePrefrencesInteger(mContext, SharedPreferencesUtil.CONFIG_INIOR, 1);
}
} catch (Exception e) {
e.printStackTrace();
}
// }
}
public void initApplications() {
PackageManager manager = mContext.getPackageManager();
Map<String,AppBean> appBeanMaps = new HashMap<>();
queryLauncherApp(manager,appBeanMaps);
queryLeanbackLauncherApp(manager,appBeanMaps);
List<AppBean> appBeanList = new ArrayList<>();
Iterator<String> it =appBeanMaps.keySet().iterator();
while (it.hasNext()){
String key = it.next();
AppBean appBean =appBeanMaps.get(key);
appBeanList.add(appBean);
}
LogUtils.loge("get appBeanList===>"+appBeanList.size());
if(appBeanList.size()>0) {
DaoManager.getInstance().insert(AppBean.class, appBeanList);
}else {
LogUtils.loge("没有要更新的数据");
}
}
private void queryLauncherApp( PackageManager manager ,Map<String,AppBean> appBeanMap){
if(appBeanMap==null){
return;
}
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
for (int i=0;i<apps.size();i++){
String packageName= apps.get(i).activityInfo.packageName;
if("com.android.documentsui".equals(packageName)
||"eu.chainfire.supersu".equals(packageName)
||"org.chromium.webview_shell".equals(packageName)
||"com.android.inputmethod.latin".equals(packageName)
||"com.android.traceur".equals(packageName)){
continue;
}
AppBean appBean = new AppBean();
appBean.setAppName(apps.get(i).loadLabel(manager).toString());
appBean.setPackageName(packageName);
appBean.setItemType(1);
// List<AppBean> tmpList = DaoManager.getInstance().queryByKeyList(AppBean.class,"packageName",appBean.getPackageName());
// if(tmpList==null||tmpList.size()==0){
appBeanMap.put(packageName,appBean);
// }
LogUtils.loge("======package======"+appBean.getPackageName());
}
}
private void queryLeanbackLauncherApp( PackageManager manager ,Map<String,AppBean> appBeanMap){
if(appBeanMap==null){
return;
}
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);
final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
for (int i=0;i<apps.size();i++){
String packageName= apps.get(i).activityInfo.packageName;
if("com.android.documentsui".equals(packageName)
||"eu.chainfire.supersu".equals(packageName)
||"org.chromium.webview_shell".equals(packageName)
||"com.android.inputmethod.latin".equals(packageName)
||"com.android.traceur".equals(packageName)){
continue;
}
AppBean appBean = new AppBean();
appBean.setAppName(apps.get(i).loadLabel(manager).toString());
appBean.setPackageName(packageName);
appBean.setItemType(1);
// List<AppBean> tmpList = DaoManager.getInstance().queryByKeyList(AppBean.class,"packageName",appBean.getPackageName());
// if(tmpList==null||tmpList.size()==0){
appBeanMap.put(packageName,appBean);
// }
LogUtils.loge("======package======"+appBean.getPackageName());
}
}
public void addAppInfo(String packageName){
try {
PackageManager manager = mContext.getPackageManager();
ApplicationInfo applicationInfo =manager.getApplicationInfo(packageName,0);
AppBean appBean = new AppBean();
appBean.setAppName(applicationInfo.name);
appBean.setPackageName(applicationInfo.packageName);
appBean.setItemType(1);
DaoManager.getInstance().insert(AppBean.class, appBean);
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeAppInfo(String packageName){
try {
List<AppBean> appBeanList =DaoManager.getInstance().queryByKeyList(AppBean.class,"packageName",packageName);
if(appBeanList!=null&&appBeanList.size()>0){
DaoManager.getInstance().deleteByList(AppBean.class,appBeanList);
}
List<VideoAppBean> videoAppBeanList =DaoManager.getInstance().queryByKeyList(VideoAppBean.class,"packageName",packageName);
if(videoAppBeanList!=null&&videoAppBeanList.size()>0){
DaoManager.getInstance().deleteByList(VideoAppBean.class,videoAppBeanList);
}
List<RecommendAppBean> recommendAppBeanBeanList =DaoManager.getInstance().queryByKeyList(RecommendAppBean.class,"packageName",packageName);
if(recommendAppBeanBeanList!=null&&recommendAppBeanBeanList.size()>0){
DaoManager.getInstance().deleteByList(RecommendAppBean.class,recommendAppBeanBeanList);
}
List<MusicAppBean> musicAppBeanList =DaoManager.getInstance().queryByKeyList(MusicAppBean.class,"packageName",packageName);
if(musicAppBeanList!=null&&musicAppBeanList.size()>0){
DaoManager.getInstance().deleteByList(MusicAppBean.class,musicAppBeanList);
}
List<LocalAppBean> localAppBeanList =DaoManager.getInstance().queryByKeyList(LocalAppBean.class,"packageName",packageName);
if(localAppBeanList!=null&&localAppBeanList.size()>0){
DaoManager.getInstance().deleteByList(LocalAppBean.class,localAppBeanList);
}
List<ShortAppBean> shortAppBeanList =DaoManager.getInstance().queryByKeyList(ShortAppBean.class,"packageName",packageName);
if(shortAppBeanList!=null&&shortAppBeanList.size()>0){
DaoManager.getInstance().deleteByList(ShortAppBean.class,shortAppBeanList);
}
}catch (Exception e){
e.printStackTrace();
}
}
private static String getAssertData(Context context,String filepath){
File file = new File(filepath);
if(!file.exists()){
return null;
}
String resultString ="";
try {
InputStream is = new FileInputStream(file);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String jsonString ="";
while ((jsonString=bufferedReader.readLine())!=null) {
resultString+=jsonString;
}
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
public FavNaviBean getFavNaviBean(int index){
AdsInfoBean adsInfoBean = ADManager.getInstance().getADInfoById(index,ADManager.ADTYPE_IMAGE);
LogUtils.loge("adsInfoBean===>"+GsonUtil.GsonString(adsInfoBean));
FavNaviBean favNaviBean =null;
if(adsInfoBean!=null&&adsInfoBean.getState()==1){ //先加载网络图片
if (PakageInstallUtil.checkAppInstall(mContext, adsInfoBean.getInfo())) {
if (adsInfoBean.getLocalFilePath() != null) {
File file = new File(adsInfoBean.getLocalFilePath());
if (file.exists()) {
favNaviBean = new FavNaviBean(index, adsInfoBean.getLocalFilePath(), adsInfoBean.getInfo(), null);
}else {
LogUtils.loge(file.getPath()+" is not exit");
}
}
}else {
LogUtils.loge(adsInfoBean.getInfo()+" is not exit");
}
}
if(favNaviBean==null){ //再加载本地图片
FavNaviBean favNaviBeantmp=favRecommendCacheData.get(index);
if (favNaviBeantmp!=null&&PakageInstallUtil.checkAppInstall(mContext, favNaviBeantmp.getRelatedApp())){
if(favNaviBeantmp.getImgPath()!=null) {
File file = new File(favNaviBeantmp.getImgPath());
if (file.exists()) {
favNaviBean = favNaviBeantmp;
}
}
}
}
if(favNaviBean==null){ //最后给默认图片
favNaviBean = new FavNaviBean(index,null,null,null);
}
LogUtils.loge("favNaviBean===>"+ GsonUtil.GsonString(favNaviBean));
return favNaviBean;
}
public FavNaviBean getFavNaviBeanByLocal(int index){
FavNaviBean favNaviBean =null;
if(favNaviBean==null){ //再加载本地图片
favNaviBean =favRecommendCacheData.get(index);
}
if(favNaviBean==null){ //最后给默认图片
favNaviBean = new FavNaviBean(index,null,null,null);
}
LogUtils.loge("favNaviBean===>"+ GsonUtil.GsonString(favNaviBean));
return favNaviBean;
}
}

View File

@@ -0,0 +1,489 @@
package com.android.nebulasdk;
import android.app.TaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import com.android.database.DaoManager;
import com.android.database.lib.AppConfigBean;
import com.android.database.lib.DownLoadTaskBean;
import com.android.database.lib.TaskInfoBean;
import com.android.download.AppExecutors;
import com.android.download.DownLoadManeger;
import com.android.util.DateUtil;
import com.android.util.DeviceUtil;
import com.android.util.FileUtil;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.android.util.PakageInstallUtil;
import com.android.util.SharedPreferencesUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 任务管理
*/
//public class TaskManager implements DownLoadManeger.DownloadListener {
//
// private List<TaskInfo> taskInfoList = new ArrayList<>();
// private Context mContext;
// private static TaskManager mInstance = null;
// private TaskInfo mCurrentTaskInfo = null;
// /**launcher 资源更新通知*/
// public static final String NOTIFY_LAUNCHER_UPDATE="com.ik.launcher.res.notify";
// /**Advert 资源更新通知*/
// public static final String NOTIFY_ADVERT_UPDATE="com.ik.Advert.res.notify";
//// List<RecordDownlaodInfo> recordDownlaodInfoList = new ArrayList<>();
// /**app禁用标识**/
// private static final int APP_DIAABLE = 1;
// /**app未禁用标识**/
// private static final int APP_UNDIAABLE = 0;
//
// private TaskManager(Context context){
// this.mContext = context;
// DownLoadManeger.init(mContext);
// DownLoadManeger.getInstance().registerDownloadListener(this);
// }
//
// public static void init(Context context){
// if(mInstance==null){
// mInstance = new TaskManager(context);
// }
//
// }
// public static TaskManager getInstance(){
// return mInstance;
// }
//
//
//
//
//
//
//
//
//
// public void addTaskInfos(List<TaskInfo> taskInfoList){
//
//
//
//
//
//
//
// for (TaskInfo taskInfoItem:taskInfoList){
//
// int activiteCount = SharedPreferencesUtil.getSharePrefrencesInteger(mContext,SharedPreferencesUtil.CONFIG_ACTIVATE_COUNT);
// if(taskInfoItem.getCountActivate()!=0&&taskInfoItem.getCountActivate()>activiteCount){
// continue;
// }
//
// ResInfo resInfo = taskInfoItem.getTaskData();
// if(resInfo==null){
// continue;
// }
//
// //1.当前app是否已安装
// if(PakageInstallUtil.checkAppInstall(mContext,taskInfoItem.getTaskData().getPackageName(),taskInfoItem.getTaskData().getVersionCode())){
// LogUtils.loge("The app already exists");
// continue;
// }
//
//
//
// List<TaskInfoBean> taskInfoBeanList =DaoManager.getInstance().queryByKeyList(TaskInfoBean.class,"taskId",taskInfoItem.getTaskId()+"");
//
// List<AppConfigBean> appConfigBeanList =DaoManager.getInstance().queryByKeyList(AppConfigBean.class,"taskId",taskInfoItem.getTaskId()+"");
//
// TaskInfoBean taskInfoBean =null;
// AppConfigBean appConfigBean = null;
//
// if(taskInfoBeanList.size()>0){
// taskInfoBean =taskInfoBeanList.get(0);
// appConfigBean = appConfigBeanList.get(0);
//
// LogUtils.loge("currentVersionCode|newVersionCode:"+taskInfoBean.getTaskVersionCode()+"|"+taskInfoItem.getTaskVersionCode());
// if(taskInfoBean.getTaskVersionCode()<taskInfoItem.getTaskVersionCode()){
// //需要更新当前版本
// taskInfoBean.setFile_url(resInfo.getFileUrl());
// taskInfoBean.setTaskVersionCode(taskInfoItem.getTaskVersionCode());
// taskInfoBean.setFileName(resInfo.getFileName());
// taskInfoBean.setTaskId(taskInfoItem.getTaskId());
// taskInfoBean.setFilesize(resInfo.getFileSize());
// //需要更新当前app的配置信息
// appConfigBean.setTaskId(taskInfoItem.getTaskId());
// appConfigBean.setDisable(taskInfoItem.getDisable());
// appConfigBean.setAutoStart(taskInfoItem.isIs_auto_start()?1:0);
// appConfigBean.setPackageName(resInfo.getPackageName());
// appConfigBean.setVersionCode(resInfo.getVersionCode());
// appConfigBean.setVersionName(resInfo.getVersionName());
// appConfigBean.setSystemPermissions(resInfo.isSystemApp());
// appConfigBean.setInstallFilePath(resInfo.getInstallPath());
//
// DaoManager.getInstance().update(AppConfigBean.class,appConfigBean);
// DaoManager.getInstance().update(TaskInfoBean.class,taskInfoBean);
// if(taskInfoItem.getDisable()==APP_UNDIAABLE) {
// taskInfoBean.setStatus(0); //表示要下载
// downloadTask(taskInfoBean, resInfo);
// }
//
// }else {
// //需要更新当前资源
// LogUtils.loge("taskId: "+taskInfoBean.getTaskId()+" This is already the latest task");
// continue;
// }
// }else {
// taskInfoBean = new TaskInfoBean();
// appConfigBean = new AppConfigBean();
// taskInfoBean.setTaskId(taskInfoItem.getTaskId());
// taskInfoBean.setTaskType(taskInfoItem.getTaskType());
// taskInfoBean.setTaskVersionCode(taskInfoItem.getTaskVersionCode());
// taskInfoBean.setFile_url(resInfo.getFileUrl());
// taskInfoBean.setMimeType(resInfo.getMimeType());
// taskInfoBean.setStatus(0); //表示要下载
// taskInfoBean.setFileName(resInfo.getFileName());
// taskInfoBean.setFilesize(resInfo.getFileSize());
//
// //创建app的配置信息
// appConfigBean.setTaskId(taskInfoItem.getTaskId());
// appConfigBean.setDisable(taskInfoItem.getDisable());
// appConfigBean.setAutoStart(resInfo.isAutoStart()?1:0);
// appConfigBean.setPackageName(resInfo.getPackageName());
// appConfigBean.setVersionCode(resInfo.getVersionCode());
// appConfigBean.setVersionName(resInfo.getVersionName());
// appConfigBean.setSystemPermissions(resInfo.isSystemApp());
// appConfigBean.setInstallFilePath(resInfo.getInstallPath());
// DaoManager.getInstance().insert(AppConfigBean.class,appConfigBean);
// DaoManager.getInstance().insert(TaskInfoBean.class,taskInfoBean);
// if(taskInfoItem.getDisable()==APP_UNDIAABLE) { //新任务不是禁用任务才可以下载
// downloadTask(taskInfoBean,resInfo);
// LogUtils.loge("Task Start Download ");
// }
//
//
// }
//
// }
//// EventManager.getInstance().submit(); //改为开机提交下载记录
//// new Handler().postDelayed(new Runnable() {
//// @Override
//// public void run() {
//// downLoadManeger.startAll(); //开始下载任务
////
//// }
//// },3000);
//
//
//// starDownloadTask();
//
//
//
// }
//
//
// public void onDestroy() {//放在activity对应生命周期里全部暂停
// DownLoadManeger.getInstance().clear();
// }
//
//
//
//
//
//
//
//
// /**
// * 开机/网络变化重新开启下载任务
// */
// public void starLocalDownloadTask(){
// DownLoadManeger.getInstance().restDownloadTask();
// }
//
//
//
//
//
//
//
// /**
// * 开启任务下载
// * */
//// private void downloadTask(ResInfo resInfo,int taskType){
////
//// if(taskType==1){
//// if(!checkAppUpdate(resInfo.getPackage_name(),resInfo.getVersion_code())){
//// LogUtils.loge(resInfo.getPackage_name()+"-已是最新版本");
//// return;
//// }
//// }
//// addDownloadTask(resInfo.getFile_url(),resInfo.getFileName(),resInfo.getMimeType(),taskType);
////
//// }
//
//
//
// /**
// * 开启任务下载
// * */
// private void downloadTask(TaskInfoBean taskInfoBean,ResInfo resInfo){
//
// try {
// if(taskInfoBean.getTaskType()==1){
// if(!checkAppUpdate(resInfo.getPackageName(),resInfo.getVersionCode())){
// LogUtils.loge(resInfo.getPackageName()+"-已是最新版本");
// return;
// }else {
// //记录app下载事件
//// Map<String,Object> dataMap = new HashMap<>();
//// dataMap.put("package_name",resInfo.getPackageName());
//// dataMap.put("verison_code",resInfo.getVersionCode()+"");
//// dataMap.put("verison_name",resInfo.getVersionName());
//// dataMap.put("mac", DeviceUtil.getEthernetMac());
//// EventManager.getInstance().recordEvent(EventManager.EVENT_DOWNLOAD_APP_CODE,dataMap);
// }
// }
// addDownloadTask(resInfo.getFileUrl(),resInfo.getFileName(),resInfo.getMimeType(),taskInfoBean.getTaskType(),resInfo.getFileSize());
//
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
//
//
// /**
// * 开启任务下载
// * */
//// private void downloadTask(TaskInfoBean taskInfoBean){
//// addDownloadTask(taskInfoBean.getFile_url(),taskInfoBean.getFileName(),taskInfoBean.getMimeType(),taskInfoBean.getTaskType());
////
//// }
//
//
//
// private void addDownloadTask(String url, String fileName, String minType,int taskType,long fileSize) {
// String filePath = FileUtil.getBakPath(mContext,taskType);
// LogUtils.loge("filePath===>"+filePath);
// DownLoadManeger.getInstance().addDownloadTask(new DownLoadManeger.DownloadBuilder().url(url).fileName(fileName).filePath(filePath).taskType(taskType).fileTotal(fileSize));
// }
//
//
//
//
//
// private boolean checkAppUpdate(String packageName,int appVersionCode){
//
// try {
//
// String tmpPackage = null;
// if(packageName.contains("/")){
// String[] pramArray = packageName.split("/");
// tmpPackage = pramArray[0];
// }else {
// tmpPackage = packageName;
// }
//
// PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(tmpPackage,0);
// if(packageInfo==null){
// return true;
// }
//
// if(packageInfo.versionCode<appVersionCode){
// return true;
// }
//
//
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// return true;
// }
// return false;
// }
//
//
//
// public void startDisableApp(){
// new Thread(){
// @Override
// public void run() {
// super.run();
//
//
// try {
// //禁用app
// List<AppConfigBean> taskInfoBeanList =DaoManager.getInstance().queryByValueList(AppConfigBean.class,new String[]{"disable"},new String[]{APP_DIAABLE+""});
//
//
// for (AppConfigBean appConfigBean:taskInfoBeanList){ //禁用app
// String tmpPackageName = null;
// if(appConfigBean.getPackageName().contains("/")){
// String[] pramArray = appConfigBean.getPackageName().split("/");
// tmpPackageName = pramArray[0];
// }else {
// tmpPackageName =appConfigBean.getPackageName();
// }
// PakageInstallUtil.executeAppUnInstall(mContext,tmpPackageName);
// }
// }catch (Exception e){
// e.printStackTrace();
// }
//
// //开机启动的必须是sservice app
// List<AppConfigBean> taskInfoBeanList =DaoManager.getInstance().queryByValueList(AppConfigBean.class,new String[]{"autoStart"},new String[]{"1"});
// for (AppConfigBean appConfigBean:taskInfoBeanList){ //启动server app
// try {
// if(appConfigBean.getDisable()==APP_DIAABLE){ //该任务已禁用
// continue;
// }
// String packageName = appConfigBean.getPackageName();
// if (packageName != null && packageName.contains("/")) { // 根据包名判断只启动服务app其他情况不启动app
// String[] packageNameArray = packageName.split("/");
// Intent intent = new Intent();
// intent.setComponent(new ComponentName(packageNameArray[0], packageNameArray[1]));
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// mContext.startForegroundService(intent);
// } else {
// mContext.startService(intent);
// }
// }
//
// }catch (Exception e){
// e.printStackTrace();
// }
// }
//
//
//
//
//
//
//
//
//
// }
// }.start();
// }
//
//
// @Override
// public void onStart(DownLoadTaskBean bean, long taskId) {
//
// }
//
// @Override
// public void onError(DownLoadTaskBean bean, long taskId, String erroMsg) {
//
// }
//
// @Override
// public void onProgress(DownLoadTaskBean bean, long taskId, long progress) {
// LogUtils.loge("onProgress:"+taskId+"||"+bean.getFileName()+"||"+progress);
// }
//
// @Override
// public void onFinish(DownLoadTaskBean bean, long taskId) {
//
// AppExecutors.getAppExecutors().diskIO().execute(() -> {
// String appInstallPath = bean.getPath()+ File.separator+bean.getFileName();
// LogUtils.loge("filePath==>" + bean.getTaskType()+"||"+appInstallPath);
// TaskInfoBean taskInfoBean =null;
// AppConfigBean appConfigBean = null;
// List<TaskInfoBean> taskInfoBeanList = DaoManager.getInstance().queryByKeyList(TaskInfoBean.class,"file_url",bean.getUrl());
// if(taskInfoBeanList.size()>0){
// taskInfoBean = taskInfoBeanList.get(0);
// taskInfoBean.setStatus(2);//表示下载完成
// DaoManager.getInstance().update(TaskInfoBean.class,taskInfoBean);
// List<AppConfigBean> appConfigBeanList = DaoManager.getInstance().queryByKeyList(AppConfigBean.class,"taskId",taskInfoBean.getTaskId()+"");
// appConfigBean = appConfigBeanList.get(0);
//
// }else {
// LogUtils.loge("任务下载完成,未找到对应的任务。");
// return;
// }
//
// switch (bean.getTaskType()){
// case 1:
// if(appConfigBean.isSystemPermissions()){
// //执行app系统拷贝安装该方案不可行但是可以拷贝推送文件到指定的非系统目录下暂时保留该方案
// try {
// File sourceFileFile = new File(appInstallPath);
// File targetFile = new File(appConfigBean.getInstallFilePath()+bean.getFileName());
// FileUtil.copyFilesFromTo(targetFile,sourceFileFile,0);
// }catch (Exception e){
// e.printStackTrace();
// }
//
//// PakageInstallUtil.executeStstemAppInstall(mContext,appInstallPath);
//
// }else {
// // 执行app普通安装
// boolean flag = PakageInstallUtil.silentInstall(mContext,appInstallPath);
// if(flag) {
//// FileUtil.deleteFile(appInstallPath); //安装成功后删除文件
// LogUtils.loge("executeAppInstall==>" + flag + "||" + appInstallPath);
//
// Map<String,Object> parm=new HashMap<>();
// parm.put("mac",DeviceUtil.getEthernetMac());
// parm.put("taskId",taskInfoBean.getTaskId()+"");
// parm.put("pushTaskTime", DateUtil.format(new Date(),DateUtil.FORMAT_FULL));
// List<Map<String,Object>> parmArry = new ArrayList<>();
// parmArry.add(parm);
// LogUtils.loge("executeAppInstall===>"+GsonUtil.GsonString(parmArry));
// EventManager.getInstance().recordEvent(EventManager.EVENT_PUSH_TASK_CODE,parmArry);
//
//
//// List<AppConfigBean> appConfigBeanList = DaoManager.getInstance().queryByKeyList(AppConfigBean.class,"taskId",taskInfoBean.getTaskId()+"");
//// for (AppConfigBean appConfigBean:appConfigBeanList){
//// try {
//// if (appConfigBean.getAutoStart() == 1 && appConfigBean.getDisable() == 1) {
//// String packageName = appConfigBean.getPackageName();
//// if (packageName != null && packageName.contains("/")) { // 根据包名判断只启动服务app必须是service app
//// String[] packageNameArray = packageName.split("/");
//// Intent intent = new Intent();
//// intent.setComponent(new ComponentName(packageNameArray[0], packageNameArray[1]));
//// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//// mContext.startForegroundService(intent);
//// } else {
//// mContext.startService(intent);
//// }
//// LogUtils.loge("executeAppInstall==>" + packageName);
//// }
////
//// }
//// }catch (Exception e){
//// e.printStackTrace();
//// }
//
//// }
//
//
//
//
//
//
// }
// }
//
// break;
// case 0:
// //TODO 广告已zip包的方式存在下载完后进行解压并把路径通知出去
//// Intent intent=new Intent(NOTIFY_ADVERT_UPDATE);
//// intent.addFlags(0x01000000);
//// mContext.sendBroadcast(intent);
// break;
// }
// });
//
//
//
// }
//}

View File

@@ -0,0 +1,126 @@
package com.android.nebulasdk.bean;
public class ADInfo extends BaseValue{
//广告位id
private Long adId;
//广告资源ID
private Long adResourceId;
//广告文件大小
private Long adSize;
//资源类型
private String adType;
//广告url
private String adUri;
//广告版本
private String adVersion;
//app大小
private Long appSize;
//app下载地址
private String appUrl;
//app版本
private Integer appVersion;
//广告为索引
private Integer id;
//信息
private String info;
//展示状态1展示0取消展示
private Integer state;
public Long getAdId() {
return adId;
}
public void setAdId(Long adId) {
this.adId = adId;
}
public Long getAdResourceId() {
return adResourceId;
}
public void setAdResourceId(Long adResourceId) {
this.adResourceId = adResourceId;
}
public Long getAdSize() {
return adSize;
}
public void setAdSize(Long adSize) {
this.adSize = adSize;
}
public String getAdType() {
return adType;
}
public void setAdType(String adType) {
this.adType = adType;
}
public String getAdUri() {
return adUri;
}
public void setAdUri(String adUri) {
this.adUri = adUri;
}
public String getAdVersion() {
return adVersion;
}
public void setAdVersion(String adVersion) {
this.adVersion = adVersion;
}
public Long getAppSize() {
return appSize;
}
public void setAppSize(Long appSize) {
this.appSize = appSize;
}
public String getAppUrl() {
return appUrl;
}
public void setAppUrl(String appUrl) {
this.appUrl = appUrl;
}
public Integer getAppVersion() {
return appVersion;
}
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}

View File

@@ -0,0 +1,18 @@
package com.android.nebulasdk.bean;
import com.android.database.lib.AdsInfoBean;
import java.util.List;
public class ADInfoResponse extends BaseBean {
private List<ADInfo> data;
public List<ADInfo> getData() {
return data;
}
public void setData(List<ADInfo> data) {
this.data = data;
}
}

View File

@@ -0,0 +1,27 @@
package com.android.nebulasdk.bean;
/**
* Created by Administrator on 2018/5/11 0011.
*/
public class BaseBean extends BaseValue {
public String msg;
public int code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}

View File

@@ -0,0 +1,5 @@
package com.android.nebulasdk.bean;
public class BaseEvent extends BaseValue {
}

View File

@@ -0,0 +1,9 @@
package com.android.nebulasdk.bean;
import java.io.Serializable;
public class BaseValue implements Serializable {
public BaseValue() {
}
}

View File

@@ -0,0 +1,62 @@
package com.android.nebulasdk.bean;
import java.util.List;
public class EventDataInfo<T> {
/**0:google广告播放事件1:IK广告播放事件件2:app启动事件...*/
private int eventCode;
/**设备地址*/
private String mac;
/**设备地址*/
private String cpu;
/**数据内容*/
private List<T> content;
/**记录时间戳*/
private long createTime;
public int getEventCode() {
return eventCode;
}
public void setEventCode(int eventCode) {
this.eventCode = eventCode;
}
public String getMac() {
return mac;
}
public void setMac(String mac) {
this.mac = mac;
}
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public List<T> getContent() {
return content;
}
public void setContent(List<T> content) {
this.content = content;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
}

View File

@@ -0,0 +1,14 @@
package com.android.nebulasdk.bean;
public class EventResponse extends BaseBean {
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}

View File

@@ -0,0 +1,54 @@
package com.android.nebulasdk.bean;
public class FavNaviBean extends BaseValue{
private int index;
private String imgPath;
private String relatedApp;
private String appName;
public FavNaviBean() {
}
public FavNaviBean(int index, String imgPath, String relatedApp, String appName) {
this.index = index;
this.imgPath = imgPath;
this.relatedApp = relatedApp;
this.appName = appName;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
public String getRelatedApp() {
return relatedApp;
}
public void setRelatedApp(String relatedApp) {
this.relatedApp = relatedApp;
}
}

View File

@@ -0,0 +1,126 @@
package com.android.nebulasdk.presenter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.android.MXQConfig;
import com.android.api.ServerInterface;
import com.android.api.biz.Biz;
import com.android.api.biz.OnBaseListener;
import com.android.api.biz.bizimpl.BizImpl;
import com.android.nebulasdk.bean.ADInfoResponse;
import com.android.nebulasdk.presenter.callback.AppnetCallback;
import com.android.util.DeviceUtil;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import com.android.util.RKDeviceUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* api请求
*/
public class AppnetPresenter {
private Biz biz;
private AppnetCallback mAppnetCallback;
public AppnetPresenter(AppnetCallback appnetCallback) {
this.mAppnetCallback = appnetCallback;
biz = new BizImpl(ServerInterface.createHttpUrl());
}
/**
* 请求广告
*/
public void postLauncherAds(Context context) {
LogUtils.loge("postLauncherAds() Device Manufacturer="+MXQConfig.getManufacturer());
Map<String,String> parm=new HashMap<>();
String cpuId ="";
if(MXQConfig.ALLWINNER_PLATFORM.equalsIgnoreCase(MXQConfig.getManufacturer())) {
cpuId = DeviceUtil.getCpu();
}else if(MXQConfig.RK_PLATFORM.equalsIgnoreCase(MXQConfig.getManufacturer())){
cpuId = RKDeviceUtil.getCpu();
}
// if(cpuId==null||"".equals(cpuId)){
// cpuId = createUUID();
// }
parm.put("cpu",cpuId);
parm.put("mac", DeviceUtil.getEthernetMac());
parm.put("packageName", context.getPackageName());
parm.put("versionCode", getAppVersion(context)+"");
parm.put("configVersion", getAppVersionName(context)+"");
LogUtils.loge("request:"+GsonUtil.GsonString(parm));
biz.postLauncherAds(parm, new OnBaseListener() {
@Override
public void onResponse(String result) {
LogUtils.loge("result:"+result);
if (GsonUtil.isJson(result)) {
try {
ADInfoResponse verificationResponse = GsonUtil.GsonToBean(result, ADInfoResponse.class);
if (verificationResponse.getCode() == ServerInterface.SUCCESS) {
mAppnetCallback.onResult(verificationResponse.getData());
} else {
mAppnetCallback.onViewFailureString(verificationResponse.getCode(), verificationResponse.getMsg());
}
} catch (Exception e) {
e.printStackTrace();
mAppnetCallback.onExceptionFailure("json 解析异常:"+e.getMessage());
}
} else {
mAppnetCallback.onServerFailure(0,"获取签到信息,服务器繁忙··");
}
}
@Override
public void onFailure(String e, int code) {
mAppnetCallback.onServerFailure(code,e);
}
});
}
private String createUUID(){
String timems =System.currentTimeMillis()+"";
String tmp = timems+"-"+UUID.randomUUID().toString();
return tmp.replace("-","").substring(0,31);
}
// Java 示例
public static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// 获取版本名称versionName
return packageInfo.versionCode;
// 如需获取版本码versionCode使用 packageInfo.versionCode
} catch (PackageManager.NameNotFoundException e) {
return 0;
}
}
public static String getAppVersionName(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// 获取版本名称versionName
return packageInfo.versionName;
// 如需获取版本码versionCode使用 packageInfo.versionCode
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
}

View File

@@ -0,0 +1,93 @@
package com.android.nebulasdk.presenter;
import android.content.Context;
import com.android.api.ServerInterface;
import com.android.api.biz.Biz;
import com.android.api.biz.OnBaseListener;
import com.android.api.biz.bizimpl.BizImpl;
import com.android.database.DaoManager;
import com.android.database.lib.AppBean;
import com.android.database.lib.LocalAppBean;
import com.android.database.lib.MusicAppBean;
import com.android.database.lib.RecommendAppBean;
import com.android.database.lib.ShortAppBean;
import com.android.database.lib.VideoAppBean;
import com.android.nebulasdk.AppManager;
import com.android.nebulasdk.bean.ADInfoResponse;
import com.android.nebulasdk.presenter.callback.AppnetCallback;
import com.android.util.DeviceUtil;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* api请求
*/
public class CategoryAppPresenter {
private AppnetCallback mAppnetCallback;
public CategoryAppPresenter(Context context,AppnetCallback appnetCallback) {
this.mAppnetCallback = appnetCallback;
AppManager.init(context);
}
public void loadAppByCategory(int category){
try {
if(AppManager.CATEGORY_MYAPPS ==category){
List<AppBean> appBeanList = AppManager.getInstance().getmyAppByCategory();
if(mAppnetCallback!=null){
mAppnetCallback.onResult(appBeanList);
}
}else if(AppManager.CATEGORY_VIDEO ==category){
List<VideoAppBean> appBeanList = AppManager.getInstance().getVideoAppByCategory();
if(mAppnetCallback!=null){
mAppnetCallback.onResult(appBeanList);
}
}else if(AppManager.CATEGORY_MUSIC ==category){
List<MusicAppBean> appBeanList = AppManager.getInstance().getMusicAppByCategory();
if(mAppnetCallback!=null){
mAppnetCallback.onResult(appBeanList);
}
}else if(AppManager.CATEGORY_RECOMMEND ==category){
List<RecommendAppBean> appBeanList = AppManager.getInstance().getRecommendAppByCategory();
if(mAppnetCallback!=null){
mAppnetCallback.onResult(appBeanList);
}
}else if(AppManager.CATEGORY_LOCAL ==category){
List<LocalAppBean> appBeanList = AppManager.getInstance().getLocalAppBeanAppByCategory();
if(mAppnetCallback!=null){
mAppnetCallback.onResult(appBeanList);
}
}else if(AppManager.CATEGORY_SHORT ==category){
List<ShortAppBean> appBeanList = AppManager.getInstance().getShortAppBeanAppByCategory();
if(mAppnetCallback!=null){
mAppnetCallback.onResult(appBeanList);
}
}
}catch (Exception e){
mAppnetCallback.onExceptionFailure(e.getMessage());
}
}
}

View File

@@ -0,0 +1,77 @@
package com.android.nebulasdk.presenter;
import android.content.Context;
import com.android.api.ServerInterface;
import com.android.api.biz.Biz;
import com.android.api.biz.OnBaseListener;
import com.android.api.biz.bizimpl.BizImpl;
import com.android.api.response.EventResponse;
import com.android.nebulasdk.bean.EventDataInfo;
import com.android.nebulasdk.presenter.callback.NetCallback;
import com.android.util.GsonUtil;
import com.android.util.LogUtils;
import java.util.List;
/**
* api请求
*/
public class DataBeePresenter {
private Biz biz;
private NetCallback mNetCallback;
public DataBeePresenter(Context context, NetCallback appnetCallback) {
this.mNetCallback = appnetCallback;
biz = new BizImpl( ServerInterface.createHttpUrl());
}
//统计事件信息
public void postEventData(List<EventDataInfo> recordEventBeans){
LogUtils.loge("submit data log==>" + GsonUtil.GsonString(recordEventBeans));
biz.postEventData(recordEventBeans, new OnBaseListener() {
@Override
public void onResponse(String result) {
if (GsonUtil.isJson(result)) {
try {
LogUtils.loge("response recoedDeviceEvent==>" + GsonUtil.GsonString(result));
EventResponse eventResponse = GsonUtil.GsonToBean(result, EventResponse.class);
if(eventResponse.getCode()== ServerInterface.SUCCESS){
// if(eventResponse.getData()!=null){
LogUtils.loge("eventResponse:"+eventResponse.getMsg());
mNetCallback.onNetWorkResult(0);
// }else {
// mNetCallback.onNetWorkResult(-1);
// }
}else {
LogUtils.loge("eventResponse:"+eventResponse.getMsg());
mNetCallback.onNetWorkResult(-1);
}
} catch (Exception e) {
mNetCallback.onExceptionFailure("json 解析异常:"+e.getMessage());
}
} else {
mNetCallback.onServerFailure(0,"服务器繁忙·····");
}
}
@Override
public void onFailure(String e, int code) {
mNetCallback.onServerFailure(code,e);
}
});
}
}

View File

@@ -0,0 +1,24 @@
package com.android.nebulasdk.presenter.callback;
import android.app.TaskInfo;
import com.android.nebulasdk.bean.ADInfo;
import java.util.List;
/**
* api请求回调
*/
public interface AppnetCallback {
/**联网验证返回参数*/
public void onResult(Object data);
/**请求失败返回接口*/
public void onViewFailureString(int code,String message);
/**数据异常信息*/
public void onExceptionFailure(String message);
/** 服务器异常*/
public void onServerFailure(int code,String message);
}

View File

@@ -0,0 +1,11 @@
package com.android.nebulasdk.presenter.callback;
public interface BaseCallback {
/**请求失败返回接口*/
public void onViewFailureString(int code,String message);
/**数据异常信息*/
public void onExceptionFailure(String message);
/** 服务器异常*/
public void onServerFailure(int code,String message);
}

View File

@@ -0,0 +1,13 @@
package com.android.nebulasdk.presenter.callback;
import java.util.List;
/**
* api请求回调
*/
public interface BlackListCallback {
public void onResult(boolean isResult,int statisticsCode);
// public void onBlackListResult(List<BlackAppBean> blackList);
}

View File

@@ -0,0 +1,18 @@
package com.android.nebulasdk.presenter.callback;
/**
* api请求回调
*/
public interface CategoryAppCallback {
/**联网验证返回参数*/
public void onResult(Object data);
/**请求失败返回接口*/
public void onViewFailureString(int code,String message);
/**数据异常信息*/
public void onExceptionFailure(String message);
/** 服务器异常*/
public void onServerFailure(int code,String message);
}

View File

@@ -0,0 +1,14 @@
package com.android.nebulasdk.presenter.callback;
/**
* api请求回调
*/
public interface NetCallback extends BaseCallback {
/**任务更新返回参数*/
public void onNetWorkResult(int code);
}

View File

@@ -0,0 +1,17 @@
package com.android.nebulasdk.presenter.callback;
/**
* api请求回调
*/
public interface StatisticsCallback {
public void onResult(boolean isResult,int statisticsCode);
/**请求失败返回接口*/
public void onViewFailureString(int code,String message);
/**数据异常信息*/
public void onExceptionFailure(String message);
/** 服务器异常*/
public void onServerFailure(int code,String message);
}

View File

@@ -0,0 +1,552 @@
package com.android.util;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 执行系统更新
*/
public class AppInstallUtil {
private static final String TAG= "INSTALL";
/**检测app是否安装*/
public static boolean checkAppUpdateLq(Context context,String packageName,int versionCode){
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName,0);
if (packageInfo != null) {
if(packageInfo.versionCode<versionCode){
return true;
}else {
return false;
}
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 检测app是否安装
*/
public static boolean checkAppUpdate(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
if (packageInfo != null) {
return true;
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**检测app是否需要更新*/
public static boolean checkAppInstall(Context context,String packageName,int versionCode){
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName,0);
if (packageInfo != null) {
if(packageInfo.versionCode<versionCode){
return false;
}else {
return true;
}
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
private static String runCommand(Context context,String apkPath) {
LogUtils.loge("AndroidSDKVersion runCommand:"+getAndroidSDKVersion());
Process process = null;
String result = "";
DataOutputStream os = null;
DataInputStream is = null;
//"pm", "install","-i","com.example.startservices", "-r", apkPath
try {
String packagename = context.getPackageName();
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
is = new DataInputStream(process.getInputStream());
os.writeBytes("pm install -i "+packagename+" -r "+apkPath+ "\n");
os.writeBytes("exit\n");
os.flush();
String line = null;
while ((line = is.readLine()) != null) {
result += line;
}
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (process != null) {
process.destroy();
}
}
return result;
}
public static String runCommandSDK24(Context context, String filePath) {
int result = -1;
try {
LogUtils.loge("AndroidSDKVersion runCommandSDK24:"+getAndroidSDKVersion());
String[] args = {"pm", "install", "-i ", context.getPackageName(), "-r", filePath};
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = processBuilder.start();
successResult = new BufferedReader(new InputStreamReader(
process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
Log.d(TAG, "s : " + s);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
if (successMsg != null && (successMsg.toString().contains("Success")
|| successMsg.toString().contains("success"))) {
result = 0;
}
return successMsg.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String runKillCommand(Context context,String pid) {
LogUtils.loge("AndroidSDKVersion runCommand:"+getAndroidSDKVersion());
Process process = null;
String result = "";
DataOutputStream os = null;
DataInputStream is = null;
//"pm", "install","-i","com.example.startservices", "-r", apkPath
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
is = new DataInputStream(process.getInputStream());
os.writeBytes("kill "+pid+"\n");
os.writeBytes("exit\n");
os.flush();
String line = null;
while ((line = is.readLine()) != null) {
result += line;
}
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (process != null) {
process.destroy();
}
}
return result;
}
// public static boolean executeAppInstall(Context context,String apkPath) {
// boolean result = false;
// StringBuilder successMsg = new StringBuilder();
// String text = "";
// if(getAndroidSDKVersion()>Build.VERSION_CODES.N){
// text = runCommand(context, apkPath);
// }else {
// text = runCommandSDK24(context, apkPath);
// }
//
// successMsg.append(text);
// successMsg.append(" install msg");
//
// if(!"".equals(successMsg)&&successMsg.toString().toLowerCase().contains("success")){
// //安装成功
// result = true;
// Log.e("install","install Success message is ==>" +successMsg.toString());
// }else {
// result = false;
// Log.e("install","install fail message is ==>" +successMsg.toString());
// }
// return true;
// }
public static boolean silentInstall(Context context,String mApkFilePath) {
File file = new File(mApkFilePath);
try {
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setSize(file.length());
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
InputStream in = new FileInputStream(file);
OutputStream out = session.openWrite("CocosDemo", 0, file.length());
byte[] buffer = new byte[65536];
int c;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
session.fsync(out);
in.close();
out.close();
LogUtils.loge("android.os.Build.VERSION.SDK_INT:"+ Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
session.commit(PendingIntent.getBroadcast(context, sessionId,
new Intent("android.intent.action.PACKAGE_ADDED"), PendingIntent.FLAG_IMMUTABLE).getIntentSender());
} else {
session.commit(PendingIntent.getBroadcast(context, sessionId,
new Intent("android.intent.action.PACKAGE_ADDED"), 0).getIntentSender());
}
return true;
} catch (Exception e) {
// Log.e(TAG,"安装失败:"+e.getMessage());
LogUtils.loge("安装失败:"+e.getMessage());
e.printStackTrace();
return false;
}
}
// public static boolean executeAppUnInstall(Context context ,String packageName){
// boolean result = false;
// Process process = null;
// BufferedReader successResult = null;
// BufferedReader errorResult = null;
// StringBuilder successMsg = new StringBuilder();
// StringBuilder errorMsg = new StringBuilder();
// try {
// Log.e("install","uninstall message is ==>" + packageName );
// process = new ProcessBuilder("pm", "uninstall","-i",context.getPackageName(), "-k",packageName).start();
// successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
// errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String s;
// while ((s = successResult.readLine()) != null) {
// successMsg.append(s);
// }
// while ((s = errorResult.readLine()) != null) {
// errorMsg.append(s);
// }
//
// if(!"".equals(successMsg)&&successMsg.toString().toLowerCase().contains("sucess")){
// //安装成功
// Log.e("install","uninstall successMsg is ==>" +successMsg.toString());
// result = true;
//
// }else {
// Log.e("install","uninstall failMsg is ==>" +errorMsg.toString());
// result = false;
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return result;
//
// }
// public void deleteApp(Context context,String appPackage) {
// PackageManager pm = context.getPackageManager();
// try {
// Class<?>[] uninstalltypes = new Class[] {String.class, IPackageDeleteObserver.class, int.class};
// Method uninstallmethod = pm.getClass().getMethod("deletePackage", uninstalltypes);
// uninstallmethod.invoke(pm, appPackage, new PackageDeletedObserver(), 0);
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
// public static boolean executeAppUnInstall(String packageName){
// boolean result = false;
// try {
//
// // 申请su权限
// Runtime.getRuntime().exec("su");
// // 执行pm install命令
// String command = "pm uninstall -k " + packageName + "\n";
// LogUtils.loge("executeAppUnInstall==>"+command);
// Process process = Runtime.getRuntime().exec(command);
// BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String msg = "";
// String line;
//
// // 读取命令的执行结果
// while ((line = errorStream.readLine()) != null) {
// msg += line;
// }
// LogUtils.loge( "uninstall msg is " + msg);
// // 如果执行结果中包含Failure字样就认为是安装失败否则就认为安装成功
// if (!msg.contains("Failure")) {
// result = true;
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// LogUtils.logd( "install msg is " + e.getMessage());
// }
//
// return result;
//
// }
public static void executeAppUnInstall(Context context, String packageName) {
LogUtils.loge("-------------------del-----");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
executeAppUnInstall29( context, packageName);
}else {
executeAppUnInstall24(context,packageName);
}
}
public static void executeAppUnInstall29(Context context,String packageName){
Log.i("----ik", "-------------------del-----");
try {
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent sender = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PackageInstaller mPackageInstaller = context.getPackageManager().getPackageInstaller();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
mPackageInstaller.uninstallExistingPackage(packageName,sender.getIntentSender());
}else {
mPackageInstaller.uninstall(packageName, sender.getIntentSender());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void executeAppUnInstall24(Context context, String packageName){
try {
PackageManager mPackageManager=context.getPackageManager();
Method method = mPackageManager
.getClass()
.getMethod(
"deletePackage",
String.class,
Class.forName("android.content.pm.IPackageDeleteObserver"),
int.class);
method.setAccessible(true);
method.invoke(mPackageManager, packageName,
null, 0x00000002);
/**
* 0x00000002 to indicate that you want the package
* deleted for all users.
*/
} catch (Exception e) {
e.printStackTrace();
}
}
public static void resetBoot(){
try {
String command = "reboot " + "\n";
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
private static int getAndroidSDKVersion() {
int version = 0;
try {
version = Integer.valueOf(Build.VERSION.SDK);
} catch (NumberFormatException e) {
}
return version;
}
@SuppressLint("WrongConstant")
public static List<Map<String,String>> findAllApps(Context context) {
PackageManager manager = context.getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> allApps = manager.queryIntentActivities(mainIntent, PackageManager.INSTALL_REASON_UNKNOWN);
List<Map<String,String>> appInfoList = new ArrayList<>();
for (int i = 0; i < allApps.size(); i++) {
ResolveInfo info = allApps.get(i);
// if((packageInfo.applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)<=0){
Map<String,String> appMap= new HashMap<>();
try {
String packageName = info.activityInfo.packageName;
PackageInfo packageInfo =context.getPackageManager().getPackageInfo(packageName,0);
String versionMessage = packageInfo.versionName+"-"+packageInfo.versionCode;
String label = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
appMap.put("appName", label);
appMap.put("packageName", info.activityInfo.packageName);
appMap.put("versionInfo", versionMessage);
appInfoList.add(appMap);
LogUtils.loge(GsonUtil.GsonString(appMap));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
// }
}
return appInfoList;
}
public static int getAppVersion(Context context) {
int versionCode = 0;
try {
// 获取PackageManager实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名0代表是获取版本信息
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
versionCode = packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
}

View File

@@ -0,0 +1,138 @@
package com.android.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class BitmapUtils {
/**
* drawable to bitmap
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable){
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(0,0,width,height);
Bitmap.Config config = drawable.getOpacity()!= PixelFormat.OPAQUE?Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565;
Bitmap bitmap =Bitmap.createBitmap(width,height,config);
Canvas canvas = new Canvas(bitmap);
drawable.draw(canvas);
return setRoundCornerBitmap(bitmap,10);
}
/**
* drawable to bitmap
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable,int mwidth, int mheight){
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(0,0,width,height);
Bitmap.Config config = drawable.getOpacity()!= PixelFormat.OPAQUE?Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565;
Bitmap bitmap =Bitmap.createBitmap(mwidth,mheight,config);
Canvas canvas = new Canvas(bitmap);
drawable.draw(canvas);
return setRoundCornerBitmap(bitmap,10);
}
/**
* drawable to bitmap
* @return
*/
public static Drawable getWidthCircleBitmapbg(){
Bitmap dest = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(dest);
PaintFlagsDrawFilter pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); //画图片时设置画布抗锯齿
c.setDrawFilter(pfd);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
c.drawCircle(50/2,50/2, 50/2, paint);
return new BitmapDrawable(dest);
}
public static Bitmap setRoundCornerBitmap(Bitmap bitmap,float roundPx){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap outmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outmap);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0,0,width,height);
final RectF rectf = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0,0,0,0);
paint.setColor(color);
canvas.drawRoundRect(rectf,roundPx,roundPx,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap,rect,rect,paint);
return outmap;
}
public static Bitmap getIconByPackageName(Context mContext,String packageName){
try {
PackageManager pm = mContext.getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
Drawable iconDrawable = applicationInfo.loadIcon(pm);//应用图标
return BitmapUtils.drawableToBitmap(iconDrawable);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Bitmap getIconByPackageName(Context mContext,String packageName,int mwidth, int mheight){
try {
PackageManager pm = mContext.getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
Drawable iconDrawable = applicationInfo.loadIcon(pm);//应用图标
return BitmapUtils.drawableToBitmap(iconDrawable, mwidth, mheight);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,418 @@
package com.android.util;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
public class DateUtil {
/**
* 预设不同的时间格式
*/
//精确到年月日(英文) eg:2019-12-31
public static String FORMAT_LONOGRAM = "yyyy-MM-dd";
public static String FORMAT_LONOGRAM01 = "yyyyMMdd";
//精确到时分秒的完整时间(英文) eg:2010-11-11 12:12:12
public static String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
//精确到毫秒完整时间(英文) eg:2019-11-11 12:12:12.55
public static String FORMAT_LONOGRAM_MILL = "yyyy-MM-dd HH:mm:ss.SSS";
//精确到年月日中文eg:2019年11月11日
public static String FORMAT_LONOGRAM_CN = "yyyy年MM月dd日";
//精确到时分秒的完整时间中文eg:2019年11月11日 12时12分12秒
public static String FORMAT_FULL_CN = "yyyy年MM月dd日 HH时MM分SS秒";
//精确到毫秒完整时间(中文)
public static String FORMAT_LONOGRAM_MILL_CN = "yyyy年MM月dd日HH时MM分SS秒SSS毫秒";
/**
* 预设默认的时间格式
*/
public static String getDefaultFormat() {
return FORMAT_FULL;
}
/**
* 预设格式格式化日期
*/
public static String format(Date date) {
return format(date,getDefaultFormat());
}
/**
* 自定义格式格式化日期
*/
public static String format(Date date, String format) {
String value = "";
if(date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
value = sdf.format(date);
}
return value;
}
/**
* 根据预设默认格式,返回当前日期
*/
public static String getNow() {
return format(new Date());
}
/**
* 自定义时间格式,返回当前日期
*/
public static String getNow(String format) {
return format(new Date(),format);
}
/**
*根据预设默认时间 String->Date
*/
public static Date parse(String strDate) {
return parse(strDate,getDefaultFormat());
}
public static String getNowTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date date = new Date(System.currentTimeMillis());
return simpleDateFormat.format(date);
}
public static String getNowDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM");
Date date = new Date(System.currentTimeMillis());
return simpleDateFormat.format(date);
}
public static String getNowWeek() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
Date date = new Date(System.currentTimeMillis());
return simpleDateFormat.format(date);
}
public static String getAm() {
String am="";
long time = System.currentTimeMillis();
final Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(time);
int apm = mCalendar.get(Calendar.AM_PM);
if (apm == 0) {
am="AM";
} else if (apm == 1) {
am="PM";
}
Log.d("getam","am value"+am);
return am;
}
/**
* 自定义时间格式Stirng->Date
*/
public static Date parse(String strDate,String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(strDate);
}catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 基于指定日期增加年
* @param num 正数往后推,负数往前移
* Calendar:它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR
* 等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
*/
public static Date addYear(Date date,int num) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, num);
return cal.getTime();
}
/**
* 基于指定日期增加整月
* @param date
* @param num 整数往后推,负数往前移
* @return
*/
public static Date addMonth(Date date,int num) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, num);
return cal.getTime();
}
/**
* 基于指定日期增加天数
* @param date
* @param num 整数往后推,负数往前移
* @return
*/
public static Date addDay(Date date,int num) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, num);
return cal.getTime();
}
/**
* 基于指定日期增加分钟
* @param date
* @param num 整数往后推,负数往前移
* @return
*/
public static Date addMinute(Date date,int num) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, num);
return cal.getTime();
}
/**
* 获取时间戳 eg:yyyy-MM-dd HH:mm:ss.S
* @return
*/
public static String getTimeStamp() {
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_LONOGRAM_MILL);
Calendar cal = Calendar.getInstance();
return sdf.format(cal.getTime());
}
/**
* 获取日期的年份
* @param date
* @return
*/
public static String getYear(Date date) {
return format(date).substring(0,4);
}
/**
* 获取年份+月
*/
public static String getYearMonth(Date date) {
return format(date).substring(0, 7);
}
/**
*获取日期的小时数
*/
public static int getHour(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.HOUR_OF_DAY);
}
/**
* 自定义时间格式字符串距离今天的天数
* @param strDate
* @param format
* @return
*/
public static int countDays(String strDate,String format) {
long time = Calendar.getInstance().getTime().getTime();
Calendar cal = Calendar.getInstance();
cal.setTime(parse(strDate,format));
long diff = cal.getTime().getTime();
long a = time/1000;
long b = diff/1000;
return (int) (a - b)/3600/24;
}
/**
* 预设格式的字符串距离今天的天数
* @param strDate
* @return
*/
public static int countDays(String strDate) {
return countDays(strDate,getDefaultFormat());
}
/**
* 获取天数差值(依赖时间)
* @param date1
* @param date2
* @return
*/
public static int diffDays(Date date1,Date date2) {
if(date1 == null || date2 == null) {
return 0;
}
return (int) (Math.abs(date1.getTime() - date2.getTime()) / (60 * 60 * 24 * 1000));
}
/**
* 获取年份差值
* @param year1
* @param year2
* @return
*/
public static int diffYear(Date year1,Date year2) {
return diffDays(year1,year2) / 365;
}
/**
* 获取天数差值(依赖Date类型的日期)
* @param d1
* @param d2
* @return
*/
public static int diffByDays(Date d1,Date d2) {
Date s1 = parse(format(d1,FORMAT_LONOGRAM),FORMAT_LONOGRAM);
Date s2 = parse(format(d2,FORMAT_LONOGRAM),FORMAT_LONOGRAM);
return diffDays(s1,s2);
}
// /**
// * 获取时间分割集合
// *
// * @param date 查询日期
// * @param strs 带拆分的时间点
// * @return
// */
// public static List<Date> collectTimes(Date date, String[] strs){
// List<Date> result = new ArrayList<Date>();
// List<String> times = Arrays.asList(strs);
// String dateStr = format(date,FORMAT_LONOGRAM);
// String pattern = FORMAT_LONOGRAM + "K";
// if(times.size() > 0 ) {
// times.stream().forEach(t -> {
// result.add(parse(date +" "+ t,pattern));
// });
// }
// return result;
// }
/**
* 根据日期查询当前为周几
* @param dt
* @return
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"7","1","2","3","4","5","6"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK); //1--7的值,对应:星期日,星期一,星期二,星期三....星期六
//System.out.println(w);
return weekDays[w-1];
}
/**
* 将时间转换成汉字
* @param hour
* @return
*/
public static String hourToCn(String hour) {
String[] timeArray = {"", "", "", "", "", "", "", "", "", "", ""};
String[] hourArray = hour.split(":");
int hourInt = Integer.parseInt(hourArray[0]);
int minute = Integer.parseInt(hourArray[1]);
String result = intToCn(hourInt,timeArray) + "\n" + intToCn(minute,timeArray) + "";
return result;
}
private static String intToCn(int hourInt, String[] timeArray) {
String result = "";
if(hourInt >= 0 && hourInt <= 10) {
result += timeArray[hourInt] + "\n";
} else if (hourInt >= 11 && hourInt <= 19) {
result += (timeArray[10] + "\n" + timeArray[hourInt % 10]) + "\n";
}else {
result += (timeArray[hourInt / 10] + "\n" + timeArray[10]) + "\n" + (hourInt % 10 == 0 ? "" : timeArray[hourInt % 10] + "\n");
}
return result;
}
/**
* 获取当前日期后的一周时间并返回LinkedHashMap<String, Date>
* @param startTime
* @return
*/
public static LinkedHashMap<String, Date> dateAfterWeek(String startTime) {
LinkedHashMap<String, Date> result = new LinkedHashMap<>();
try {
Date date = parse(startTime,FORMAT_LONOGRAM);
for (int i = 0; i < 7; i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.DATE, i); //把日期往后增加一天,整数往后推,负数往前移动 时间戳转时间
Date newDate = calendar.getTime();
String str = new SimpleDateFormat("yyyy-MM-dd").format(newDate);
result.put(str, newDate);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 获取当前日期 后的一周时间并返回yyyy-MM-dd字符串数组
* @param startTime
* @return
*/
public static String[] dateAfterWeekArray(String startTime) {
String weekArray[] = new String[7];
try {
Date date = parse(startTime,FORMAT_LONOGRAM);
for (int i = 0; i < 7; i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.DATE, i);//把日期往后增加一天,整数往后推,负数往前移动 时间戳转时间
Date newDate = calendar.getTime();
weekArray[i] = new SimpleDateFormat("yyyy-MM-dd").format(newDate);
}
} catch (Exception e) {
e.printStackTrace();
}
return weekArray;
}
/**
* 根据传入的时间获取本周开始0-表示本周1-表示下周,-1-表示上周
* @param date
* @return
*/
public static String getMonDayToDate(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, "yyyy-MM-dd"));
// N0-表示本周1-表示下周,-1-表示上周
cal.add(Calendar.DATE, 0 * 7);
// Calendar.MONDAY 表示获取周一的日期; Calendar.WEDNESDAY:表示周三的日期
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return format(cal.getTime());
}
public static String getYesterDayDate(){
//获取当前日期
Calendar calendar= Calendar.getInstance();
// 将日期减一天
calendar.add(Calendar.DAY_OF_MONTH,-1);
return format(calendar.getTime(),FORMAT_LONOGRAM01);
}
public static void main(String[] args) {
//String time = format(new Date());
//String weekOfDate = getWeekOfDate(new Date());
//int countDays = countDays("2019-12-22",FORMAT_LONOGRAM);
//Calendar cal = Calendar.getInstance();
// long time = cal.getTime().getTime();
// System.out.println("星期:"+weekOfDate);
// String hourToCn = hourToCn(format(new Date()).substring(11, 19));
// System.out.print(hourToCn);
// String[] dateAfterWeekArray = dateAfterWeekArray(format(new Date()));
// for (int i = 0; i < dateAfterWeekArray.length; i++) {
// System.out.println(dateAfterWeekArray[i]);
// }
String monDayToDate = getMonDayToDate(format(new Date()));
System.out.println(monDayToDate);
}
// public static String getDeviceName( NodeInfo nodeInfo) {
// DevicTypeModelBean deviceType = TelinkMeshApplication.mDeviceModel.getDeviceModel(nodeInfo.deviceModleType.toLowerCase());
// if (deviceType != null) {
// nodeInfo.deviceName = deviceType.getType() + "-" + nodeInfo.macAddress.replace(":", "");
// }
// return nodeInfo.deviceName;
// }
// }
}

View File

@@ -0,0 +1,502 @@
package com.android.util;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class DeviceUtil {
public static String getDeviceId() {
// String uuid =null;
// TelephonyManager TelephonyMgr = (TelephonyManager) activity.getSystemService(TELEPHONY_SERVICE);
// if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
// PermissionChecker.getInstance().requestReadPhoneState(activity);
// return uuid;
// }
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// /* LogUtils.e("$$$$$$$$------Build.getSerial()="+Build.getSerial());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getSimSerialNumber()="+TelephonyMgr.getSimSerialNumber());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getImei()="+TelephonyMgr.getImei());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getSubscriberId()="+TelephonyMgr.getSubscriberId());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getLine1Number()="+TelephonyMgr.getLine1Number());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getDeviceId()="+TelephonyMgr.getDeviceId());
// LogUtils.e("$$$$$$$$------UUID="+UUID.randomUUID().toString());*/
// uuid = Build.getSerial();//序列号
// if(isEmpty(uuid)){//IMEI:国际移动设备识别码
// uuid = TelephonyMgr.getImei();
// }
// if(isEmpty(uuid)){//IMEI:国际移动设备识别码
// uuid = TelephonyMgr.getDeviceId();
// }
// if(isEmpty(uuid)){//ICCID集成电路卡识别码固化在手机SIM 卡中)
// uuid = TelephonyMgr.getSimSerialNumber();
// }
// if(isEmpty(uuid)){//IMSI国际移动用户识别码sim卡运营商信息
// uuid = TelephonyMgr.getSubscriberId();
// }
// if(isEmpty(uuid)){
// uuid = TelephonyMgr.getLine1Number();
// }
// //UUID.randomUUID().toString();
// }else {
// Class<?> c = null;
// try {
// c = Class.forName("android.os.SystemProperties");
// Method get = c.getMethod("get", String.class);
// uuid = (String) get.invoke(c, "ro.serialno");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
// if (isEmpty(uuid)){
// UUID.randomUUID().toString();
// }
return "";
}
// public static String getSerialNumber(){
// String serial = null;
// try {
// if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1){//7.11+
// serial = Build.getSerial();
// LogUtils.e("===========7.11+=======================");
// }else{
// Class<?> c;
// c = Class.forName("android.os.SystemProperties");
// Method get = c.getMethod("get", String.class);
// serial = (String) get.invoke(c, "ro.serialno");
// LogUtils.e("===========7.11-======================");
// }
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// if (serial == null){
// //serial = "000000";
// }
// return serial;
// }
public static String getSerialNum(Context context) {
String serial = null;
// try {
// Class<?> c = Class.forName("android.os.SystemProperties");
// Method get = c.getMethod("get", String.class);
// serial = (String) get.invoke(c, "ro.serialno");
// } catch (Exception e) {
// }
// if (serial == null || serial.isEmpty() || serial.length() < 5) {
// serial = getWifiMacAddress(context);
// if (serial == null || serial.isEmpty()) serial = getBtMacAddress(context);
// if (serial == null || serial.isEmpty()) serial = "serial No. error ";
// }
// return serial;
return "BBBBBBBB";
}
public static boolean isDeviceExist(Context context, String mac) {
String deviceId = getEthernetMac();
if (deviceId.equals(mac)) {
return true;
} else {
return false;
}
}
public static String getEthernetMac() {
String ethernetMac = null;
try {
NetworkInterface NIC = NetworkInterface.getByName("eth0");
byte[] buf = NIC.getHardwareAddress();
ethernetMac = byteHexString(buf);
} catch (SocketException e) {
e.printStackTrace();
}
// return "EC:2E:CC:81:0D:62"; //for test
return ethernetMac;
}
public static String getWifiMac(){
String wifiMac = null;
String line = null;
String cmd = "cat /sys/class/net/wlan0/address";
try {
Process p = Runtime.getRuntime().exec(cmd);
// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String error = null;
// while ((error = ie.readLine()) != null && !error.equals("null")) {
// Log.d("===========", "========error="+error);
// }
while ((line = in.readLine()) != null && !line.equals("null")) {
wifiMac = line;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return wifiMac;
}
/*
* 字节数组转16进制字符串
*/
public static String byteHexString(byte[] array) {
StringBuilder builder = new StringBuilder();
for(int i=0;i<array.length;i++){
String hex = Integer.toHexString(array[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
if(i<array.length-1){
builder.append(hex+":");
}else {
builder.append(hex);
}
}
return builder.toString().toUpperCase();
}
public static String getBrand(){
return Build.BRAND;
}
public static String getBuild(){
return Build.FINGERPRINT;
}
public static String getDevice(){
return Build.DEVICE;
}
public static String getCpu(){
String platform = getAllwinnerPlatform();
if("sun8iw7".equals(platform)){
return getH3CPUinfo();
}
return getH616And313CPUinfo();
}
private static String getRKCPUinfo() {
String cpuAddress = "";
String line = null;
String cmd = "cat /proc/cpuinfo";
try {
Process p = Runtime.getRuntime().exec(cmd);
// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String error = null;
// while ((error = ie.readLine()) != null && !error.equals("null")) {
// Log.d("===========", "========error="+error);
// }
while ((line = in.readLine()) != null && !line.equals("null")) {
if (line.contains("Serial")) {
String[] SerialStr = line.split(":");
if (SerialStr.length == 2) {
String mSerial = SerialStr[1];
cpuAddress = mSerial.trim();
return cpuAddress;
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return cpuAddress;
}
public static String getDdr(){
return "";
}
public static String getModel(){
return Build.MODEL;
}
public static String getPlatform(){
return "allwinner";
}
public static String getSystemVersion(){
return Build.VERSION.RELEASE;
}
private static String getH3CPUinfo() {
String cpuAddress = "";
String line = null;
String cmd = "cat /sys/class/sunxi_info/sys_info";
try {
Process p = Runtime.getRuntime().exec(cmd);
// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String error = null;
// while ((error = ie.readLine()) != null && !error.equals("null")) {
// Log.d("===========", "========error="+error);
// }
while ((line = in.readLine()) != null && !line.equals("null")) {
if (line.contains("sunxi_chipid")) {
String[] SerialStr = line.split(":");
if (SerialStr.length == 2) {
String mSerial = SerialStr[1];
cpuAddress = mSerial.trim();
return cpuAddress;
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return cpuAddress;
}
private static String getH616And313CPUinfo() {
String cpuAddress = "";
String line = null;
String cmd = "cat /sys/class/sunxi_info/sys_info";
try {
Process p = Runtime.getRuntime().exec(cmd);
// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String error = null;
// while ((error = ie.readLine()) != null && !error.equals("null")) {
// Log.d("===========", "========error="+error);
// }
while ((line = in.readLine()) != null && !line.equals("null")) {
if (line.contains("sunxi_serial")) {
String[] SerialStr = line.split(":");
if (SerialStr.length == 2) {
String mSerial = SerialStr[1];
cpuAddress = mSerial.trim();
return cpuAddress;
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return cpuAddress;
}
private static String getAllwinnerPlatform() {
String platform = "";
String line = null;
String cmd = "cat /sys/class/sunxi_info/sys_info";
try {
Process p = Runtime.getRuntime().exec(cmd);
// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String error = null;
// while ((error = ie.readLine()) != null && !error.equals("null")) {
// Log.d("===========", "========error="+error);
// }
while ((line = in.readLine()) != null && !line.equals("null")) {
if (line.contains("sunxi_platform")) {
String[] SerialStr = line.split(":");
if (SerialStr.length == 2) {
String mSerial = SerialStr[1];
platform = mSerial.trim();
return platform;
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return platform;
}
/**
* 获取系统ram大小
* @return
*/
public static String getSysteTotalMemorySize(Context context){
//获得ActivityManager服务的对象
ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
//获得MemoryInfo对象
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo() ;
//获得系统可用内存保存在MemoryInfo对象上
mActivityManager.getMemoryInfo(memoryInfo) ;
long memSize = memoryInfo.totalMem ;
//字符类型转换
String availMemStr = formateFileSize(memSize,true);
return availMemStr ;
}
// /**
// * 获取系统rom大小
// * @return
// */
// @RequiresApi(api = Build.VERSION_CODES.O)
// public static String getSysteTotalStorageSize(Context context){
// //获得ActivityManager服务的对象
// String availMemStr = null;
// try {
// StorageStatsManager storageManager = (StorageStatsManager)context.getSystemService(Context.STORAGE_STATS_SERVICE);
// //字符类型转换
// availMemStr = formateFileSize( storageManager.getTotalBytes(StorageManager.UUID_DEFAULT),true);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return availMemStr ;
// }
/**
* 获取系统rom大小
* @return
*/
public static String getSysteTotalStorageSize(Context context){
//获得ActivityManager服务的对象
String availMemStr = null;
try {
// final StorageManager storageManager = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
// storageManager.getStorageVolumes()
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
long totalSize = statFs.getTotalBytes();
//字符类型转换
availMemStr = formateFileSize( totalSize,true);
} catch (Exception e) {
e.printStackTrace();
}
return availMemStr ;
}
// public static String getSysteTotalStorageSize(Context context) {
// String dir = "/proc/meminfo";
// try {
// FileReader fr = new FileReader(dir);
// BufferedReader br = new BufferedReader(fr, 2048);
// String memoryLine = br.readLine();
// String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
// br.close();
// return formateFileSize(Integer.parseInt(subMemoryLine.replaceAll("\\D+", "")) * 1024l,true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return formateFileSize(0, true);
// }
public static String formateFileSize(long size, boolean isInteger) {
DecimalFormat df = isInteger ? new DecimalFormat("#0") : new DecimalFormat("#0.#");
String fileSizeString = "0M";
if (size < 1024 && size > 0) {
fileSizeString = df.format((double) size) + "B";
} else if (size < 1024 * 1024) {
fileSizeString = df.format((double) size / 1024) + "K";
} else if (size < 1024 * 1024 * 1024) {
fileSizeString = df.format((double) size / (1024 * 1024)) + "M";
} else {
fileSizeString = df.format((double) size / (1024 * 1024 * 1024)) + "G";
}
return fileSizeString;
}
/***
* 获取本机默认的launcher
* @return
*/
public static String getDefaultLauncherPackageName(Context context) {
final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
return mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
return null;
}
public static String getLauncherPackageName(Context context) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addCategory(Intent.CATEGORY_DEFAULT);
final List<ResolveInfo> resList = context.getPackageManager().queryIntentActivities(intent, 0);
String tmp="";
for (ResolveInfo res:resList) {
if (res.activityInfo == null) {
continue;
}
if("com.android.settings".equals(res.activityInfo.packageName)){
continue;
}
if("com.android.tv.settings".equals(res.activityInfo.packageName)){
continue;
}
tmp+=res.activityInfo.packageName+",";
}
return "".equals(tmp)?null:tmp;
}
}

View File

@@ -0,0 +1,39 @@
package com.android.util;
public class EventBusType{
private Object mMessgae;
private int mType;
/**添加喜欢的应用到频道中去*/
public static final int ADD_APP_TO_CHANNEL_TYPE=10;
/**频道设置关消息*/
public static final int SWITCH_OFF_CHANNEL_TYPE=11;
/**频道设置开消息*/
public static final int SWITCH_ON_CHANNEL_TYPE=12;
public static final int TYPE_USB_REMOVE=0;
public static final int TYPE_SD_REMOVE=1;
public static final int TYPE_SD_MOUNT=2;
public static final int TYPE_USB_MOUNT=3;
public static final int TYPE_ETHERNET=4;
public static final int TYPE_WIFI=5;
public static final int TYPE_NONET=6;
public static final int TYPE_APP_REMOVE=7;
public static final int TYPE_APP_INSTALL=8;
/**app扫描完成*/
public static final int SCANING_APP_COMPLETE =9;
public EventBusType(int type,Object message){
this.mType =type;
this.mMessgae = message;
};
public Object getMessgae() {
return mMessgae;
}
public int getType() {
return mType;
}
}

View File

@@ -0,0 +1,354 @@
/********************************************************************************************************
* @file FileSystem.java
*
* @brief for TLSR chips
*
* @author telink
* @date Sep. 30, 2010
*
* @par Copyright (c) 2010, Telink Semiconductor (Shanghai) Co., Ltd.
* All rights reserved.
*
* The information contained herein is confidential and proprietary property of Telink
* Semiconductor (Shanghai) Co., Ltd. and is available under the terms
* of Commercial License Agreement between Telink Semiconductor (Shanghai)
* Co., Ltd. and the licensee in separate contract or the terms described here-in.
* This heading MUST NOT be removed from this file.
*
* Licensees are granted free, non-transferable use of the information in this
* file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
*
*******************************************************************************************************/
package com.android.util;
import android.content.Context;
import android.os.Environment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class FileSystem {
public static boolean writeAsObject(Context context, String fileName, Object obj) {
File externalFilesDir = context.getExternalFilesDir(null);
// LogUtils.loge("externalFilesDir===>"+externalFilesDir.getPath());
File file = new File(externalFilesDir, fileName);
FileOutputStream fos = null;
ObjectOutputStream ops = null;
boolean success = false;
try {
if (!file.exists())
file.createNewFile();
fos = new FileOutputStream(file);
ops = new ObjectOutputStream(fos);
ops.writeObject(obj);
ops.flush();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ops != null)
ops.close();
if (ops != null)
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return success;
}
public static boolean writeAsObject(Context context,String mkdir, String fileName, Object obj) {
File externalFilesDir = context.getExternalFilesDir(mkdir);
// LogUtils.loge("externalFilesDir===>"+externalFilesDir.getPath());
File file = new File(externalFilesDir, fileName);
FileOutputStream fos = null;
ObjectOutputStream ops = null;
boolean success = false;
try {
if (!file.exists())
file.createNewFile();
fos = new FileOutputStream(file);
ops = new ObjectOutputStream(fos);
ops.writeObject(obj);
ops.flush();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ops != null)
ops.close();
if (ops != null)
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return success;
}
public static Object readAsObject(Context context, String fileName) {
File dir = context.getExternalFilesDir(null);
// LogUtils.loge("dir===>"+dir.getPath());
File file = new File(dir, fileName);
if (!file.exists())
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
Object result = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
result = ois.readObject();
} catch (IOException | ClassNotFoundException e) {
LogUtils.loge("read object error : " + e.toString());
} finally {
try {
if (ois != null)
ois.close();
} catch (Exception e) {
}
}
return result;
}
public static Object readAsObject(Context context, String mkdir,String fileName) {
File dir = context.getExternalFilesDir(mkdir);
// LogUtils.loge("dir===>"+dir.getPath());
File file = new File(dir, fileName);
if (!file.exists())
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
Object result = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
result = ois.readObject();
} catch (IOException | ClassNotFoundException e) {
LogUtils.loge("read object error : " + e.toString());
} finally {
try {
if (ois != null)
ois.close();
} catch (Exception e) {
}
}
return result;
}
/**获取指定目录下的所有文件*/
public static File[] getListFileByMkdir(Context context,String mkdir){
File dir = context.getExternalFilesDir(mkdir);
if(dir.exists()){
return dir.listFiles();
}
return null;
}
public static Object readTestAsObject(Context context, String filePath) {
// File dir = context.getFilesDir();
File file = new File(filePath);
if (!file.exists())
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
Object result = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
result = ois.readObject();
} catch (IOException | ClassNotFoundException e) {
LogUtils.loge("read object error : " + e.toString());
} finally {
try {
if (ois != null)
ois.close();
} catch (Exception e) {
}
}
return result;
}
public static File getSettingPath() {
File root = Environment.getExternalStorageDirectory();
return new File(root.getAbsolutePath() + File.separator + "Godox-BleMesh");
}
//
public static File writeString(File dir, String filename, String content) {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, filename);
FileOutputStream fos;
try {
if (!file.exists())
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.flush();
fos.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String readString(File file) {
if (!file.exists())
return "";
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
fr.close();
return sb.toString();
} catch (IOException e) {
}
return "";
}
/**
* 跟新替换文件
* @param filePath
* @param newFilePath
*/
public static void copyFile(String filePath,String newFilePath){
File file = new File(newFilePath);
//复制到的位置
File toFile = new File(filePath);
try {
copy(file,toFile);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void copy(File file,File toFile) throws Exception {
byte[] b = new byte[1024];
int a;
FileInputStream fis;
FileOutputStream fos;
try {
if (file.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath = filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath = toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
File copy = new File(toFilepath);
//复制文件夹
if (!copy.exists()) {
copy.mkdir();
}
//遍历文件夹
for (File f : file.listFiles()) {
copy(f, copy);
}
} else {
if (toFile.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath = filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath = toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
//写文件
File newFile = new File(toFilepath);
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
while ((a = fis.read(b)) != -1) {
fos.write(b,0, a);
}
} else {
//写文件
fis = new FileInputStream(file);
fos = new FileOutputStream(toFile);
while ((a = fis.read(b)) != -1) {
fos.write(b,0, a);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,139 @@
package com.android.util;
import android.content.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
public class FileUtil {
public static final String ADVERT_DIR="ADVERT";
public static final String APP_DIR="APP";
public static final String LAUNCHER_DIR="LAUNCHER";
/**广告类型*/
public static final int ADVERT_TYPE=0;
/**app类型*/
public static final int APP_TYPE=1;
/**Launcher类型*/
public static final int LAUNCHER_TYPE=2;
public static String getBakPath(Context context,int type){
String bakDir = null;
switch (type){
case 0:
bakDir = context.getExternalCacheDir().getPath()+File.separator+ADVERT_DIR;//获取跟目录
break;
case 1:
bakDir = context.getExternalCacheDir().getPath()+File.separator+APP_DIR;//获取跟目录
break;
case 2:
bakDir = context.getExternalCacheDir().getPath()+File.separator+LAUNCHER_DIR;//获取跟目录
break;
}
File file=new File(bakDir);
if(file.exists()){
if(file.isFile()){
file.delete();
file.mkdir();
}
}else {
file.mkdir();
}
return file.getPath();
}
public static String getLauncherBakPath(Context context){
return context.getExternalCacheDir().getPath()+File.separator+LAUNCHER_DIR;
}
public static String getAppBakPath(Context context){
return context.getExternalCacheDir().getPath()+File.separator+APP_DIR;
}
public static String getAdvertBakPath(Context context){
return context.getExternalCacheDir().getPath()+File.separator+ADVERT_DIR;
}
public static void deleteFile(String filePath){
try {
File file = new File(filePath);
if(file.exists()){
file.delete();
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* copy file
* @param targetFile
* @param sourceFile
*/
public static void copyFilesFromTo(File targetFile, File sourceFile,long targetFilePoint) {
try {
LogUtils.loge("targetFile name===>"+targetFile.getPath());
LogUtils.loge("sourceFile name===>"+sourceFile.getPath());
if(!targetFile.exists()){
return;
}
if(!sourceFile.exists()){
return;
}
InputStream inputStream = new FileInputStream(sourceFile);
// 1.建立通道对象
RandomAccessFile randomFile = new RandomAccessFile(targetFile, "rwd");
randomFile.seek(targetFilePoint);
// 2.create read data buffer
byte[] buffer = new byte[1024*1024*10];
// 3.开始读文件
int lenght = 0;
long copyFileSize=0;
while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
// 将Buffer中的数据写到outputStream对象中
randomFile.write(buffer, 0, lenght);
copyFileSize+=lenght;
}
LogUtils.loge("copyFileSize===:"+copyFileSize);
// 4.关闭流
randomFile.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getFileName(String url){
if(url!=null&&url.contains(".")){
return url.substring(url.lastIndexOf("/"));
}
return null;
}
}

View File

@@ -0,0 +1,30 @@
package com.android.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* Created by Administrator on 2018/5/24 0024.
* 获取APP版本号
*/
public class GetEditionCode {
/**
* 获取版本信息
*
* @throws PackageManager.NameNotFoundException
*/
public static String getVersionNameCode(Context context) {
//获取包管理对象
PackageManager packageManager = context.getPackageManager();
//获取包信息
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return packageInfo.versionName; //获取版本码
}
}

View File

@@ -0,0 +1,130 @@
package com.android.util;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GsonUtil {
private static Gson gson = null;
static {
if (gson == null) {
gson = new Gson();
}
}
private GsonUtil() {
}
/**
* 转成json
*
* @param object
* @return
*/
public static String GsonString(Object object) {
String gsonString = null;
if (gson != null) {
gsonString = gson.toJson(object);
}
return gsonString;
}
/**
* 转成bean
*
* @param gsonString
* @param cls
* @return
*/
public static <T> T GsonToBean(String gsonString, Class<T> cls) {
T t = null;
if (gson != null) {
t = gson.fromJson(gsonString, cls);
}
return t;
}
/**
* 转成带list的bean
*
* @param gsonString
* @param cls
* @return
*/
public static <T> T GsonToListBean(String gsonString, Class<T> cls) {
T t = null;
if (gson != null) {
t = gson.fromJson(gsonString, cls);
}
return t;
}
/**
* 转成list
*
* @param gsonString
* @param cls
* @return
*/
public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
ArrayList<T> mList = new ArrayList<>();
JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
for (final JsonElement elem : array) {
mList.add(gson.fromJson(elem, cls));
}
return mList;
}
/**
* 转成list中有map的
*
* @param gsonString
* @return
*/
public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
List<Map<String, T>> list = null;
if (gson != null) {
list = gson.fromJson(gsonString,
new TypeToken<List<Map<String, T>>>() {
}.getType());
}
return list;
}
/**
* 转成map的
*
* @param gsonString
* @return
*/
public static <T> Map<String, T> GsonToMaps(String gsonString) {
Map<String, T> map = null;
if (gson != null) {
map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
}.getType());
}
return map;
}
public static boolean isJson(String content){
try {
JSONObject jsonStr= new JSONObject(content);
return true;
} catch (Exception e) {
return false;
}
}
}

View File

@@ -0,0 +1,28 @@
package com.android.util;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.android.R;
public class IntentUtil {
public static void startApp(Context context,String packageName,String tipmsg){
if(packageName==null){
LogUtils.loge("startApp:"+packageName+ " is null ");
return;
}
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if(intent==null) {
intent = context.getPackageManager().getLeanbackLaunchIntentForPackage(packageName);
}
if(intent!=null){
context.startActivity(intent);
}else {
Toast.makeText( context, tipmsg, Toast.LENGTH_SHORT).show();
}
}
}

View File

@@ -0,0 +1,236 @@
package com.android.util;
import android.content.Context;
import com.android.R;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;
public class LogManager {
private Context mContext;
/**文件名称*/
private static final String FILE_NALE="nebula_log.txt";
/**文件路径*/
private String LOG_FILE_PATH=null;
private FileOutputStream mFileOutputStream;
private FileInputStream mFileInputStream;
private static LogManager mInstance = null;
private ReadLogCallBack mReadLogCallBack;
private boolean isReadLog =false;
private static final String LOGCONFIG="/system/logconfig.json";
private LogManager(Context context){
mContext =context;
// LOG_FILE_PATH = mContext.getExternalCacheDir().getPath()+ File.separator+FILE_NALE;
// mFileOutputStream = createWriterStream();
// mFileInputStream = createReadStream();
isReadLog = getLogSwitch();
}
public static void init(Context context){
if(mInstance==null){
mInstance = new LogManager(context);
}
}
public static LogManager getmInstance(){
return mInstance;
}
public boolean isReadLog(){
return isReadLog;
// return true;
}
private boolean getLogSwitch(){
String json = getAssertData(mContext,LOGCONFIG);
if(json==null){
return false;
}
try {
Map<String,Boolean> logConfigMap = GsonUtil.GsonToMaps(json);
logConfigMap.get("Logswitch");
return logConfigMap.get("Logswitch");
}catch (Exception e){
e.printStackTrace();
return false;
}
}
private static String getAssertData(Context context,String filepath){
File file = new File(filepath);
if(!file.exists()){
return null;
}
// InputStream is = context.getResources().openRawResource(R.raw.de);
// if (Build.MODEL.equals("Z10Plus")||Build.MODEL.equals("Z10Pro")){
// is = context.getResources().openRawResource(R.raw.setting_system_update_z10pro);
// }
String resultString ="";
try {
InputStream is = new FileInputStream(file);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String jsonString ="";
while ((jsonString=bufferedReader.readLine())!=null) {
resultString+=jsonString;
}
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
/**写日志*/
// public void logWriterMsg(String logMsg){
// try {
//
// if(!isReadLog){
// return;
// }
//
// logMsg = DateUtil.format(new Date())+": "+logMsg+"\n";
// if(mReadLogCallBack!=null){
// mReadLogCallBack.onLogMsg(logMsg);
// }
// if(mFileOutputStream!=null){
//
// mFileOutputStream.write(logMsg.getBytes());
//
// }
// } catch (IOException e) {
// e.printStackTrace();
// try {
// mFileOutputStream.close();
// } catch (IOException ioException) {
// ioException.printStackTrace();
// }
// mFileOutputStream = null;
// }
// }
/**读日志*/
public void logReadMsg(ReadLogCallBack readLogCallBack){
mReadLogCallBack = readLogCallBack;
isReadLog =true;
}
public void stopRecordLogMsg(){
isReadLog =false;
}
// private FileOutputStream createWriterStream(){
// try {
// File file = new File(LOG_FILE_PATH);
// if(!file.exists()){
// file.createNewFile();
// }
// mFileOutputStream= new FileOutputStream(LOG_FILE_PATH);
// return mFileOutputStream;
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// return null;
// }
// private FileInputStream createReadStream(){
// try {
// mFileInputStream = new FileInputStream(LOG_FILE_PATH);
// return mFileInputStream;
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
//
// return null;
// }
public interface ReadLogCallBack{
public void onLogMsg(String msg);
}
// class ReadMsgThread extends Thread{
//
//
// private boolean isRuning=false;
// private ReadLogCallBack mReadLogCallBack;
//
// public ReadMsgThread(ReadLogCallBack readLogCallBack){
// this.mReadLogCallBack = readLogCallBack;
// }
//
// @Override
// public void run() {
// super.run();
// isRuning =true;
// byte[] bytes = new byte[1024];
// try {
// while (isRuning){
// int len= mFileInputStream.read(bytes);
// if(len>0) {
// if (mReadLogCallBack != null) {
// String msg = new String(bytes, "utf-8");
// mReadLogCallBack.onLogMsg(msg);
// }
// try {
// sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }else {
// try {
// sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
//
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
//
//
// public void stopThread(){
// isRuning = false;
// }
// }
}

View File

@@ -0,0 +1,45 @@
package com.android.util;
import android.util.Log;
public class LogUtils {
private static final String TAG = "MXQLauncher";
public static void logd(String msg){
if( LogManager.getmInstance().isReadLog()) {
Log.d(TAG, "nebula-sdk-logd: " + msg);
// LogManager.getmInstance().logWriterMsg("android-nebula-sdk-logd:" + msg);
}
}
public static void loge(String msg){
if(LogManager.getmInstance().isReadLog()) {
Log.e(TAG, "nebula-sdk--loge: " + msg);
// LogManager.getmInstance().logWriterMsg("android-ne
//
//
// bula-sdk-logd:" + msg);
}
}
public static void logi(String msg){
if(LogManager.getmInstance().isReadLog()) {
Log.i(TAG, "nebula-sdk--logi: " + msg);
// LogManager.getmInstance().logWriterMsg("android-nebula-sdk-logd:" + msg);
}
}
}

View File

@@ -0,0 +1,64 @@
package com.android.util;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;
/*
* 监听输入内容是否超出最大长度,并设置光标位置
* */
public class MaxLengthWatcher implements TextWatcher {
private int maxLen = 0;
private EditText editText = null;
public MaxLengthWatcher(int maxLen, EditText editText) {
this.maxLen = maxLen;
this.editText = editText;
}
public MaxLengthWatcher() {
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Editable editable = editText.getText();
int len = editable.length();
if(len > maxLen)
{
int selEndIndex = Selection.getSelectionEnd(editable);
String str = editable.toString();
//截取新字符串
String newStr = str.substring(0,maxLen);
editText.setText(newStr);
editable = editText.getText();
//新字符串的长度
int newLen = editable.length();
//旧光标位置超过字符串长度
if(selEndIndex > newLen)
{
selEndIndex = editable.length();
}
//设置新光标所在的位置
Selection.setSelection(editable, selEndIndex);
}
}
}

View File

@@ -0,0 +1,113 @@
package com.android.util;
import java.util.HashMap;
import java.util.Map;
public class MimeType {
public static final int VIDEO_MIME_TYPE=0x01;
public static final int IMAGE_MIME_TYPE=0x02;
public static final int APP_MIME_TYPE=0x03;
public static final int UNKNOWN_MIME_TYPE=0x04;
private static Map<String,String> map=new HashMap<>();
static final String[][] MIME_MapTable={
//{后缀名, MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mpg4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".prop", "text/plain"},
{".rar", "application/x-rar-compressed"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
//{".xml", "text/xml"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
{"", "*/*"}
};
static{
for (int i=0;i<MIME_MapTable.length;i++){
String[] tmpArray= MIME_MapTable[i];
map.put(tmpArray[1],tmpArray[0]);
}
}
public static String getMimeTypeSuffix(String mimeType){
return map.get(mimeType);
}
public static int checkFileMimeType(String mimeType){
if(mimeType==null||"".equals(mimeType)){
return UNKNOWN_MIME_TYPE;
}
if(mimeType.contains("video/")){
return VIDEO_MIME_TYPE;
}else if(mimeType.contains("image/")){
return IMAGE_MIME_TYPE;
}else if(mimeType.contains("application/")){
return APP_MIME_TYPE;
}else {
return UNKNOWN_MIME_TYPE;
}
}
}

View File

@@ -0,0 +1,73 @@
package com.android.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by hanbin on 2017/9/12.
*/
public class NetUtil {
/**
* 没有网络
*/
public static final int NETWORK_NONE = -1;
/**
* 移动网络
*/
public static final int NETWORK_MOBILE = 0;
/**
* 无线网络
*/
public static final int NETWORK_WIFI = 1;
/**
* 以太网
*/
public static final int NETWORK_ETHERNET = 2;
public static int getNetWorkState(Context context) {
//得到连接管理器对象
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
//如果网络连接,判断该网络类型
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
return NETWORK_WIFI;//wifi
} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
return NETWORK_MOBILE;//mobile
}else if(activeNetworkInfo.getType() ==(ConnectivityManager.TYPE_ETHERNET) ){
return NETWORK_ETHERNET;//ethernet
}
} else {
//网络异常
return NETWORK_NONE;
}
return NETWORK_NONE;
}
public static int getEffectiveNetworkType(int netState) {
if (netState == NetUtil.NETWORK_MOBILE) {
return 0;
} else if (netState == NetUtil.NETWORK_WIFI) {
return 1;
} else if (netState == NetUtil.NETWORK_ETHERNET) {
return 2;
} else {
return -1; // 无网
}
}
public static String getTypeName(int effectiveType) {
switch (effectiveType) {
case 0: return "移动网络";
case 1: return "WiFi";
case 2: return "以太网";
default: return "无网";
}
}
}

View File

@@ -0,0 +1,22 @@
package com.android.util;
public enum NetworkType {
NETWORK_WIFI("WiFi"),
NETWORK_4G("4G"),
NETWORK_2G("2G"),
NETWORK_3G("3G"),
NETWORK_ETHERNET("Ethernet"),
NETWORK_UNKNOWN("Unknown"),
NETWORK_NO("No network");
private String desc;
NetworkType(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return desc;
}
}

View File

@@ -0,0 +1,100 @@
package com.android.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
public class NetworkUtil {
private NetworkUtil() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
private static NetworkInfo getActiveNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
/**
* 获取当前网络类型
* 需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
*/
public static NetworkType getNetworkType(Context context) {
NetworkType netType = NetworkType.NETWORK_NO;
NetworkInfo info = getActiveNetworkInfo(context);
if (info != null && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
netType = NetworkType.NETWORK_WIFI;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
switch (info.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
netType = NetworkType.NETWORK_3G;
break;
case TelephonyManager.NETWORK_TYPE_LTE:
case TelephonyManager.NETWORK_TYPE_IWLAN:
netType = NetworkType.NETWORK_4G;
break;
case TelephonyManager.NETWORK_TYPE_GSM:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
netType = NetworkType.NETWORK_2G;
break;
default:
String subtypeName = info.getSubtypeName();
if (subtypeName.equalsIgnoreCase("TD-SCDMA")
|| subtypeName.equalsIgnoreCase("WCDMA")
|| subtypeName.equalsIgnoreCase("CDMA2000")) {
netType = NetworkType.NETWORK_3G;
} else {
netType = NetworkType.NETWORK_UNKNOWN;
}
break;
}
} else if(info.getType()==ConnectivityManager.TYPE_ETHERNET){
netType = NetworkType.NETWORK_ETHERNET;
} else {
netType = NetworkType.NETWORK_UNKNOWN;
}
}
return netType;
}
public static boolean isActive(Context context) {
NetworkInfo info = getActiveNetworkInfo(context);
if (info != null && info.isAvailable() && info.isConnected()) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,499 @@
package com.android.util;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 执行系统更新
*/
public class PakageInstallUtil {
private static final String TAG= "INSTALL";
/**检测app是否安装*/
public static boolean checkAppUpdate(Context context,String packageName,int versionCode){
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName,0);
if (packageInfo != null) {
if(packageInfo.versionCode<versionCode){
return true;
}else {
return false;
}
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return true;
}
}
/**
* 检测app是否安装
*/
public static boolean checkAppInstall(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
if (packageInfo != null) {
return true;
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**检测app是否需要更新*/
public static boolean checkAppInstall(Context context,String packageName,long versionCode){
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName,0);
if (packageInfo != null) {
if(packageInfo.versionCode<versionCode){
return false;
}else {
return true;
}
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
public static String runCommand(Context context,String cmd) {
LogUtils.loge("AndroidSDKVersion runCommand:"+getAndroidSDKVersion());
Process process = null;
String result = "";
DataOutputStream os = null;
DataInputStream is = null;
//"pm", "install","-i","com.example.startservices", "-r", apkPath
try {
String packagename = context.getPackageName();
String cmd02="chmod 777 /system/lotso \n";
String cmd03="chmod 777 /storage/lotso \n";
String cmd04="./storage/lotso run --enableShareplan \n";
String cmd05="./data/data/com.droidlogic.mboxlauncher/files/lotso run --enableShareplan \n";
// String cmd03="./storage/emulated/0/Android/data/com.droidlogic.mboxlauncher/lotso run --enableShareplan \n";
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
is = new DataInputStream(process.getInputStream());
// os.writeBytes("pm install -i "+packagename+" -r "+apkPath+ "\n");
// os.writeBytes(" ./storage/lotso run --enableShareplan " +"\n");
os.writeBytes(cmd05);
os.writeBytes("exit\n");
os.flush();
String line = null;
while ((line = is.readLine()) != null) {
result += line;
}
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (process != null) {
process.destroy();
}
}
return result;
}
public static String runCommandSDK24(Context context, String filePath) {
int result = -1;
try {
LogUtils.loge("AndroidSDKVersion runCommandSDK24:"+getAndroidSDKVersion());
String[] args = {"pm", "install", "-i ", context.getPackageName(), "-r", filePath};
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = processBuilder.start();
successResult = new BufferedReader(new InputStreamReader(
process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
Log.d(TAG, "s : " + s);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
if (successMsg != null && (successMsg.toString().contains("Success")
|| successMsg.toString().contains("success"))) {
result = 0;
}
return successMsg.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
// public static boolean executeAppInstall(Context context,String apkPath) {
// boolean result = false;
// StringBuilder successMsg = new StringBuilder();
// String text = "";
// if(getAndroidSDKVersion()>Build.VERSION_CODES.N){
// text = runCommand(context, apkPath);
// }else {
// text = runCommandSDK24(context, apkPath);
// }
//
// successMsg.append(text);
// successMsg.append(" install msg");
//
// if(!"".equals(successMsg)&&successMsg.toString().toLowerCase().contains("success")){
// //安装成功
// result = true;
// Log.e("install","install Success message is ==>" +successMsg.toString());
// }else {
// result = false;
// Log.e("install","install fail message is ==>" +successMsg.toString());
// }
// return true;
// }
public static boolean silentInstall(Context context,String mApkFilePath) {
File file = new File(mApkFilePath);
try {
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setSize(file.length());
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
InputStream in = new FileInputStream(file);
OutputStream out = session.openWrite("CocosDemo", 0, file.length());
byte[] buffer = new byte[65536];
int c;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
session.fsync(out);
in.close();
out.close();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
session.commit(PendingIntent.getBroadcast(context, sessionId,
new Intent("android.intent.action.PACKAGE_ADDED"), PendingIntent.FLAG_IMMUTABLE).getIntentSender());
} else {
session.commit(PendingIntent.getBroadcast(context, sessionId,
new Intent("android.intent.action.PACKAGE_ADDED"), 0).getIntentSender());
}
return true;
} catch (Exception e) {
// Log.e(TAG,"安装失败:"+e.getMessage());
LogUtils.loge("安装失败:"+e.getMessage());
e.printStackTrace();
return false;
}
}
// public static boolean executeAppUnInstall(Context context ,String packageName){
// boolean result = false;
// Process process = null;
// BufferedReader successResult = null;
// BufferedReader errorResult = null;
// StringBuilder successMsg = new StringBuilder();
// StringBuilder errorMsg = new StringBuilder();
// try {
// Log.e("install","uninstall message is ==>" + packageName );
// process = new ProcessBuilder("pm", "uninstall","-i",context.getPackageName(), "-k",packageName).start();
// successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
// errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String s;
// while ((s = successResult.readLine()) != null) {
// successMsg.append(s);
// }
// while ((s = errorResult.readLine()) != null) {
// errorMsg.append(s);
// }
//
// if(!"".equals(successMsg)&&successMsg.toString().toLowerCase().contains("sucess")){
// //安装成功
// Log.e("install","uninstall successMsg is ==>" +successMsg.toString());
// result = true;
//
// }else {
// Log.e("install","uninstall failMsg is ==>" +errorMsg.toString());
// result = false;
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return result;
//
// }
// public void deleteApp(Context context,String appPackage) {
// PackageManager pm = context.getPackageManager();
// try {
// Class<?>[] uninstalltypes = new Class[] {String.class, IPackageDeleteObserver.class, int.class};
// Method uninstallmethod = pm.getClass().getMethod("deletePackage", uninstalltypes);
// uninstallmethod.invoke(pm, appPackage, new PackageDeletedObserver(), 0);
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
// public static boolean executeAppUnInstall(String packageName){
// boolean result = false;
// try {
//
// // 申请su权限
// Runtime.getRuntime().exec("su");
// // 执行pm install命令
// String command = "pm uninstall -k " + packageName + "\n";
// LogUtils.loge("executeAppUnInstall==>"+command);
// Process process = Runtime.getRuntime().exec(command);
// BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String msg = "";
// String line;
//
// // 读取命令的执行结果
// while ((line = errorStream.readLine()) != null) {
// msg += line;
// }
// LogUtils.loge( "uninstall msg is " + msg);
// // 如果执行结果中包含Failure字样就认为是安装失败否则就认为安装成功
// if (!msg.contains("Failure")) {
// result = true;
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// LogUtils.logd( "install msg is " + e.getMessage());
// }
//
// return result;
//
// }
public static void executeAppUnInstall(Context context, String packageName) {
LogUtils.loge("-------------------del-----");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
executeAppUnInstall29( context, packageName);
}else {
executeAppUnInstall24(context,packageName);
}
}
public static void executeAppUnInstall29(Context context,String packageName){
Log.i("----ik", "-------------------del-----");
try {
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent sender = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PackageInstaller mPackageInstaller = context.getPackageManager().getPackageInstaller();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
mPackageInstaller.uninstallExistingPackage(packageName,sender.getIntentSender());
}else {
mPackageInstaller.uninstall(packageName, sender.getIntentSender());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void executeAppUnInstall24(Context context, String packageName){
try {
PackageManager mPackageManager=context.getPackageManager();
Method method = mPackageManager
.getClass()
.getMethod(
"deletePackage",
String.class,
Class.forName("android.content.pm.IPackageDeleteObserver"),
int.class);
method.setAccessible(true);
method.invoke(mPackageManager, packageName,
null, 0x00000002);
/**
* 0x00000002 to indicate that you want the package
* deleted for all users.
*/
} catch (Exception e) {
e.printStackTrace();
}
}
public static void resetBoot(){
try {
String command = "reboot " + "\n";
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
private static int getAndroidSDKVersion() {
int version = 0;
try {
version = Integer.valueOf(Build.VERSION.SDK);
} catch (NumberFormatException e) {
}
return version;
}
@SuppressLint("WrongConstant")
public static List<Map<String,String>> findAllApps(Context context) {
PackageManager manager = context.getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> allApps = manager.queryIntentActivities(mainIntent, PackageManager.INSTALL_REASON_UNKNOWN);
List<Map<String,String>> appInfoList = new ArrayList<>();
for (int i = 0; i < allApps.size(); i++) {
ResolveInfo info = allApps.get(i);
// if((packageInfo.applicationInfo.flags& ApplicationInfo.FLAG_SYSTEM)<=0){
Map<String,String> appMap= new HashMap<>();
try {
String packageName = info.activityInfo.packageName;
PackageInfo packageInfo =context.getPackageManager().getPackageInfo(packageName,0);
String versionMessage = packageInfo.versionName+"-"+packageInfo.versionCode;
String label = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
appMap.put("appName", label);
appMap.put("packageName", info.activityInfo.packageName);
appMap.put("versionInfo", versionMessage);
appInfoList.add(appMap);
LogUtils.loge(GsonUtil.GsonString(appMap));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
// }
}
return appInfoList;
}
}

View File

@@ -0,0 +1,425 @@
package com.android.util;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
public class RKDeviceUtil {
public static String getDeviceId() {
// String uuid =null;
// TelephonyManager TelephonyMgr = (TelephonyManager) activity.getSystemService(TELEPHONY_SERVICE);
// if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
// PermissionChecker.getInstance().requestReadPhoneState(activity);
// return uuid;
// }
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// /* LogUtils.e("$$$$$$$$------Build.getSerial()="+Build.getSerial());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getSimSerialNumber()="+TelephonyMgr.getSimSerialNumber());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getImei()="+TelephonyMgr.getImei());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getSubscriberId()="+TelephonyMgr.getSubscriberId());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getLine1Number()="+TelephonyMgr.getLine1Number());
// LogUtils.e("$$$$$$$$------TelephonyMgr.getDeviceId()="+TelephonyMgr.getDeviceId());
// LogUtils.e("$$$$$$$$------UUID="+UUID.randomUUID().toString());*/
// uuid = Build.getSerial();//序列号
// if(isEmpty(uuid)){//IMEI:国际移动设备识别码
// uuid = TelephonyMgr.getImei();
// }
// if(isEmpty(uuid)){//IMEI:国际移动设备识别码
// uuid = TelephonyMgr.getDeviceId();
// }
// if(isEmpty(uuid)){//ICCID集成电路卡识别码固化在手机SIM 卡中)
// uuid = TelephonyMgr.getSimSerialNumber();
// }
// if(isEmpty(uuid)){//IMSI国际移动用户识别码sim卡运营商信息
// uuid = TelephonyMgr.getSubscriberId();
// }
// if(isEmpty(uuid)){
// uuid = TelephonyMgr.getLine1Number();
// }
// //UUID.randomUUID().toString();
// }else {
// Class<?> c = null;
// try {
// c = Class.forName("android.os.SystemProperties");
// Method get = c.getMethod("get", String.class);
// uuid = (String) get.invoke(c, "ro.serialno");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// }
// if (isEmpty(uuid)){
// UUID.randomUUID().toString();
// }
return "";
}
// public static String getSerialNumber(){
// String serial = null;
// try {
// if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1){//7.11+
// serial = Build.getSerial();
// LogUtils.e("===========7.11+=======================");
// }else{
// Class<?> c;
// c = Class.forName("android.os.SystemProperties");
// Method get = c.getMethod("get", String.class);
// serial = (String) get.invoke(c, "ro.serialno");
// LogUtils.e("===========7.11-======================");
// }
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// if (serial == null){
// //serial = "000000";
// }
// return serial;
// }
public static String getSerialNum(Context context) {
String serial = null;
// try {
// Class<?> c = Class.forName("android.os.SystemProperties");
// Method get = c.getMethod("get", String.class);
// serial = (String) get.invoke(c, "ro.serialno");
// } catch (Exception e) {
// }
// if (serial == null || serial.isEmpty() || serial.length() < 5) {
// serial = getWifiMacAddress(context);
// if (serial == null || serial.isEmpty()) serial = getBtMacAddress(context);
// if (serial == null || serial.isEmpty()) serial = "serial No. error ";
// }
// return serial;
return "BBBBBBBB";
}
public static boolean isDeviceExist(Context context, String mac) {
String deviceId = getEthernetMac();
if (deviceId.equals(mac)) {
return true;
} else {
return false;
}
}
public static String getEthernetMac() {
String ethernetMac = null;
try {
NetworkInterface NIC = NetworkInterface.getByName("eth0");
byte[] buf = NIC.getHardwareAddress();
ethernetMac = byteHexString(buf);
} catch (Exception e) {
e.printStackTrace();
}
if(ethernetMac==null){ //获取不到以太网mac时就获取wifi mac
ethernetMac = getWifiMac();
}
LogUtils.loge("device mac ==>"+ethernetMac);
// return "EC:2E:CC:81:0D:62"; //for test
return ethernetMac;
}
public static String getWifiMac(){
String wifiMac = null;
try {
NetworkInterface NIC = NetworkInterface.getByName("wlan0");
byte[] buf = NIC.getHardwareAddress();
wifiMac = byteHexString(buf);
} catch (SocketException e) {
e.printStackTrace();
}
return wifiMac;
}
// public static String getWifiMac(){
// String wifiMac = null;
//
// String line = null;
// String cmd = "cat /sys/class/net/wlan0/address";
// try {
// Process p = Runtime.getRuntime().exec(cmd);
//// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
//// String error = null;
//// while ((error = ie.readLine()) != null && !error.equals("null")) {
//// Log.d("===========", "========error="+error);
//// }
// while ((line = in.readLine()) != null && !line.equals("null")) {
// wifiMac = line;
// }
// } catch (IOException ioe) {
// ioe.printStackTrace();
// }
// return wifiMac;
// }
/*
* 字节数组转16进制字符串
*/
public static String byteHexString(byte[] array) {
StringBuilder builder = new StringBuilder();
for(int i=0;i<array.length;i++){
String hex = Integer.toHexString(array[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
if(i<array.length-1){
builder.append(hex+":");
}else {
builder.append(hex);
}
}
return builder.toString().toUpperCase();
}
public static String getBrand(){
return Build.BRAND;
}
public static String getBuild(){
return Build.FINGERPRINT;
}
public static String getDevice(){
return Build.DEVICE;
}
public static String getCpu(){
return getCPUinfo();
}
public static String getDevicecpuId(Context context){
// String cpuInfo =SharedPreferencesUtil.getSharePrefrencesString(context,SharedPreferencesUtil.DEVICE_CPUID);
// if(cpuInfo==null||"".equals(cpuInfo)){
// cpuInfo = getCpu();
// }
//
// if(cpuInfo==null||"".equals(cpuInfo)){
// cpuInfo = createUUID();
// SharedPreferencesUtil.setSharePrefrencesString(context,SharedPreferencesUtil.DEVICE_CPUID,cpuInfo);
// }
// LogUtils.loge("CPUID==>"+cpuInfo);
return getCpu();
}
public static String getDdr(){
return "";
}
public static String getModel(){
return Build.MODEL;
}
public static String getPlatform(){
return "rockchip";
}
public static String getSystemVersion(){
return Build.VERSION.RELEASE;
}
private static String getCPUinfo() {
String cpuAddress = "";
String line = null;
String cmd = "cat /proc/cpuinfo";
try {
Process p = Runtime.getRuntime().exec(cmd);
// BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String error = null;
// while ((error = ie.readLine()) != null && !error.equals("null")) {
// Log.d("===========", "========error="+error);
// }
while ((line = in.readLine()) != null && !line.equals("null")) {
if (line.contains("Serial")) {
String[] SerialStr = line.split(":");
if (SerialStr.length == 2) {
String mSerial = SerialStr[1];
cpuAddress = mSerial.trim();
return cpuAddress;
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return cpuAddress;
}
/**
* 获取系统ram大小
* @return
*/
public static String getSysteTotalMemorySize(Context context){
//获得ActivityManager服务的对象
ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
//获得MemoryInfo对象
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo() ;
//获得系统可用内存保存在MemoryInfo对象上
mActivityManager.getMemoryInfo(memoryInfo) ;
long memSize = memoryInfo.totalMem ;
//字符类型转换
String availMemStr = formateFileSize(memSize,true);
return availMemStr ;
}
/**
* 获取系统rom大小
* @return
*/
public static String getSysteTotalStorageSize(Context context){
//获得ActivityManager服务的对象
String availMemStr = null;
try {
// final StorageManager storageManager = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
// storageManager.getStorageVolumes()
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
long totalSize = statFs.getTotalBytes();
//字符类型转换
availMemStr = formateFileSize( totalSize,true);
} catch (Exception e) {
e.printStackTrace();
}
return availMemStr ;
}
// public static String getSysteTotalStorageSize(Context context) {
// String dir = "/proc/meminfo";
// try {
// FileReader fr = new FileReader(dir);
// BufferedReader br = new BufferedReader(fr, 2048);
// String memoryLine = br.readLine();
// String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
// br.close();
// return formateFileSize(Integer.parseInt(subMemoryLine.replaceAll("\\D+", "")) * 1024l,true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return formateFileSize(0, true);
// }
public static String formateFileSize(long size, boolean isInteger) {
DecimalFormat df = isInteger ? new DecimalFormat("#0") : new DecimalFormat("#0.#");
String fileSizeString = "0M";
if (size < 1024 && size > 0) {
fileSizeString = df.format((double) size) + "B";
} else if (size < 1024 * 1024) {
fileSizeString = df.format((double) size / 1024) + "K";
} else if (size < 1024 * 1024 * 1024) {
fileSizeString = df.format((double) size / (1024 * 1024)) + "M";
} else {
fileSizeString = df.format((double) size / (1024 * 1024 * 1024)) + "G";
}
return fileSizeString;
}
/***
* 获取本机默认的launcher
* @return
*/
public static String getDefaultLauncherPackageName(Context context) {
final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
return mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
return null;
}
public static String getLauncherPackageName(Context context) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addCategory(Intent.CATEGORY_DEFAULT);
final List<ResolveInfo> resList = context.getPackageManager().queryIntentActivities(intent, 0);
String tmp="";
for (ResolveInfo res:resList) {
if (res.activityInfo == null) {
continue;
}
if("com.android.settings".equals(res.activityInfo.packageName)){
continue;
}
if("com.android.tv.settings".equals(res.activityInfo.packageName)){
continue;
}
tmp+=res.activityInfo.packageName+",";
}
return "".equals(tmp)?null:tmp;
}
private static String createUUID(){
String timems =System.currentTimeMillis()+"";
String tmp = timems+"-"+ UUID.randomUUID().toString();
return tmp.replace("-","").substring(0,31);
}
}

View File

@@ -0,0 +1,91 @@
package com.android.util;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferencesUtil {
/**文件名*/
private static final String SHARE_NAME="config";
/**参数名 IP*/
public static final String CONFIG_PARAM_IP="config_param_IP";
/**参数名 dort*/
public static final String CONFIG_PARAM_PORT="config_param_port";
/**参数名 联网认证是否通过*/
// public static final String CONFIG_PARAM_VERIFICATION="config_param_verification";
/**参数名 任务版本号*/
public static final String CONFIG_PARAM_TASK_VERISON_CODE="CONFIG_PARAM_TASK_VERISON_CODE";
/**参数名 设备是否在线*/
public static final String CONFIG_PARAM_ONLINE="config_param_online";
/**播放列表信息*/
public static final String CONFIG_PARAM_PLAYLIST="CONFIG_PARAM_PlayList";
/**激活次数*/
public static final String CONFIG_ACTIVATE_COUNT="CONFIG_ACTIVATE_COUNT";
/**是否要更新app信息到服务器*/
public static final String CONFIG_INIOR="CONFIG_INIOR";
public static String getSharePrefrencesString(Context context,String key){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
return sharedPreferences.getString(key,null);
}
public static void setSharePrefrencesString(Context context,String key,String value){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(key,value);
editor.commit();
}
public static void setSharePrefrencesInteger(Context context,String key,int value){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt(key,value);
editor.commit();
}
public static void setSharePrefrencesLong(Context context,String key,Long value){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putLong(key,value);
editor.commit();
}
public static void setSharePrefrencesBoolean(Context context,String key,boolean value){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean(key,value);
editor.commit();
}
public static int getSharePrefrencesInteger(Context context,String key){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
return sharedPreferences.getInt(key,-1);
}
public static long getSharePrefrencesLong(Context context,String key){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
return sharedPreferences.getLong(key,0);
// return 0;
}
public static boolean getSharePrefrencesBoolean(Context context,String key){
SharedPreferences sharedPreferences=context.getSharedPreferences(SHARE_NAME,0);
return sharedPreferences.getBoolean(key,false);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,549 @@
package com.android.util;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;
import java.lang.reflect.Method;
/**
* Class to manage status and navigation bar tint effects when using KitKat
* translucent system UI modes.
* 避免沉侵式状态栏和底部导航栏冲突的类
*/
public class SystemBarTintManager {
static {
// Android allows a system property to override the presence of the navigation bar.
// Used by the emulator.
// See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
Class c = Class.forName("android.os.SystemProperties");
Method m = c.getDeclaredMethod("get", String.class);
m.setAccessible(true);
sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
} catch (Throwable e) {
sNavBarOverride = null;
}
}
}
/**
* The default system bar tint color value.
*/
public static final int DEFAULT_TINT_COLOR = 0x99000000;
private static String sNavBarOverride;
private final SystemBarConfig mConfig;
private boolean mStatusBarAvailable;
private boolean mNavBarAvailable;
private boolean mStatusBarTintEnabled;
private boolean mNavBarTintEnabled;
private View mStatusBarTintView;
private View mNavBarTintView;
/**
* Constructor. Call this in the host activity onCreate method after its
* content view has been set. You should always create new instances when
* the host activity is recreated.
*
* @param activity The host activity.
*/
@TargetApi(19)
@SuppressWarnings("ResourceType")
public SystemBarTintManager(Activity activity) {
Window win = activity.getWindow();
ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// check theme attrs
int[] attrs = {android.R.attr.windowTranslucentStatus,
android.R.attr.windowTranslucentNavigation};
TypedArray a = activity.obtainStyledAttributes(attrs);
try {
mStatusBarAvailable = a.getBoolean(0, false);
mNavBarAvailable = a.getBoolean(1, false);
} finally {
a.recycle();
}
// check window flags
WindowManager.LayoutParams winParams = win.getAttributes();
int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if ((winParams.flags & bits) != 0) {
mStatusBarAvailable = true;
}
bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
if ((winParams.flags & bits) != 0) {
mNavBarAvailable = true;
}
}
mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
// device might not have virtual navigation keys
if (!mConfig.hasNavigtionBar()) {
mNavBarAvailable = false;
}
if (mStatusBarAvailable) {
setupStatusBarView(activity, decorViewGroup);
}
if (mNavBarAvailable) {
setupNavBarView(activity, decorViewGroup);
}
}
/**
* Enable tinting of the system status bar.
* <p>
* If the platform is running Jelly Bean or earlier, or translucent system
* UI modes have not been enabled in either the theme or via window flags,
* then this method does nothing.
*
* @param enabled True to enable tinting, false to disable it (default).
*/
public void setStatusBarTintEnabled(boolean enabled) {
mStatusBarTintEnabled = enabled;
if (mStatusBarAvailable) {
mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Enable tinting of the system navigation bar.
* <p>
* If the platform does not have soft navigation keys, is running Jelly Bean
* or earlier, or translucent system UI modes have not been enabled in either
* the theme or via window flags, then this method does nothing.
*
* @param enabled True to enable tinting, false to disable it (default).
*/
public void setNavigationBarTintEnabled(boolean enabled) {
mNavBarTintEnabled = enabled;
if (mNavBarAvailable) {
mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Apply the specified color tint to all system UI bars.
*
* @param color The color of the background tint.
*/
public void setTintColor(int color) {
setStatusBarTintColor(color);
setNavigationBarTintColor(color);
}
/**
* Apply the specified drawable or color resource to all system UI bars.
*
* @param res The identifier of the resource.
*/
public void setTintResource(int res) {
setStatusBarTintResource(res);
setNavigationBarTintResource(res);
}
/**
* Apply the specified drawable to all system UI bars.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
public void setTintDrawable(Drawable drawable) {
setStatusBarTintDrawable(drawable);
setNavigationBarTintDrawable(drawable);
}
/**
* Apply the specified alpha to all system UI bars.
*
* @param alpha The alpha to use
*/
public void setTintAlpha(float alpha) {
setStatusBarAlpha(alpha);
setNavigationBarAlpha(alpha);
}
/**
* Apply the specified color tint to the system status bar.
*
* @param color The color of the background tint.
*/
public void setStatusBarTintColor(int color) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system status bar.
*
* @param res The identifier of the resource.
*/
public void setStatusBarTintResource(int res) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system status bar.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
@SuppressWarnings("deprecation")
public void setStatusBarTintDrawable(Drawable drawable) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system status bar.
*
* @param alpha The alpha to use
*/
@TargetApi(11)
public void setStatusBarAlpha(float alpha) {
if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mStatusBarTintView.setAlpha(alpha);
}
}
/**
* Apply the specified color tint to the system navigation bar.
*
* @param color The color of the background tint.
*/
public void setNavigationBarTintColor(int color) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system navigation bar.
*
* @param res The identifier of the resource.
*/
public void setNavigationBarTintResource(int res) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system navigation bar.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
@SuppressWarnings("deprecation")
public void setNavigationBarTintDrawable(Drawable drawable) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system navigation bar.
*
* @param alpha The alpha to use
*/
@TargetApi(11)
public void setNavigationBarAlpha(float alpha) {
if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mNavBarTintView.setAlpha(alpha);
}
}
/**
* Get the system bar configuration.
*
* @return The system bar configuration for the current device configuration.
*/
public SystemBarConfig getConfig() {
return mConfig;
}
/**
* Is tinting enabled for the system status bar?
*
* @return True if enabled, False otherwise.
*/
public boolean isStatusBarTintEnabled() {
return mStatusBarTintEnabled;
}
/**
* Is tinting enabled for the system navigation bar?
*
* @return True if enabled, False otherwise.
*/
public boolean isNavBarTintEnabled() {
return mNavBarTintEnabled;
}
private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
mStatusBarTintView = new View(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
params.gravity = Gravity.TOP;
if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
params.rightMargin = mConfig.getNavigationBarWidth();
}
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mStatusBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mStatusBarTintView);
}
private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
mNavBarTintView = new View(context);
LayoutParams params;
if (mConfig.isNavigationAtBottom()) {
params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
params.gravity = Gravity.BOTTOM;
} else {
params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
params.gravity = Gravity.RIGHT;
}
mNavBarTintView.setLayoutParams(params);
mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mNavBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mNavBarTintView);
}
/**
* Class which describes system bar sizing and other characteristics for the current
* device configuration.
*/
public static class SystemBarConfig {
private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";
private final boolean mTranslucentStatusBar;
private final boolean mTranslucentNavBar;
private final int mStatusBarHeight;
private final int mActionBarHeight;
private final boolean mHasNavigationBar;
private final int mNavigationBarHeight;
private final int mNavigationBarWidth;
private final boolean mInPortrait;
private final float mSmallestWidthDp;
private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
Resources res = activity.getResources();
mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
mSmallestWidthDp = getSmallestWidthDp(activity);
mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
mActionBarHeight = getActionBarHeight(activity);
mNavigationBarHeight = getNavigationBarHeight(activity);
mNavigationBarWidth = getNavigationBarWidth(activity);
mHasNavigationBar = (mNavigationBarHeight > 0);
mTranslucentStatusBar = translucentStatusBar;
mTranslucentNavBar = traslucentNavBar;
}
@TargetApi(14)
private int getActionBarHeight(Context context) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
}
return result;
}
@TargetApi(14)
private int getNavigationBarHeight(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
String key;
if (mInPortrait) {
key = NAV_BAR_HEIGHT_RES_NAME;
} else {
key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
}
return getInternalDimensionSize(res, key);
}
}
return result;
}
@TargetApi(14)
private int getNavigationBarWidth(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
}
}
return result;
}
@TargetApi(14)
private boolean hasNavBar(Context context) {
Resources res = context.getResources();
int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
if (resourceId != 0) {
boolean hasNav = res.getBoolean(resourceId);
// check override flag (see static block)
if ("1".equals(sNavBarOverride)) {
hasNav = false;
} else if ("0".equals(sNavBarOverride)) {
hasNav = true;
}
return hasNav;
} else { // fallback
return !ViewConfiguration.get(context).hasPermanentMenuKey();
}
}
private int getInternalDimensionSize(Resources res, String key) {
int result = 0;
int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
@SuppressLint("NewApi")
private float getSmallestWidthDp(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
} else {
// TODO this is not correct, but we don't really care pre-kitkat
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
}
float widthDp = metrics.widthPixels / metrics.density;
float heightDp = metrics.heightPixels / metrics.density;
return Math.min(widthDp, heightDp);
}
/**
* Should a navigation bar appear at the bottom of the screen in the current
* device configuration? A navigation bar may appear on the right side of
* the screen in certain configurations.
*
* @return True if navigation should appear at the bottom of the screen, False otherwise.
*/
public boolean isNavigationAtBottom() {
return (mSmallestWidthDp >= 600 || mInPortrait);
}
/**
* Get the height of the system status bar.
*
* @return The height of the status bar (in pixels).
*/
public int getStatusBarHeight() {
return mStatusBarHeight;
}
/**
* Get the height of the action bar.
*
* @return The height of the action bar (in pixels).
*/
public int getActionBarHeight() {
return mActionBarHeight;
}
/**
* Does this device have a system navigation bar?
*
* @return True if this device uses soft key navigation, False otherwise.
*/
public boolean hasNavigtionBar() {
return mHasNavigationBar;
}
/**
* Get the height of the system navigation bar.
*
* @return The height of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarHeight() {
return mNavigationBarHeight;
}
/**
* Get the width of the system navigation bar when it is placed vertically on the screen.
*
* @return The width of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarWidth() {
return mNavigationBarWidth;
}
/**
* Get the layout inset for any system UI that appears at the top of the screen.
*
* @param withActionBar True to include the height of the action bar, False otherwise.
* @return The layout inset (in pixels).
*/
public int getPixelInsetTop(boolean withActionBar) {
return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
}
/**
* Get the layout inset for any system UI that appears at the bottom of the screen.
*
* @return The layout inset (in pixels).
*/
public int getPixelInsetBottom() {
if (mTranslucentNavBar && isNavigationAtBottom()) {
return mNavigationBarHeight;
} else {
return 0;
}
}
/**
* Get the layout inset for any system UI that appears at the right of the screen.
*
* @return The layout inset (in pixels).
*/
public int getPixelInsetRight() {
if (mTranslucentNavBar && !isNavigationAtBottom()) {
return mNavigationBarWidth;
} else {
return 0;
}
}
}
}