首先先弄一个Service在代码中
接下来 就自己去弄一个UpdateManager到时候在Activity中调用一下就好了
上面几个Dialog其实都是继承了这个ValidDialog,下面的这个dialog是SimpleStyleDialog
/*
* Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com>
*
* 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.cifmedia.starwish.data.common.service;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import com.cifmedia.starwish.R;
import java.io.File;
/**
* 下载apk service
*
* @author BSN
*/
@SuppressLint("NewApi")
public class DownLoadApkService extends Service {
private DownloadManager downloadManager;
private BroadcastReceiver receiver;
private long lastDownloadId = -1L;
private String loadUrl;
public static final String DOWNLOADURL="downloadurl";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate()
{
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if(intent == null){
return;
}
try {
loadUrl = intent.getStringExtra(DOWNLOADURL);
update(loadUrl);
} catch (Exception e) {
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
public void startDownload(String url) {
try {
Uri uri = Uri.parse(url);
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
Request dwreq = new Request(uri);
dwreq.setAllowedNetworkTypes(Request.NETWORK_MOBILE
| Request.NETWORK_WIFI);
String filename ="date_feeling";
dwreq.setTitle(getString(R.string.app_name));
dwreq.setDescription(filename+ System.currentTimeMillis());
dwreq.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, System.currentTimeMillis()+filename);
dwreq.setShowRunningNotification(true);
lastDownloadId = downloadManager.enqueue(dwreq);
} catch (Exception e) {
e.printStackTrace();
}
}
private void update(String url) {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
receiver = new DownloadCompleteReceiver();
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
startDownload(url);
}
class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
//long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(lastDownloadId);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.e("file local url:", filename);
openFile(filename, "application/vnd.android.package-archive");
}
}
context.unregisterReceiver(receiver);
}
}
private void openFile(String fileDir, String mimeType) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File file = new File(fileDir.substring(7));
if (file.exists()) {
intent.setDataAndType(Uri.fromFile(file), mimeType);
startActivity(intent);
stopSelf();
downloadManager=null;
}
}
}
}
然后在AndroidManifest.xml中配置一下
<service android:name=".data.common.service.DownLoadApkService" />
接下来 就自己去弄一个UpdateManager到时候在Activity中调用一下就好了
package com.cifmedia.starwish.data.common.manager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import com.cifmedia.starwish.R;
import com.cifmedia.starwish.data.api.ApiFactory;
import com.cifmedia.starwish.data.api.request.VersionNoRequest;
import com.cifmedia.starwish.data.api.response.QueryAppVersionResponse;
import com.cifmedia.starwish.data.common.service.DownLoadApkService;
import com.cifmedia.starwish.mvp.ui.widget.ForceDialog;
import com.cifmedia.starwish.mvp.ui.widget.SimpleStyleDialog;
import com.zitech.framework.data.network.response.ApiResponse;
import com.zitech.framework.data.network.subscribe.ProgressSubscriber;
import com.zitech.framework.utils.ToastMaster;
import com.zitech.framework.utils.Utils;
public class UpdateManager {
private Context context;
private ProgressDialog mProgressDialog;
public UpdateManager(Context context) {
this.context = context;
}
public synchronized void update(final boolean showDialog) {
if (showDialog)
showUpdateDialog();
VersionNoRequest versionNoRequest = new VersionNoRequest();
versionNoRequest.setVersionNo(Utils.getVersionName(context));
ApiFactory.queryAppVersion(versionNoRequest).subscribe(new ProgressSubscriber<ApiResponse<QueryAppVersionResponse>>(context) {
@Override
public void onNext(ApiResponse<QueryAppVersionResponse> response) {
if (response.getData()!=null){
if (response.getData().getIsUpd() == 1) {
if (response.getData().getLevel() == 0) {
showSuggestUpdateDialog(response.getData().getAppUrl(), response.getData().getDes());
} else {
showMustUpdateDialog(response.getData().getAppUrl(), response.getData().getDes());
}
}
}
}
@Override
public void onError(Throwable e) {
super.onError(e);//
if (mProgressDialog != null) mProgressDialog.dismiss();
}
});
}
private void showUpdateDialog() {
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage("正在检查新版本");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
private void showMustUpdateDialog(final String url, String content) {
ForceDialog dialog = new ForceDialog(context, context.getString(R.string.check_new_version), content);
dialog.setOnConfirmButtonClickListener(new ForceDialog.OnConfirmButtonClickListener() {
@Override
public void onClick(Dialog dialog) {
Intent intent = new Intent(context, DownLoadApkService.class);
intent.putExtra(DownLoadApkService.DOWNLOADURL, url);
context.startService(intent);
ToastMaster.shortToast("开始下载...");
}
});
dialog.show();
}
private void showSuggestUpdateDialog(final String url, String content) {
SimpleStyleDialog dialog = new SimpleStyleDialog(context, content);
dialog.setPositiveButtonText("立即下载");
dialog.setCancelButtonText("稍后再说");
dialog.setOnPositiveButtonClickListener(new SimpleStyleDialog.OnPositiveButtonClickListener() {
@Override
public void onClick(Dialog dialog) {
Intent intent = new Intent(context, DownLoadApkService.class);
intent.putExtra(DownLoadApkService.DOWNLOADURL, url);
context.startService(intent);
ToastMaster.shortToast("开始下载...");
}
});
dialog.show();
}
public boolean isNewVersion(String current, String remote) {
String[] oldArray = current.split("\\.");
String[] newArray = remote.split("\\.");
int length = oldArray.length < newArray.length ? oldArray.length : newArray.length;
for (int i = 0; i < length; i++) {
if (Integer.parseInt(oldArray[i]) < Integer.parseInt(newArray[i]))
return true;
else if (Integer.parseInt(oldArray[i]) > Integer.parseInt(newArray[i]))
return false;
}
return false;
}
}
UpdateManager中的代码
VersionNoRequest versionNoRequest = new VersionNoRequest();
versionNoRequest.setVersionNo(Utils.getVersionName(context));
ApiFactory.queryAppVersion(versionNoRequest).subscribe(new ProgressSubscriber<ApiResponse<QueryAppVersionResponse>>(context) {
@Override
public void onNext(ApiResponse<QueryAppVersionResponse> response) {
if (response.getData()!=null){
if (response.getData().getIsUpd() == 1) {
if (response.getData().getLevel() == 0) {
showSuggestUpdateDialog(response.getData().getAppUrl(), response.getData().getDes());
} else {
showMustUpdateDialog(response.getData().getAppUrl(), response.getData().getDes());
}
}
}
}
@Override
public void onError(Throwable e) {
super.onError(e);//
if (mProgressDialog != null) mProgressDialog.dismiss();
}
});
就是网络请求返回的逻辑 根据自己项目中的框架自己写吧 然后分别去去调用必须跟新showMustUpdateDialog和选择跟新showSuggestUpdateDialog的Dialog其中这两个方法就是
中getData().getAppUrl()是后台服务器返回的App下载地址,response.getData().getDes()是APP下载的跟新说明。
现在就差几个dialog的代码了先给出上面的Dialog的父类
public abstract class ValidDialog extends Dialog {
private Activity mContext;
public ValidDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
setContext(context);
}
public ValidDialog(Context context, int theme) {
super(context, theme);
setContext(context);
}
public ValidDialog(Context context) {
super(context);
setContext(context);
}
private void setContext(Context context) {
if (context instanceof Activity) {
mContext = (Activity) context;
}
}
@Override
public void show() {
if (isActivityActive()) {
try {
super.show();
} catch (Exception e) {
}
}
}
@Override
public void dismiss() {
if (isActivityActive()) {
try {
super.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected boolean isActivityActive() {
return mContext == null || !mContext.isFinishing();
}
}
上面几个Dialog其实都是继承了这个ValidDialog,下面的这个dialog是SimpleStyleDialog
首先在R.styles.xml中增加一个公共的Style
<style name="CommonDialog" parent="android:Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:backgroundDimEnabled">true</item>
</style>
这个就是SimpleStyleDialog
public class SimpleStyleDialog extends ValidDialog {
private TextView contentView;
private RippleButton confirm;
private RippleButton cancel;
private OnPositiveButtonClickListener onPositiveButtonClickListener;
public SimpleStyleDialog(Context context, int resId) {
this(context,context.getString(resId));
}
// private TextView titleView;
public interface OnPositiveButtonClickListener {
public void onClick(Dialog dialog);
}
public SimpleStyleDialog(Context context, String content) {
super(context, R.style.CommonDialog);
setContentView(R.layout.dialog_simple_style);
contentView = (TextView) findViewById(R.id.content);
// titleView = (TextView) findViewById(R.id.title);
// titleView.setText(title);
contentView.setText(content);
confirm = (RippleButton) findViewById(R.id.confirm);
cancel = (RippleButton) findViewById(R.id.cancle);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
if (onPositiveButtonClickListener != null)
onPositiveButtonClickListener.onClick(SimpleStyleDialog.this);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancel();
}
});
}
public void setPositiveButtonText(String text) {
confirm.setText(text);
}
public void setCancelButtonText(String text){
cancel.setText(text);
}
public void setOnPositiveButtonClickListener(OnPositiveButtonClickListener onPositiveButtonClickListener) {
this.onPositiveButtonClickListener = onPositiveButtonClickListener;
}
}
下面就是上面的Dialog的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@drawable/bg_white_rectangle_corner_r20"
android:orientation="vertical">
<TextView
android:id="@+id/content"
style="@style/CommonText"
android:layout_width="@dimen/w490"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/h48"
android:textSize="@dimen/w28"
android:paddingLeft="@dimen/w48"
android:paddingRight="@dimen/w48"
tools:text="一个简单对话提示狂"
android:layout_marginLeft="@dimen/w30"
android:layout_marginRight="@dimen/w30"
android:gravity="center"
/>
<View
style="@style/DividerLineHorizontal"
android:layout_marginTop="@dimen/h48"
android:background="@color/divider_color" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="@dimen/h96"
android:orientation="horizontal" >
<com.cifmedia.starwish.mvp.ui.widget.RippleButton
app:rv_color="@color/rippleColorGray"
android:id="@+id/cancle"
style="@style/CommonText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="取消"
android:textColor="#868B90"
android:textSize="@dimen/w28"
android:background="@null"
app:rv_background="@drawable/trans_background_light_ripple"
/>
<View
style="@style/DividerLineVertical"
android:background="@color/divider_color" />
<com.cifmedia.starwish.mvp.ui.widget.RippleButton
app:rv_color="@color/rippleColorGray"
android:id="@+id/confirm"
style="@style/CommonText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="确定"
android:textColor="#24DECA"
android:textSize="@dimen/w28"
android:background="@null"
app:rv_background="@drawable/trans_background_light_ripple"/>
</LinearLayout>
</LinearLayout>
下面这个就是必须更新的dialog
public class ForceDialog extends ValidDialog {
private TextView contentView;
private TextView confirm;
private OnConfirmButtonClickListener onConfirmButtonClickListener;
private TextView titleView;
private OnKeyListener keylistener = new OnKeyListener(){
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode== KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0){
return true;
}else{
return false;
}
}
} ;
public interface OnConfirmButtonClickListener {
public void onClick(Dialog dialog);
}
public ForceDialog(Context context, String title, String content) {
super(context, R.style.CommonDialog);
setContentView(R.layout.dialog_force);
contentView = (TextView) findViewById(R.id.content);
setCanceledOnTouchOutside(false);
setOnKeyListener(keylistener);
titleView = (TextView) findViewById(R.id.title);
titleView.setText(title);
contentView.setText(content);
confirm = (TextView) findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
if (onConfirmButtonClickListener != null)
onConfirmButtonClickListener.onClick(ForceDialog.this);
}
});
}
public void setPositiveButtonText(String text){
confirm.setText(text);
}
public void setOnConfirmButtonClickListener(OnConfirmButtonClickListener onConfirmButtonClickListener) {
this.onConfirmButtonClickListener = onConfirmButtonClickListener;
}
}
下面就是布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:background="@drawable/bg_white_rectangle_corner_r20"
android:orientation="vertical">
<TextView
android:id="@+id/title"
style="@style/CommonText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/h48"
android:gravity="center"
android:text="提示"
android:textSize="@dimen/w40" />
<TextView
android:id="@+id/content"
style="@style/CommonText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/h29"
android:gravity="center"
android:paddingLeft="@dimen/w48"
android:paddingRight="@dimen/w48"
tools:text="发现新版本,强制更新!"
android:textSize="@dimen/w28" />
<View
style="@style/DividerLineHorizontal"
android:layout_width="match_parent"
android:layout_marginTop="@dimen/h48"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="@dimen/h100"
android:orientation="horizontal" >
<TextView
android:id="@+id/confirm"
style="@style/CommonText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="更新"
android:textSize="@dimen/w32" />
</LinearLayout>
</LinearLayout>
其中的RippleButton这些都是控件可以替换成Button等 在xml中替换了 不要忘记了在dialog中findViewById的地方替换一下
··················
接下来说怎么使用了其实使用很简单
在Activity中的onCreate方法调用这个方法就好了
protected void checkUpdate() {
new UpdateManager(this).update(false);
}
上面的几个dialog也是比较通用的