import java.io.FileOutputStream;php
import java.io.InputStream;java
import java.io.OutputStream;android
import java.net.HttpURLConnection;express
import java.net.MalformedURLException;服務器
import java.net.URL;app
import android.app.Notification;ide
import android.app.NotificationManager;ui
import android.app.PendingIntent;this
import android.app.Service;url
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.runye.express.android.R;
import com.runye.express.utils.FileUtils;
import com.runye.express.utils.LogUtil;
/***
* s 更新版本
*
* @author zhangjia
*
*/
public class UpdateService extends Service {
private final String TAG = "UpdateService";
/** 超時 */
private static final int TIMEOUT = 10 * 1000;
/** 下載地址 */
private static final String down_url = "http://www.tyfind.com:8080/find-consumers-android-update/new/find-consumers-android.apk";
/** 下載成功 */
private static final int DOWN_OK = 1;
/** 下載失敗 */
private static final int DOWN_ERROR = 0;
/***
* 建立通知欄
*/
RemoteViews mViews;
/** 應用名稱 */
private String app_name;
/** 通知管理器 */
private NotificationManager notificationManager;
/** 通知 */
private Notification notification;
/** 點擊通知跳轉 */
private Intent mUpdateIntent;
/** 等待跳轉 */
private PendingIntent mPendingIntent;
/** 通知ID */
private final int notification_id = 0;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LogUtil.d(TAG, "UpdateService+onStartCommand");
app_name = getResources().getString(R.string.app_name);
// 建立文件
FileUtils.createFile(app_name);
createNotification();
createThread();
return super.onStartCommand(intent, flags, startId);
}
/**
*
* @Description: 建立通知
* [url=home.php?mod=space&uid=309376]@return[/url] void
*/
public void createNotification() {
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
android.app.Notification.Builder builder = new Notification.Builder(this);
mViews = new RemoteViews(getPackageName(), R.layout.notification_item);
mViews.setImageViewResource(R.id.notificationImage, R.drawable.ic_launcher);
mViews.setTextViewText(R.id.notificationTitle, "Find物流版正在下載");
mViews.setTextViewText(R.id.notificationPercent, "0%");
mViews.setProgressBar(R.id.notificationProgress, 100, 0, false);
builder.setContent(mViews);
mUpdateIntent = new Intent(Intent.ACTION_MAIN);
mUpdateIntent.addCategory(Intent.CATEGORY_HOME);
mPendingIntent = PendingIntent.getActivity(this, 0, mUpdateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(mPendingIntent);
builder.setTicker("開始下載,點擊可查看");
builder.setSmallIcon(R.drawable.ic_launcher).setWhen(System.currentTimeMillis()).setAutoCancel(true);// 設置能夠清除
notification = builder.getNotification();
notificationManager.notify(notification_id, notification);
}
/***
* 開線程下載
*/
public void createThread() {
/***
* 更新UI
*/
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWN_OK:
InstallationAPK();
break;
case DOWN_ERROR:
break;
default:
stopSelf();
break;
}
}
};
final Message message = new Message();
new Thread(new Runnable() {
@Override
public void run() {
try {
long downloadSize = downloadUpdateFile(down_url, FileUtils.updateFile.toString());
if (downloadSize > 0) {
// 下載成功
message.what = DOWN_OK;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
message.what = DOWN_ERROR;
handler.sendMessage(message);
}
}
}).start();
}
/**
*
* @Description: 自動安裝
* @return void
*/
private void InstallationAPK() {
notificationManager.cancel(notification_id);
// 中止服務
stopSelf();
// 下載完成,點擊安裝
Uri uri = Uri.fromFile(FileUtils.updateFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
}
/***
* 下載文件
*
* @return
* @throws MalformedURLException
*/
public long downloadUpdateFile(String down_url, String file) throws Exception {
int down_step = 5;// 提示step
int totalSize;// 文件總大小
int downloadCount = 0;// 已經下載好的大小
int updateCount = 0;// 已經上傳的文件大小
InputStream inputStream;
OutputStream outputStream;
URL url = new URL(down_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(TIMEOUT);
httpURLConnection.setReadTimeout(TIMEOUT);
// 獲取下載文件的size
totalSize = httpURLConnection.getContentLength();
if (httpURLConnection.getResponseCode() == 404) {
throw new Exception("fail!");
}
inputStream = httpURLConnection.getInputStream();
outputStream = new FileOutputStream(file, false);// 文件存在則覆蓋掉
byte buffer[] = new byte[1024];
int readsize = 0;
while ((readsize = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, readsize);
downloadCount += readsize;// 時時獲取下載到的大小
/**
* 每次增張5%
*/
if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
updateCount += down_step;
mViews.setTextViewText(R.id.notificationPercent, updateCount + "%");
mViews.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
notificationManager.notify(notification_id, notification);
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
inputStream.close();
outputStream.close();
return downloadCount;
}
}
複製代碼
在須要用的地方,好比登錄的時候檢查服務器與本地的版本
private void checkVersion() {
if (NetWork.isNetworkConnected(LoginActivity.this)) {
LogUtil.d(TAG, "開始檢測更新\n");
if (MyApplication.getInstance().localVersion < MyApplication.getInstance().serverVersion) {
LogUtil.d(TAG, "有新版本,開始更新\n" + "本地version:" + MyApplication.getInstance().localVersion
+ "\n服務器version:" + MyApplication.getInstance().serverVersion);
// 發現新版本,提示用戶更新
AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
alert.setTitle("軟件升級").setMessage("發現新版本,建議當即更新使用.")
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 開啓更新服務UpdateService
updateIntent = new Intent(LoginActivity.this, UpdateService.class);
startService(updateIntent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.create().show();
} else
{
LogUtil.d(TAG, "沒有新版本,無需更新");
}
}
}