Android版本更新代码
16lz
2021-12-20
ApkUtils
/** * * App相关辅助类 * Created by kenway on 17/3/9 18:15 * Email : xiaokai090704@126.com */public class ApkUtils { private ApkUtils(){ /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 获取应用程序名称 */ public static String getAppName(Context context){ try { PackageManager manager= context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(),0); int labeRes= info.applicationInfo.labelRes; return context.getResources().getString(labeRes); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * get App versionName * * @param context * @return 当前应用的版本名称 */ public static String getVersionName(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); return packageInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * get App versionCode * @param context * @return 当前应用的版本Code */ public static int getVersionCode(Context context){ PackageManager packageManager=context.getPackageManager(); PackageInfo packageInfo; int versionCode = 0; try { packageInfo=packageManager.getPackageInfo(context.getPackageName(),0); versionCode=packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 得到安装的intent * @param apkFile * @return */ public static Intent getInstallIntent(Context context,File apkFile) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); //7.0以上需要使用FileProvider安装apk if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){ intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(context,"com.alpha.fileprovider", apkFile); intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); }else { intent.setDataAndType(Uri.fromFile(new File(apkFile.getAbsolutePath())), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } return intent; }}
PreferenceUtils
package com.alpha.alphaapp.version;import com.lidroid.xutils.DbUtils;import com.lidroid.xutils.exception.DbException;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;/** * * @项目名: WinfoSeaMap * @包名:com.winfo.seamap.utils * @类名:PreferenceUtils * @创建者:yanfeijun * @创建时间:2015-9-15上午10:55:24 * @描述:SharedPreferences工具类 * * @svn版本:$Rev: 93 $ * @更新人:$Author: wenjie $ * @更新时间:$Date: 2015-09-24 15:48:12 +0800 (Thu, 24 Sep 2015) $ * @更新描述:TODO */public class PreferenceUtils{private static SharedPreferencesmSp;private final static StringSP_NAME= "config";/** * 获得sharePreference内存对象 * * @param context * @return */private static SharedPreferences getSp(Context context){if (mSp == null){mSp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);}return mSp;}/** * 获取boolean类型的值 * * @param context * 上下文 * @param key * 对应的键 * @param defValue * 如果没有对应的值, * @return */public static boolean getBoolean(Context context, String key, boolean defValue){SharedPreferences sp = getSp(context);return sp.getBoolean(key, defValue);}/** * 获取boolean类型的值,如果没有对应的值,默认值返回false * * @param context * 上下文 * @param key * 对应的键 * @return */public static boolean getBoolean(Context context, String key){return getBoolean(context, key, false);}/** * 设置int类型的值 * * @param context * @param key * @param value */public static void setInt(Context context, String key, int value){SharedPreferences sp = getSp(context);Editor editor = sp.edit();editor.putInt(key, value);editor.commit();}/** * 设置boolean类型的值 * * @param context * @param key * @param value */public static void setBoolean(Context context, String key, boolean value){SharedPreferences sp = getSp(context);Editor editor = sp.edit();editor.putBoolean(key, value);editor.commit();}/** * 获取String类型的值 * * @param context * 上下文 * @param key * 对应的键 * @param defValue * 如果没有对应的值, * @return */public static String getString(Context context, String key, String defValue){SharedPreferences sp = getSp(context);return sp.getString(key, defValue);}/** * 获取int类型的值 * * @param context * 上下文 * @param key * 对应的键 * @param defValue * 如果没有对应的值, * @return */public static int getInt(Context context, String key, int defValue){SharedPreferences sp = getSp(context);return sp.getInt(key, defValue);}/** * 获取String类型的值,如果没有对应的值,默认值返回null * * @param context * 上下文 * @param key * 对应的键 * @return */public static String getString(Context context, String key){return getString(context, key, null);}/** * 设置String类型的值 * * @param context * @param key * @param value */public static void setString(Context context, String key, String value){SharedPreferences sp = getSp(context);Editor editor = sp.edit();editor.putString(key, value);editor.commit();}/** * 获取long类型的值 * * @param context * 上下文 * @param key * 对应的键 * @param defValue * 如果没有对应的值, * @return */public static long getLong(Context context, String key, long defValue){SharedPreferences sp = getSp(context);return sp.getLong(key, defValue);}/** * 获取long类型的值,如果没有对应的值,默认值返回0 * * @param context * 上下文 * @param key * 对应的键 * @return */public static Long getLong(Context context, String key){return getLong(context, key, 0);}/** * 设置Long类型的值 * * @param context * @param key * @param value */public static void setLong(Context context, String key, long value){SharedPreferences sp = getSp(context);Editor editor = sp.edit();editor.putLong(key, value);editor.commit();}/** * 根据key值删除指定的数据 * @param context * @param key */public static void remove(Context context , String key){SharedPreferences sp = getSp(context);Editor editor = sp.edit();editor.remove(key);editor.commit();}}
UpdateStatus
package com.alpha.alphaapp.version;/** * Created by kenway on 17/7/12 18:07 * Email : xiaokai090704@126.com */public interface UpdateStatus { /** * 没有新版本 */ int NO = 1; /** * 有新版本 */ int YES = 2; /** * 连接超时 */ int TIMEOUT = 3; /** * 没有wifi */ int NOWIFI = 4; /** * 数据解析出错 */ int ERROR = -1;}
UpdateVersionService
** * @author wenjie * 下载新版本的服务类 */public class UpdateVersionService extends Service { private static final String TAG = "UpdateVersionService"; private NotificationManager nm; private Notification notification; //标题标识 private int titleId = 0; //安装文件 private File updateFile; private static HttpHandler httpHandler; private HttpUtils httpUtils; private long initTotal = 0;//文件的总长度 @Override public void onCreate() { super.onCreate(); httpUtils = new HttpUtils(); updateFile = new File(SDCardUtils.getRootDirectory() + "/updateVersion/"+ MyApplication.APP_NAME_E); if(!updateFile.exists()){ //先得到文件的上级目录,并创建上级目录,在创建文件 updateFile.getParentFile().mkdir(); try { //创建文件 updateFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notification = new Notification(); notification.icon = R.drawable.icon512; notification.tickerText = "开始下载"; notification.when = System.currentTimeMillis(); notification.contentView = new RemoteViews(getPackageName(), R.layout.notification_version); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); String url = bundle.getString("downloadUrl"); nm.notify(titleId, notification); downLoadFile(url); return super.onStartCommand(intent, flags, startId); } public void downLoadFile(String url) { httpHandler = httpUtils.download(url, updateFile.getAbsolutePath(), true, false, new RequestCallBack() { @Override public void onSuccess(ResponseInfo response) { ToastUtils.showToast(getApplicationContext(), "下载完成!"); // 更改文字 notification.contentView.setTextViewText(R.id.msg, "下载完成!点击安装");// notification.contentView.setViewVisibility(R.id.btnStartStop, View.GONE);// notification.contentView.setViewVisibility(R.id.btnCancel,View.GONE); // 发送消息 nm.notify(0, notification); stopSelf(); //收起通知栏// UpdateVersionUtil.collapseStatusBar(UpdateVersionService.this); //自动安装新版本 Intent installIntent = ApkUtils.getInstallIntent(UpdateVersionService.this,updateFile); startActivity(installIntent); } @Override public void onFailure(HttpException error, String msg) { LogUtils.e("下载失败 error=="+error.getMessage()); LogUtils.e("下载失败 msg=="+msg); //网络连接错误 if (error.getExceptionCode() == 0) { // 更改文字 notification.contentView.setTextViewText(R.id.msg, "网络异常!请检查网络设置!"); } else if (error.getExceptionCode() == 416) {//文件已经下载完毕 // 更改文字 notification.contentView.setTextViewText(R.id.msg, MyApplication.APP_NAME_C); // 更改文字 notification.contentView.setTextViewText(R.id.bartext, "检测到新版本已经下载完成,点击即安装!"); // 隐藏进度条 notification.contentView.setViewVisibility(R.id.progressBar1, View.GONE); Intent intent = ApkUtils.getInstallIntent(UpdateVersionService.this,updateFile); PendingIntent pendingIntent = PendingIntent.getActivity(UpdateVersionService.this, 0, intent, 0); notification.flags = Notification.FLAG_AUTO_CANCEL;//点击通知栏之后 消失 notification.contentIntent = pendingIntent;//启动指定意图 } // 发送消息 ToastUtils.showToast(getApplicationContext(), "下载失败,请检查网络!"); nm.notify(0, notification); } @Override public void onLoading(long total, long current, boolean isUploading) { if (initTotal == 0) {//说明第一次开始下载 initTotal = total; } if (initTotal != total) {//说明下载过程中暂停过,文件的总长度出现问题 就把初始的文件的长度赋值给他重新计算已经下载的比例 total = initTotal; } long l = current * 100 / total; notification.contentView.setTextViewText(R.id.msg, "正在下载:"+MyApplication.APP_NAME_C); LogUtils.e("正在下载:"+ l + "%"); // 更改文字 notification.contentView.setTextViewText(R.id.bartext, l + "%"); // 更改进度条 notification.contentView.setProgressBar(R.id.progressBar1, 100, (int) l, false); // 发送消息 nm.notify(0, notification); } @Override public void onStart() { notification.contentView.setTextViewText(R.id.msg, "开始下载:"+MyApplication.APP_NAME_C); ToastUtils.showToast(getApplicationContext(),"开始下载:"+MyApplication.APP_NAME_C); nm.notify(titleId, notification); } }); } public static HttpHandler getHandler() { return httpHandler; } @Override public void onDestroy() { //下载完成时,清除该通知,自动安装 nm.cancel(titleId); LogUtils.e(TAG, "UpdateVersionService----onDestroy"); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; }}
UpdateVersionUtil
package com.alpha.alphaapp.version;import android.app.AlertDialog;import android.app.Dialog;import android.content.Context;import android.content.Intent;import android.os.Build;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.TextView;import com.alpha.alphaapp.R;import com.alpha.alphaapp.app.MyApplication;import com.alpha.lib_sdk.app.log.LogUtils;import com.alpha.lib_sdk.app.net.ReqCallBack;import com.alpha.lib_sdk.app.net.RequestManager;import com.alpha.lib_sdk.app.tool.JsonUtil;import com.alpha.lib_sdk.app.unitily.SDCardUtils;import com.alpha.lib_sdk.app.unitily.SPUtils;import com.alpha.lib_sdk.app.unitily.ToastUtils;import org.json.JSONObject;import java.io.File;import java.lang.reflect.Method;/** * Created by kenway on 17/7/12 17:28 * Email : xiaokai090704@126.com */public class UpdateVersionUtil { private static final String TAG = "UpdateVersionUtil"; /** * 接口回调 */ public interface UpdateListener { void onUpdateReturned(int updateStatus, VersionInfo info); } public UpdateListener updateListener; public void setUpdateListener(UpdateListener updateListener) { this.updateListener = updateListener; } /** * 检测是否有新版本 * * @param context * @param url 获取版本信息 * @param isDebug 是否为正式版 */ public static void doCheckVersionUpdate(final Context context, String url, boolean isDebug) { //本地测试是否有新版本发布 UpdateVersionUtil.UpdateListener listener = new UpdateVersionUtil.UpdateListener() { @Override public void onUpdateReturned(int updateStatus, final VersionInfo info) { //判断回调过来的版本检测状态 switch (updateStatus) { case UpdateStatus.YES: //弹出更新提示 UpdateVersionUtil.showDialog(context, info); break; case UpdateStatus.NO: //没有新版本// ToastUtils.showToast(context, "已经是最新版本了!"); break; case UpdateStatus.NOWIFI: //当前是非Wifi网络// ToastUtils.showToast(context, "只有在wifi下更新"); UpdateVersionUtil.showDialog(context, info);// DialogUtils.showDialog(MainActivity.this, "温馨提示","当前非wifi网络,下载会消耗手机流量!", "确定", "取消",new DialogOnClickListenner() {// @Override// public void btnConfirmClick(Dialog dialog) {// dialog.dismiss();// //点击确定之后弹出更新对话框// UpdateVersionUtil.showDialog(SplashActivity.this,info);// }//// @Override// public void btnCancelClick(Dialog dialog) {// dialog.dismiss();// }// }); break; case UpdateStatus.ERROR: //检测失败 ToastUtils.showToast(context, "检测失败,请稍后重试!"); break; case UpdateStatus.TIMEOUT: //链接超时 ToastUtils.showToast(context, "链接超时"); break; } } }; if (isDebug) { //debug localCheckVersion(context, listener); } else { //正式版 checkVersion(context, url, listener); } } /** * 网络测试 检查版本 */ private static void checkVersion(final Context context, String url, final UpdateListener listener) { ReqCallBack call = new ReqCallBack() { @Override public void onReqSuccess(String result) { try { JSONObject jsonObject = JsonUtil.stringToJson(result); VersionInfo mVersionInfo = JsonUtil.jsonToBean(jsonObject.toString(), VersionInfo.class); String clientVersion = ApkUtils.getVersionName(context); String serverVersion = mVersionInfo.getVersion(); LogUtils.e("clientVersionInfo=="+clientVersion+",serverVersion=="+mVersionInfo.getVersion()); //有新版本 if (!clientVersion.equals(serverVersion)) {// if (!NetUtils.isWifi(context)) {// listener.onUpdateReturned(UpdateStatus.NOWIFI, mVersionInfo);// } else {// listener.onUpdateReturned(UpdateStatus.YES, mVersionInfo);// } listener.onUpdateReturned(UpdateStatus.YES, mVersionInfo); } else { listener.onUpdateReturned(UpdateStatus.NO, null); } } catch (Exception e) { e.printStackTrace(); listener.onUpdateReturned(UpdateStatus.ERROR, null); } } @Override public void onReqFailed(String errorMsg) { listener.onUpdateReturned(UpdateStatus.TIMEOUT, null); } }; RequestManager.getInstance(context).requestGet(url, call); } private static void localCheckVersion(Context context, UpdateListener listener) { try { VersionInfo mVersionInfo = new VersionInfo(); mVersionInfo.setUrl("http://gdown.baidu.com/data/wisegame/57a788487345e938/QQ_358.apk"); mVersionInfo.setContent("更新内容:\n1、增加更新功能\n2、增加apk下载!\n3、用户界面优化!\n4、修改了不知道什么功能!"); mVersionInfo.setVersion(2 + ""); mVersionInfo.setVersion("v 1.0.4"); mVersionInfo.setSize("9.3M"); String clientVersionName = ApkUtils.getVersionName(context); String serverVersionCode = mVersionInfo.getVersion(); LogUtils.e(TAG, "clientVersionCode==" + clientVersionName + ",serverVersionCode==" + serverVersionCode); //有新版本 if (!clientVersionName.equals(serverVersionCode)) { listener.onUpdateReturned(UpdateStatus.YES, mVersionInfo);// if (!NetUtils.isWifi(context)) {// listener.onUpdateReturned(UpdateStatus.NOWIFI, mVersionInfo);// } else {// listener.onUpdateReturned(UpdateStatus.YES, mVersionInfo);// } } else { //无新本 listener.onUpdateReturned(UpdateStatus.NO, null); } } catch (Exception e) { e.printStackTrace(); listener.onUpdateReturned(UpdateStatus.ERROR, null); } } private static void showDialog(final Context context, final VersionInfo versionInfo) { final Dialog dialog = new AlertDialog.Builder(context).create(); //这里的名字可以修改 final File file = new File(SDCardUtils.getRootDirectory() + "/updateVersion/" + MyApplication.APP_NAME_E); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(false); dialog.show(); View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null); dialog.setContentView(view); final Button btnOk = (Button) view.findViewById(R.id.btn_update_id_ok); Button btnCancel = (Button) view.findViewById(R.id.btn_update_id_cancel); TextView tvContent = (TextView) view.findViewById(R.id.tv_update_content); TextView tvUpdateTitle = (TextView) view.findViewById(R.id.tv_update_title); TextView tvUpdateMsgSize = (TextView) view.findViewById(R.id.tv_update_msg_size); tvContent.setText(versionInfo.getContent()); tvUpdateTitle.setText("版本: " + versionInfo.getVersion()); final String existVersion = (String) SPUtils.get(context, SPUtils.KEY_VERSION, "string"); if (file.exists() && file.getName().equals(MyApplication.APP_NAME_E) && existVersion.equals(versionInfo.getVersion())) { tvUpdateMsgSize.setText("新版本已经下载,是否安装"); } else { tvUpdateMsgSize.setText("大小: " + versionInfo.getSize()); } btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (v.getId() == R.id.btn_update_id_ok) { //新版本已经下载 if (file.exists() && file.getName().equals(MyApplication.APP_NAME_E)&&existVersion.equals(versionInfo.getVersion())) { Intent intent = ApkUtils.getInstallIntent(context, file); context.startActivity(intent); } else { //没有下载,则开启服务下载最新版本 LogUtils.e(TAG, "新版本即将开始下载。。。。"); Intent intent = new Intent(context, UpdateVersionService.class); intent.putExtra("downloadUrl", versionInfo.getUrl()); context.startService(intent); SPUtils.put(context, SPUtils.KEY_VERSION, versionInfo.getVersion()); } } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); }// /**// * 收起通知栏// *///// public static void collapsingNotification(Context context){// //这里更改为新的//// Object service = context.getSystemService("statusbar");// Object service=null;// if (null == service)// return;// try {// Class<?> clazz = Class.forName("android.app.StatusBarManager");// int sdkVersion = android.os.Build.VERSION.SDK_INT;// Method collapse;// if (sdkVersion <= 16) {// collapse = clazz.getMethod("collapse");// } else {// collapse = clazz.getMethod("collapsePanels");// }// collapse.setAccessible(true);// collapse.invoke(service);// } catch (Exception e) {// e.printStackTrace();// }// } /** * 收起通知栏 * * @param context */ public static void collapseStatusBar(Context context) { try { Object statusBarManager = context.getSystemService("statusbar"); Method collapse; if (Build.VERSION.SDK_INT <= 16) { collapse = statusBarManager.getClass().getMethod("collapse"); } else { collapse = statusBarManager.getClass().getMethod("collapsePanels"); } collapse.invoke(statusBarManager); } catch (Exception localException) { localException.printStackTrace(); } }}
VersionInfo
package com.alpha.alphaapp.version;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import org.json.JSONException;import org.json.JSONObject;import java.io.Serializable;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.List;/** * Created by kenway on 17/7/12 17:37 * Email : xiaokai090704@126.com * 版本信息类 */public class VersionInfo implements Serializable { private static final long serialVersionUID = 1L; private String version; private String md5; private String url; private String content; private String size; public static VersionInfo objectFromData(String str, String key) { try { JSONObject jsonObject = new JSONObject(str); return new Gson().fromJson(jsonObject.getJSONObject(key).toString(), VersionInfo.class); } catch (JSONException e) { e.printStackTrace(); } return null; } public static List arrayVersionInfoFromData(String str, String key) { try { JSONObject jsonObject = new JSONObject(str); Type listType = new TypeToken>() { }.getType(); return new Gson().fromJson(jsonObject.getJSONArray(key).toString(), listType); } catch (JSONException e) { e.printStackTrace(); } return new ArrayList(); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } @Override public String toString() { return "VersionInfo{" + "version='" + version + '\'' + ", md5='" + md5 + '\'' + ", url='" + url + '\'' + ", content='" + content + '\'' + ", size='" + size + '\'' + '}'; }}
ToastUtils
import android.app.Activity;import android.content.Context;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import com.alpha.lib_sdk.R;/** * Toast统一管理类 * Created by kenway on 17/3/9 18:02 * Email : xiaokai090704@126.com */public class ToastUtils { private ToastUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isShow = true; /** * 短时间显示Toast * * @param context * @param message */ public static void showShort(Context context, CharSequence message) { if (isShow) Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * 短时间显示Toast * * @param context * @param message */ public static void showShort(Context context, int message) { if (isShow) Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * 长时间显示Toast * * @param context * @param message */ public static void showLong(Context context, CharSequence message) { if (isShow) Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } /** * 长时间显示Toast * * @param context * @param message */ public static void showLong(Context context, int message) { if (isShow) Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } /** * 自定义显示Toast时间 * * @param context * @param message * @param duration */ public static void show(Context context, CharSequence message, int duration) { if (isShow) Toast.makeText(context, message, duration).show(); } /** * 自定义显示Toast时间 * @param context * @param message * @param duration */ public static void show(Context context, int message, int duration) { if (isShow) Toast.makeText(context, message, duration).show(); } private static String oldMsg; protected static Toast toast = null; private static long oneTime = 0; private static long twoTime = 0; /** * 吐出一个显示时间较短的提示 * * @param context 上下文 * @param s 文本内容 */ public static void showToast(Context context, String s) { if (toast == null) { toast = Toast.makeText(context, s, Toast.LENGTH_SHORT); toast.show(); oneTime = System.currentTimeMillis(); } else { twoTime = System.currentTimeMillis(); if (s.equals(oldMsg)) { if (twoTime - oneTime > Toast.LENGTH_SHORT) { toast.show(); } } else { oldMsg = s; toast.setText(s); toast.show(); } } oneTime = twoTime; } /** * 吐出一个显示时间较短的提示 * * @param context 上下文 * @param resId 文本内容 */ public static void showToast(Context context, int resId) { String s = ResourceUtil.resToStr(context, resId); if (toast == null) { toast = Toast.makeText(context, s, Toast.LENGTH_SHORT); toast.show(); oneTime = System.currentTimeMillis(); } else { twoTime = System.currentTimeMillis(); if (s.equals(oldMsg)) { if (twoTime - oneTime > Toast.LENGTH_SHORT) { toast.show(); } } else { oldMsg = s; toast.setText(s); toast.show(); } } oneTime = twoTime; } public static void showForumToast(Context context, String msg, int resDrawable) { //Inflater意思是充气 //LayoutInflater这个类用来实例化XML文件到其相应的视图对象的布局 LayoutInflater inflater =LayoutInflater.from(context); //通过制定XML文件及布局ID来填充一个视图对象 View layout = inflater.inflate(R.layout.widget_toast,null); ImageView image = (ImageView) layout.findViewById(R.id.widget_toast_iv); //设置布局中图片视图中图片 image.setImageResource(resDrawable); TextView title = (TextView) layout.findViewById(R.id.widget_toast_tv); //设置标题 title.setText(msg); Toast toast= new Toast(context); toast.setGravity(Gravity.CENTER , 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); }}
/** * Created by kenway on 17/3/9 18:05 * Email : xiaokai090704@126.com */public class SPUtils { public static final String KEY_VERSION="version"; /** * 保存在手机里面的文件名 */ public static final String FILE_NAME = "share_data"; /** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 * * @param context * @param key * @param object */ public static void put(Context context, String key, Object object) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (object instanceof String) { editor.putString(key, (String) object); } else if (object instanceof Integer) { editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) { editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) { editor.putFloat(key, (Float) object); } else if (object instanceof Long) { editor.putLong(key, (Long) object); } else { editor.putString(key, object.toString()); } SharedPreferencesCompat.apply(editor); } /** * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 * * @param context * @param key * @param defaultObject * @return */ public static Object get(Context context, String key, Object defaultObject) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } return null; } /** * 移除某个key值已经对应的值 * @param context * @param key */ public static void remove(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); SharedPreferencesCompat.apply(editor); } /** * 清除所有数据 * @param context */ public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); SharedPreferencesCompat.apply(editor); } /** * 查询某个key是否已经存在 * @param context * @param key * @return */ public static boolean contains(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.contains(key); } /** * 返回所有的键值对 * * @param context * @return */ public static Map getAll(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.getAll(); } /** * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 * * @author zhy * */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 * * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Method findApplyMethod() { try { Class clz = SharedPreferences.Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) { } return null; } /** * 如果找到则使用apply执行,否则使用commit * * @param editor */ public static void apply(SharedPreferences.Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); } }}
SDcardUtils
package com.alpha.lib_sdk.app.unitily;import android.annotation.TargetApi;import android.os.Build;import android.os.Environment;import android.os.StatFs;import java.io.File;/** * Created by kenway on 17/3/9 18:11 * Email : xiaokai090704@126.com */public class SDCardUtils { public static String getPath(){ return Environment.getExternalStorageDirectory().getAbsolutePath(); } /** * 获取SD卡的状态 * @return */ public static String getState(){ return Environment.getExternalStorageState(); } /** * SD卡是否可用 * @return 只有当SD卡已经安装并且准备好了才返回true */ public static boolean isAvailable(){ return getState().equals(Environment.MEDIA_MOUNTED); } /** * 获取SD卡的根目录 * @return null:不存在SD卡 */ public static File getRootDirectory(){ return isAvailable()?Environment.getExternalStorageDirectory():null; } /** * 获取SD卡的根路径 * @return null:不存在SD卡 */ public static String getRootPath(){ File rootDirectory = getRootDirectory(); return rootDirectory != null ?rootDirectory.getPath():null; } /** * 获取SD卡总的容量 * @return 总容量;-1:SD卡不可用 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static long getTotalSize(){ if(isAvailable()){ StatFs statFs = new StatFs(getRootDirectory().getPath()); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1){ return statFs.getBlockCount() * statFs.getBlockSize(); }else{ return statFs.getBlockCount() * statFs.getBlockSize(); } }else{ return -1; } } /** * 获取SD卡中可用的容量 * @return 可用的容量;-1:SD卡不可用 */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static long getAvailableSize(){ if(isAvailable()){ StatFs statFs = new StatFs(getRootDirectory().getPath()); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1){ return statFs.getAvailableBlocks() * statFs.getBlockSize(); }else{ return statFs.getAvailableBlocks() * statFs.getBlockSize(); } }else{ return -1; } }}
JsonUtils
package com.alpha.lib_sdk.app.tool;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.content.Context;import com.google.gson.Gson;/** * json 和 实体类之间的相互转换 * * @author 00 */public class JsonUtil { /** * 将一个实体对象 转换成一个json字符串 提示对象中可包含集合 * * @param t 实体类 * @return */ public static String beanToJson(T t) { Gson gson = new Gson(); String json = gson.toJson(t); return json; } /** * 将一个json字符串 转换成一个实体类对象 可包含list * * @param json * @param class1 * @return */ public static T jsonToBean(String json, Class class1) { T t = null; try { Gson gson = new Gson(); t = class1.newInstance(); t = gson.fromJson(json, class1); } catch (java.lang.InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return t; } /** * 将一个json字符串 转换成一个实体类集合 可包含list * [{},{},{}] * @param jsonArray * @param class1 * @return */ public static List jsonToBeanArray(String jsonArray, Class class1) { List list = new ArrayList<>(); T t = null; try { JSONArray array = new JSONArray(jsonArray); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); Gson gson = new Gson(); t = class1.newInstance(); t = gson.fromJson(object.toString(), class1); list.add(t); } } catch (java.lang.InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return list; } /** * 将json字符串转换成一个json对象 * * @param str * @return */ public static JSONObject stringToJson(String str) { try { return new JSONObject(str); } catch (JSONException e) { e.printStackTrace(); return null; } } public static String getString(InputStream is) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } byte[] byteArray = baos.toByteArray(); //String str = new String(byteArray); return new String(byteArray, "utf-8"); } catch (IOException e) { e.printStackTrace(); } return ""; } /** * 从assert文件夹中读取json文件,然后转化为json对象 * * @throws Exception */ public static JSONObject getJsonDataFromAssets(Context context, String jsonFileName) throws Exception { JSONObject mJsonObj = null; StringBuffer sb = new StringBuffer(); InputStream is = context.getAssets().open(jsonFileName); int len = -1; byte[] buf = new byte[1024]; while ((len = is.read(buf)) != -1) { sb.append(new String(buf, 0, len, "UTF-8")); } is.close(); mJsonObj = new JSONObject(sb.toString()); return mJsonObj; } public static String getJSONStrFromList(List list){ Gson gson = new Gson(); String str = gson.toJson(list); return str; }}
RequestManager
package com.alpha.lib_sdk.app.net;import android.content.Context;import android.os.Handler;import android.util.Log;import com.alpha.lib_sdk.app.log.LogUtils;import com.alpha.lib_sdk.app.tool.SortTools;import com.alpha.lib_sdk.app.tool.SystemUtils;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.security.cert.CertificateException;import java.util.HashMap;import java.util.concurrent.TimeUnit;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;import okio.Buffer;import okio.BufferedSink;import okio.Okio;import okio.Source;/** * Created by kenway on 17/5/22 14:09 * Email : xiaokai090704@126.com * 请求管理类 okHttpClient */public class RequestManager { private static final String TAG = "RequestManager"; private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final MediaType MEDIA_OBJECT_STREAM = MediaType.parse("application/octet-stream");//mdiatype 这个需要和服务端保持一致 你需要看下你们服务器设置的ContentType 是不是这个,他们设置的是哪个 我们要和他们保持一致 private static RequestManager mInstance;//单例引用 private OkHttpClient mOkHttpClient;//okHttpClient; private Handler okHttpHandler;//全局处理子线程和M线程通信 private RequestManager(Context context) { //初始化OkHttpClient mOkHttpClient = gettUnsafeOkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .build(); okHttpHandler = new Handler(context.getMainLooper());//属于主线程的Handler } private static OkHttpClient gettUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); OkHttpClient okHttpClient = builder.build(); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } } /** * 获取网络请求管理类实例 * * @param context * @return */ public static RequestManager getInstance(Context context) { RequestManager inst = mInstance; if (inst == null) { synchronized (RequestManager.class) { inst = mInstance; if (inst == null) { inst = new RequestManager(context.getApplicationContext()); mInstance = inst; } } } return inst; } public Call requestGetWXData(String actionUrl, final ReqCallBack callBack) { try { String requestUrl = actionUrl; Request request = new Request.Builder().url(actionUrl).get().build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack("访问失败", callBack); LogUtils.e(TAG, e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); LogUtils.e(TAG, "response ----->" + string); successCallBack((T) string, callBack); } else { failedCallBack("服务器错误", callBack); } } }); return call; } catch (Exception e) { LogUtils.e(TAG, e.toString()); } return null; } /** * 获取省市县的get请求 * * @param actionUrl * @param callBack * @param * @return */ public Call requestGet(String actionUrl, final ReqCallBack callBack) { try { final Request request = new Request.Builder().url(actionUrl).get().build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack("访问失败", callBack); LogUtils.e(TAG, "这里发生了错误==" + e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); successCallBack((T) string, callBack); } else { failedCallBack("服务器错误", callBack); } } }); return call; } catch (Exception e) { LogUtils.e(TAG, e.toString()); } return null; } /** * okHttp post异步请求 发送json数据 * * @param actionUrl 接口地址 * @param json 请求参数json 数据 vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv * @param callBack 请求返回数据回调 * @param 数据泛型 * @return */ public Call requestPostByJsonAsyn(String actionUrl, String json, final ReqCallBack callBack) { try { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(actionUrl).post(body).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack("访问失败", callBack); LogUtils.e(TAG, e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); LogUtils.e(TAG, "response ----->" + string); successCallBack((T) string, callBack); } else { failedCallBack("服务器错误", callBack); } } }); return call; } catch (Exception e) { LogUtils.e(e.toString()); } return null; } /** * okHttp post异步请求表单提交 * 论坛模块使用 * * @param actionUrl 接口地址 * @param paramsMap 请求参数 * @param callBack 请求返回数据回调 * @param 数据泛型 * @return */ public Call requestPostByAsynWithForm(String actionUrl, HashMap paramsMap, final ReqCallBack callBack) { paramsMap.put(ForumNetPostUtil.KEY_TICK, SystemUtils.getCurrentTimeMillis() + ""); paramsMap.put(ForumNetPostUtil.KEY_RANDOM, ForumNetPostUtil.createRandom(false, 12));//12位数字和字母随机数据 String sign = SortTools.getSign(paramsMap); paramsMap.put(ForumNetPostUtil.KEY_SIGN, sign); paramsMap.put(ForumNetPostUtil.KEY_APPID, JsonEncryptUtil.getAPPID()); LogUtils.e("论坛发送数据"+paramsMap.toString()); try { FormBody.Builder builder = new FormBody.Builder(); for (String key : paramsMap.keySet()) { builder.add(key, paramsMap.get(key)); } RequestBody formBody = builder.build(); String requestUrl = actionUrl; Request request = new Request.Builder().url(actionUrl).post(formBody).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack("访问失败", callBack); LogUtils.e(TAG, e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); successCallBack((T) string, callBack); } else { LogUtils.e("错误原因," + response.toString()); failedCallBack("服务器错误", callBack); } } }); return call; } catch (Exception e) { LogUtils.e(TAG, e.toString()); } return null; } /** * okHttp post异步请求表单提交 * * @param actionUrl 接口地址 * @param paramsMap 请求参数 * @param callBack 请求返回数据回调 * @param 数据泛型 * @return */ public Call requestPostByCommonAsynWithForm(String actionUrl, HashMap paramsMap, final ReqCallBack callBack) { try { FormBody.Builder builder = new FormBody.Builder(); for (String key : paramsMap.keySet()) { builder.add(key, paramsMap.get(key)); } RequestBody formBody = builder.build(); String requestUrl = actionUrl; Request request = new Request.Builder().url(actionUrl).post(formBody).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack("访问失败", callBack); LogUtils.e(TAG, e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); successCallBack((T) string, callBack); } else { LogUtils.e("错误原因," + response.toString()); failedCallBack("服务器错误", callBack); } } }); return call; } catch (Exception e) { LogUtils.e(TAG, e.toString()); } return null; } /** * 统一同意处理成功信息 * * @param result * @param callBack * @param */ private void successCallBack(final T result, final ReqCallBack callBack) { okHttpHandler.post(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onReqSuccess(result); } } }); } /** * okHttp post异步上传文件。带参数 * * @param actionUrl 接口地址 * @param paramsMap 请求参数 * @param callBack 请求返回数据回调 * @param 数据泛型 * @return */ public Call uploadFile(String actionUrl, HashMap paramsMap, final ReqCallBack callBack) { try { //带参数上传文件 MultipartBody.Builder builder_pic = new MultipartBody.Builder(); builder_pic.setType(MultipartBody.FORM); LogUtils.e(paramsMap.toString()); //追加参数 for (String key : paramsMap.keySet()) { Object object = paramsMap.get(key); if (!(object instanceof File)) { builder_pic.addFormDataPart(key, object.toString()); } else { File file = (File) object; builder_pic.addFormDataPart(key, file.getName(), RequestBody.create(null, file)); } } //创建RequestBody RequestBody body = builder_pic.build(); //创建Request final Request request = new Request.Builder().url(actionUrl).post(body).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack("访问失败", callBack); LogUtils.e(TAG, e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); LogUtils.e("onResponse--->" + string); successCallBack((T) string, callBack); } else { failedCallBack("服务器错误", callBack); } } }); return call; } catch (Exception e) { LogUtils.e(e.toString()); } return null; } /** * 带参数带进度上传文件 * * @param actionUrl * @param paramsMap * @param callBack * @param */ public void upLoadFileHasProgress(String actionUrl, HashMap paramsMap, final ReqProgressCallBack callBack) { try { //补全请求地址 MultipartBody.Builder builder = new MultipartBody.Builder(); //设置类型 builder.setType(MultipartBody.FORM); //追加参数 for (String key : paramsMap.keySet()) { Object object = paramsMap.get(key); if (!(object instanceof File)) { builder.addFormDataPart(key, object.toString()); } else { File file = (File) object; builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack)); } } //创建RequestBody RequestBody body = builder.build(); //创建Request final Request request = new Request.Builder().url(actionUrl).post(body).build(); final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { LogUtils.e(e.toString()); failedCallBack("上传失败", callBack); } @Override public void onResponse(Call call, Response response) throws IOException { LogUtils.e("上传成功===response.isSuccessful()==" + response.isSuccessful()); if (response.isSuccessful()) { String string = response.body().string(); LogUtils.e("response ----->" + string); successCallBack((T) string, callBack); } else { LogUtils.e("response.toString==" + response.toString()); failedCallBack("上传失败", callBack); } } }); } catch (Exception e) { LogUtils.e(e.toString()); } } /** * 不带进度文件下载 * * @param callBack * @param */ public void downLoadFile(String fileUrl, final String destFileDir, final ReqCallBack callBack) { final String fileName = fileUrl; final File file = new File(destFileDir, fileName);// LogUtils.e("filePath==" + file.getAbsolutePath()); if (file.exists()) { LogUtils.e("该文件已存在"); successCallBack((T) file, callBack); return; } final Request request = new Request.Builder().url(fileUrl).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, e.toString()); failedCallBack("下载失败", callBack); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { long total = response.body().contentLength(); long current = 0; is = response.body().byteStream(); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { current += len; fos.write(buf, 0, len); Log.e(TAG, "current------>" + current); } fos.flush(); successCallBack((T) file, callBack); } catch (IOException e) { Log.e(TAG, e.toString()); failedCallBack("下载失败", callBack); } finally { try { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { Log.e(TAG, e.toString()); } } } }); } /** * 统一处理失败信息 * * @param errorMsg * @param callBack * @param */ private void failedCallBack(final String errorMsg, final ReqCallBack callBack) { okHttpHandler.post(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onReqFailed(errorMsg); } } }); } public RequestBody createProgressRequestBody(final MediaType contentType, final File file, final ReqProgressCallBack callBack) { return new RequestBody() { @Override public MediaType contentType() { return contentType; } @Override public long contentLength() throws IOException { return file.length(); } @Override public void writeTo(BufferedSink sink) throws IOException { Source source; try { source = Okio.source(file); Buffer buf = new Buffer(); long remaining = contentLength(); long current = 0; for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) { sink.write(buf, readCount); current += readCount; progressCallBack(remaining, current, callBack); } } catch (Exception e) { e.printStackTrace(); } } }; } /** * 统一处理进度信息 * * @param total 总计大小 * @param current 当前进度 * @param callBack * @param */ private void progressCallBack(final long total, final long current, final ReqProgressCallBack callBack) { okHttpHandler.post(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onProgress(total, current); } } }); }}
package com.alpha.lib_sdk.app.net;public interface ReqCallBack { /** * 响应成功 */ void onReqSuccess(T result); /** * 响应失败 */ void onReqFailed(String errorMsg);}
manifest.xml
UpdateVersionServices
package com.alpha.alphaapp.version;import java.io.File;import java.io.IOException;import com.alpha.alphaapp.R;import com.alpha.alphaapp.app.MyApplication;import com.alpha.lib_sdk.app.log.LogUtils;import com.alpha.lib_sdk.app.unitily.SDCardUtils;import com.alpha.lib_sdk.app.unitily.ToastUtils;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.HttpHandler;import com.lidroid.xutils.http.ResponseInfo;import com.lidroid.xutils.http.callback.RequestCallBack;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.widget.RemoteViews;/** * @author wenjie * 下载新版本的服务类 */public class UpdateVersionService extends Service { private static final String TAG = "UpdateVersionService"; private NotificationManager nm; private Notification notification; //标题标识 private int titleId = 0; //安装文件 private File updateFile; private static HttpHandler httpHandler; private HttpUtils httpUtils; private long initTotal = 0;//文件的总长度 @Override public void onCreate() { super.onCreate(); httpUtils = new HttpUtils(); updateFile = new File(SDCardUtils.getRootDirectory() + "/updateVersion/"+ MyApplication.APP_NAME_E); if(!updateFile.exists()){ //先得到文件的上级目录,并创建上级目录,在创建文件 updateFile.getParentFile().mkdir(); try { //创建文件 updateFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notification = new Notification(); notification.icon = R.drawable.icon512; notification.tickerText = "开始下载"; notification.when = System.currentTimeMillis(); notification.contentView = new RemoteViews(getPackageName(), R.layout.notification_version); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); String url = bundle.getString("downloadUrl"); nm.notify(titleId, notification); downLoadFile(url); return super.onStartCommand(intent, flags, startId); } public void downLoadFile(String url) { httpHandler = httpUtils.download(url, updateFile.getAbsolutePath(), true, false, new RequestCallBack() { @Override public void onSuccess(ResponseInfo response) { ToastUtils.showToast(getApplicationContext(), "下载完成!"); // 更改文字 notification.contentView.setTextViewText(R.id.msg, "下载完成!点击安装");// notification.contentView.setViewVisibility(R.id.btnStartStop, View.GONE);// notification.contentView.setViewVisibility(R.id.btnCancel,View.GONE); // 发送消息 nm.notify(0, notification); stopSelf(); //收起通知栏// UpdateVersionUtil.collapseStatusBar(UpdateVersionService.this); //自动安装新版本 Intent installIntent = ApkUtils.getInstallIntent(UpdateVersionService.this,updateFile); startActivity(installIntent); } @Override public void onFailure(HttpException error, String msg) { LogUtils.e("下载失败 error=="+error.getMessage()); LogUtils.e("下载失败 msg=="+msg); //网络连接错误 if (error.getExceptionCode() == 0) { // 更改文字 notification.contentView.setTextViewText(R.id.msg, "网络异常!请检查网络设置!"); } else if (error.getExceptionCode() == 416) {//文件已经下载完毕 // 更改文字 notification.contentView.setTextViewText(R.id.msg, MyApplication.APP_NAME_C); // 更改文字 notification.contentView.setTextViewText(R.id.bartext, "检测到新版本已经下载完成,点击即安装!"); // 隐藏进度条 notification.contentView.setViewVisibility(R.id.progressBar1, View.GONE); Intent intent = ApkUtils.getInstallIntent(UpdateVersionService.this,updateFile); PendingIntent pendingIntent = PendingIntent.getActivity(UpdateVersionService.this, 0, intent, 0); notification.flags = Notification.FLAG_AUTO_CANCEL;//点击通知栏之后 消失 notification.contentIntent = pendingIntent;//启动指定意图 } // 发送消息 ToastUtils.showToast(getApplicationContext(), "下载失败,请检查网络!"); nm.notify(0, notification); } @Override public void onLoading(long total, long current, boolean isUploading) { if (initTotal == 0) {//说明第一次开始下载 initTotal = total; } if (initTotal != total) {//说明下载过程中暂停过,文件的总长度出现问题 就把初始的文件的长度赋值给他重新计算已经下载的比例 total = initTotal; } long l = current * 100 / total; notification.contentView.setTextViewText(R.id.msg, "正在下载:"+MyApplication.APP_NAME_C); LogUtils.e("正在下载:"+ l + "%"); // 更改文字 notification.contentView.setTextViewText(R.id.bartext, l + "%"); // 更改进度条 notification.contentView.setProgressBar(R.id.progressBar1, 100, (int) l, false); // 发送消息 nm.notify(0, notification); } @Override public void onStart() { notification.contentView.setTextViewText(R.id.msg, "开始下载:"+MyApplication.APP_NAME_C); ToastUtils.showToast(getApplicationContext(),"开始下载:"+MyApplication.APP_NAME_C); nm.notify(titleId, notification); } }); } public static HttpHandler getHandler() { return httpHandler; } @Override public void onDestroy() { //下载完成时,清除该通知,自动安装 nm.cancel(titleId); LogUtils.e(TAG, "UpdateVersionService----onDestroy"); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; }}
更多相关文章
- android 7.0+下载安装
- Android(安卓)使用decodeFile方法加载手机磁盘中的图片文件
- android 保存和读取文件
- android 6.0锁屏界面时间位置修改
- the android sdk folder can no longer be inside the applicati
- Android(安卓)AudioRecord录音实时pcm 编码为 aac 文件
- AndroidStudio使用NDK报错显示mips64el-linux-android-strip''
- Android拍照、录像、录音代码范例
- NPM 和webpack 的基础使用