天天看点

android app 版本更新

android app 的版本更新(自己的app 要求是这样,进入首页,如果服务器上面有新的版本,进入首页,就会自动弹出一alertDialog,提示用户更新,接下来我会把文档写细点)

第一步:获得服务器的版本号

我这里是一个方法:在onCreate里面写一个方法  

//获得版本号

        initVersion();

第二步:写异步网络请求方法(这里是我自己独特的网络请求框架,你们应该也有自己的网络请求框架)

 private void initVersion() {

        AbstractCommonData acd = DataConvertFactory.getInstanceEmpty();

        acd.putStringValue("url", App.BASEURL + "/index.php/Webservice/getUpdatedVersionWS?client=2");

        acd.putObjectValue("iservice", new IServiceLogic() {

            @Override

            public AbstractCommonData doSuccess(AbstractCommonData acd) {

                // TODO Auto-generated method stub

                // Log.e("---------", "-----a1---" + acd);

                VersionNum = acd.getDataValue("data").getFloatValue("android_version");

                apkurl = acd.getDataValue("data").getStringValue("android_url");

                //Log.e("---------", "-----aaaaaa-apkurl--" + apkurl);

                updateVersion();

                return null;

            }

            @Override

            public AbstractCommonData doError(AbstractCommonData acd) {

                // TODO Auto-generated method stub

                return null;

            }

        });

        ServiceController.addService(acd, this);

    }

第三步:获得本地的版本号和服务器的版本号

    public int getlocalVersion() {

        int localversion = 0;

        try {

            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);

            localversion = info.versionCode;

        } catch (PackageManager.NameNotFoundException e) {

            e.printStackTrace();

        }

        return localversion;

    }

    public int getServiceVersion() {

        int serviceversion = VersionNum.intValue();

        return serviceversion;

    }

第四步:弹出框,弹出是否版本更新(代码)

    public void updateVersion() {

        if (getServiceVersion() > getlocalVersion()) {

            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(IndexActivity.this);

            builder.setTitle("检查到新版本");

            builder.setMessage("是否更新");

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int which) {

                }

            });

            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int which) {

                    startService(new Intent(IndexActivity.this, UpdateService.class));

                }

            });

            builder.create().show();

        } else {

            Toast.makeText(IndexActivity.this, "当前没有新版本", Toast.LENGTH_SHORT).show();

        }

    }

第五步:启动service  ,开启下载(下载地址我写死了,可以更改)

UpdateService .java

package service;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.net.Uri;

import android.os.Environment;

import android.os.Handler;

import android.os.IBinder;

import android.os.Message;

import android.util.Log;

import android.widget.RemoteViews;

import android.widget.Toast;

import com.example.myproject.IndexActivity;

import com.example.myproject.R;

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;

import frg.HelpFragment;

public class UpdateService extends Service {

private String apkurl = "http://www.xwjiang.com/estudy.apk";

private String apkPath;

private String apkName;

private boolean canceled = false;

private NotificationManager manager;

private Notification notification;

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public void onCreate() {

super.onCreate();

Log.e("-----a----", "-----a1---" +apkurl);

if (Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED)) {

apkPath = Environment.getExternalStorageDirectory()

.getAbsolutePath() + "/update";

apkName = "tools.apk";

registerBroader();

setUpNotifiction();

new Thread(new DownApkRunnable()).start();

} else {

Toast.makeText(UpdateService.this, "SD卡不存在", Toast.LENGTH_SHORT)

.show();

}

}

private void setUpNotifiction() {

manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);

int icon = R.drawable.ic_launcher;

CharSequence tickerText = "开始下载";

long when = System.currentTimeMillis();

notification = new Notification(icon, tickerText, when);

RemoteViews contentView = new RemoteViews(getPackageName(),

R.layout.notify_update_layout);

contentView.setTextViewText(R.id.name, "易思达正在下载中");

Intent canceledIntent = new Intent("canceled");

canceledIntent.putExtra("canceled", "canceled");

PendingIntent canceledPendingIntent = PendingIntent.getBroadcast(

UpdateService.this, 1, canceledIntent,

PendingIntent.FLAG_UPDATE_CURRENT);

contentView.setOnClickPendingIntent(R.id.cancle, canceledPendingIntent);

notification.contentView = contentView;

Intent intent = new Intent(UpdateService.this, HelpFragment.class);

PendingIntent contentIntent = PendingIntent.getActivity(

UpdateService.this, 0, intent,

PendingIntent.FLAG_UPDATE_CURRENT);

notification.contentIntent = contentIntent;

manager.notify(0, notification);// 发送通知

}

class CanceledReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

if ("canceled".equals(intent.getStringExtra("canceled"))) {

canceled = true;

manager.cancel(0);

stopSelf();

}

}

}

public void registerBroader() {

IntentFilter filter = new IntentFilter();

filter.addAction("canceled");

registerReceiver(new CanceledReceiver(), filter);

}

class DownApkRunnable implements Runnable {

@Override

public void run() {

downloadApk();

}

}

private int laterate = 0;

private void downloadApk() {

try {

URL url = new URL(apkurl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

int length = conn.getContentLength();

int count = 0;

File apkPathFile = new File(apkPath);

if (!apkPathFile.exists()) {

apkPathFile.mkdir();

}

File apkFile = new File(apkPath, apkName);

InputStream in = conn.getInputStream();

FileOutputStream os = new FileOutputStream(apkFile);

byte[] buffer = new byte[1024];

do {

int numread = in.read(buffer);

count += numread;

int progress = (int) (((float) count / length) * 100);// 得到当前进度

if (progress >= laterate + 1) {// 只有当前进度比上一次进度大于等于1,才可以更新进度

laterate = progress;

Message msg = new Message();

msg.what = 1;

msg.arg1 = progress;

handler.sendMessage(msg);

}

if (numread <= 0) {// 下载完毕

handler.sendEmptyMessage(2);

canceled = true;

break;

}

os.write(buffer, 0, numread);

} while (!canceled);// 如果没有被取消

in.close();

os.close();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.toString();

e.printStackTrace();

}

}

Handler handler = new Handler() {

public void handleMessage(Message msg) {

switch (msg.what) {

case 1:// 更新进度

int progress = msg.arg1;

if (progress < 100) {

RemoteViews contentView = notification.contentView;

contentView.setTextViewText(R.id.tv_progress, progress

+ "%");

contentView.setProgressBar(R.id.progressbar, 100, progress,

false);

} else {// 下载完成,停止服务

stopSelf();

}

manager.notify(0, notification);

break;

case 2:// 安装apk

manager.cancel(0);

installApk();

break;

default:

break;

}

}

};

private void installApk() {

File apkFile = new File(apkPath, apkName);

if (!apkFile.exists()) {

return;

}

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),

"application/vnd.android.package-archive");

startActivity(intent);

}

}