JsonResponseHandleMSJQ handler_version_new = new JsonResponseHandleMSJQ(this) {
@Override
public void onSuccess(JSONArray jsonArray) {
try {
String versionUrl = null;
List<Bean_Dict_Version_New> mListVersion = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<Bean_Dict_Version_New>>() {
}.getType());
String versionCode = "";
String versionDesc = "";
for (Bean_Dict_Version_New bean_dict_version : mListVersion) {
if ("android".equals(bean_dict_version.getPlatForm())) {
if ("labx_share".equals(bean_dict_version.getAppName())) {
versionCode = bean_dict_version.getAppVersion();
versionUrl = Utils.getStrPathPic(ActSplash.this, bean_dict_version.getFilePathValue());
versionDesc = bean_dict_version.getVersionChangeDesc();
break;
}
}
}
// 獲取當前軟件包信息
PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), PackageManager.GET_CONFIGURATIONS);
// 當前軟件版本號
String versionLocal = pi.versionName;
Timber.e("local:" + versionLocal + "server:" + versionCode);
if (!TextUtils.isEmpty(versionCode)) {
if (!versionCode.equals(versionLocal)) {
final String finalVersionUrl = versionUrl;
if (isAvailable) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(ActSplash.this, UpdateService.class);
intent.putExtra("url", finalVersionUrl);
startService(intent);
goToNextAct();
}
});
alertDialog.setNegativeButton("忽略", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
goToNextAct();
}
});
alertDialog.setTitle("新版更新提示");
alertDialog.setMessage(versionDesc);
alertDialog.setCancelable(false);
alertDialog.create().show();
} else {
new SharedPreferencesHelper(ActSplash.this).LogOut();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(ActSplash.this, UpdateService.class);
intent.putExtra("url", finalVersionUrl);
startService(intent);
}
});
alertDialog.setNegativeButton("退出應用", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
alertDialog.setTitle("新版更新提示");
alertDialog.setMessage(versionDesc);
alertDialog.setCancelable(false);
alertDialog.create().show();
}
} else {
goToNextAct();
}
} else {
goToNextAct();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
2,updateService
package com.weilaifu.aqbx.base;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.weilaifu.aqbx.R;
import com.weilaifu.aqbx.act.ActMain;
import com.weilaifu.aqbx.util.Utils;
import com.weilaifu.msjqlib.util.UtilTools;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UpdateService extends Service {
private NotificationManager nm;
private Notification notification;
private File tempFile = null;
private boolean cancelUpdate = false;
private MyHandler myHandler;
private int download_precent = 0;
private RemoteViews views;
private int notificationId = 1234;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
UtilTools.showToast(getApplicationContext(), R.string.text_toast_update);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// notification = new Notification();
// notification.icon = android.R.drawable.stat_sys_download;
// //notification.icon=android.R.drawable.stat_sys_download_done;
// notification.tickerText = getString(R.string.app_name) + getString(R.string.text_app_update);
// notification.when = System.currentTimeMillis();
// notification.defaults = Notification.DEFAULT_LIGHTS;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ActMain.class), 0);
Notification.Builder builder = new Notification.Builder(UpdateService.this);
builder.setSmallIcon(R.drawable.ic_logo)
.setTicker(getString(R.string.app_name) + "正在更新")
.setContentTitle(getString(R.string.app_name))
.setContentIntent(contentIntent);
views = new RemoteViews(getPackageName(), R.layout.update);
builder.setContent(views);
notification = builder.getNotification();
nm.notify(notificationId, notification);
myHandler = new MyHandler(Looper.myLooper(), this);
Message message = myHandler.obtainMessage(3, 0);
myHandler.sendMessage(message);
downFile(intent.getStringExtra("url"));
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void downFile(final String url) {
new Thread() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
if (is != null) {
File rootFile = new File(Environment.getExternalStorageDirectory(), "/" + Utils.DIR);
if (!rootFile.exists() && !rootFile.isDirectory())
rootFile.mkdir();
tempFile = new File(Environment.getExternalStorageDirectory(),
"/" + Utils.DIR + "/" + url.substring(url.lastIndexOf("/") + 1));
if (tempFile.exists())
tempFile.delete();
tempFile.createNewFile();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int read;
long count = 0;
int precent = 0;
byte[] buffer = new byte[1024];
while ((read = bis.read(buffer)) != -1 && !cancelUpdate) {
bos.write(buffer, 0, read);
count += read;
precent = (int) (((double) count / length) * 100);
if (precent - download_precent >= 5) {
download_precent = precent;
Message message = myHandler.obtainMessage(3, precent);
myHandler.sendMessage(message);
}
}
bos.flush();
bos.close();
fos.flush();
fos.close();
is.close();
bis.close();
}
if (!cancelUpdate) {
Message message = myHandler.obtainMessage(2, tempFile);
myHandler.sendMessage(message);
} else {
tempFile.delete();
}
} catch (ClientProtocolException e) {
Message message = myHandler.obtainMessage(4, "下載應用失敗");
myHandler.sendMessage(message);
} catch (IOException e) {
Message message = myHandler.obtainMessage(4, "下載應用失敗");
myHandler.sendMessage(message);
} catch (Exception e) {
Message message = myHandler.obtainMessage(4, "下載應用失敗");
myHandler.sendMessage(message);
}
}
}.start();
}
private void Instanll(File file, Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
}
class MyHandler extends Handler {
private Context context;
public MyHandler(Looper looper, Context c) {
super(looper);
this.context = c;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg != null) {
switch (msg.what) {
case 0:
Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
break;
case 1:
break;
case 2:
download_precent = 0;
nm.cancel(notificationId);
Instanll((File) msg.obj, context);
stopSelf();
break;
case 3:
views.setTextViewText(R.id.tvProcess, download_precent + "%");
views.setProgressBar(R.id.pbDownload, 100, download_precent, false);
// notification.contentView = views;
nm.notify(notificationId, notification);
break;
case 4:
nm.cancel(notificationId);
break;
}
}
}
}
//---------------------------------------------------------------------
/**
* �������ؿ�
*/
private void showDownloadDialog() {
// AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
// builder.setTitle("�汾������...");
// final LayoutInflater inflater = LayoutInflater.from(mContext);
// View v = inflater.inflate(R.layout.dialog_download, null);
// progressBar = (NumberProgressBar) v.findViewById(R.id.pb_dialog_download);
// builder.setView(v);
// builder.setNegativeButton("ȡ��", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// //��ֹ����
// isInterceptDownload = true;
// }
// });
// dialogDownload = builder.create();
// dialogDownload.show();
//
// //����apk
// Thread downLoadThread = new Thread(downApkRunnable);
// downLoadThread.start();
}
// ���ؽ����
// private NumberProgressBar progressBar;
// �Ƿ���ֹ����
private boolean isInterceptDownload = false;
//�������ʾ��ֵ
private int progress = 0;
/**
* �ӷ����������°�apk���߳�
*/
private Runnable downApkRunnable = new Runnable() {
@Override
public void run() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//���û��SD��
// AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
// builder.setTitle("��ʾ");
// builder.setMessage("��ǰ�豸��SD�������������");
// builder.setPositiveButton("ȷ��", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
// builder.show();
} else {
try {
//���������°�apk��ַ
URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/");
if (!file.exists()) {
//����ļ��в�����,�