您的位置:首页 > 理论基础 > 计算机网络

软件自动更新提示和安装

2014-06-24 10:55 351 查看
第一步:写Activity页面(用异步线程做)

package com.geek.sjws.activity;

import java.io.File;

import com.geek.sjws.MainActivity;

import com.geek.sjws.R;

import com.geek.sjws.entity.Updateinfo;

import com.geek.sjws.service.ServiceActivity;

import android.app.Activity;

import android.app.AlertDialog;

import android.app.ProgressDialog;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.DialogInterface.OnClickListener;

import android.content.SharedPreferences;

import android.net.Uri;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.widget.FrameLayout;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.TextView;

import android.widget.Toast;

public class RenewActivity extends Activity {
ServiceActivity serviceActivity;
//虚拟机访问路径
public static final String URL = "http://10.0.2.2:8080/service/updateinfo.xml";

     //真机访问路径
// public static final String URL = "http://192.168.43.13:8080/service/updateinfo.xml";
public String url2 = "";
int versionCode = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gengxinlayout);

new renew().execute(URL);

}

// 检查更新
class renew extends AsyncTask<String, Object, Updateinfo> {
ProgressDialog pd = null;

// 异步线程启动之前调用
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = new ProgressDialog(RenewActivity.this);
// 设置标题
pd.setTitle("正在开启梦幻手机");
// 设置进度条的风格
pd.show();

}

// 异步线程运行时调用
@Override
protected Updateinfo doInBackground(String... params) {
// TODO Auto-generated method stub
try {
// 拿到一个服务类的实例
serviceActivity = new ServiceActivity(RenewActivity.this);
// 调用服务类
return serviceActivity.jieXiUpdateinfo(params[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

// 异步线程运行之后调用
@Override
protected void onPostExecute(Updateinfo result) {
// TODO Auto-generated method stub
try {
// 获取应用本身最新版本号
versionCode = getPackageManager().getPackageInfo(
getPackageName(), 0).versionCode;
// 判断是否为空
if (result != null) {
// 服务器的版本号比自身的版本号大就进
if (result.getVersion() > versionCode) {
// 关闭上一个对话框
pd.cancel();
//拿到服务器上的xml文件中的最新版本路径
url2 = result.getUrl();
//拿到一个对话框实例
AlertDialog.Builder ad = new AlertDialog.Builder(RenewActivity.this);
ad.setTitle("更新提示");
ad.setMessage(result.getDescription());
ad.setPositiveButton("确定", new OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
//启动线程下载最新版本
new banbeigengxin().execute(url2);

}

});
ad.setNegativeButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(RenewActivity.this, "你点击的是取消",
1000).show();
//跳转页面
Intent intent = new Intent();
intent.setClass(RenewActivity.this,
MainActivity.class);
startActivityForResult(intent, 300);
}
});
ad.show();
//如果服务器的版本号不比自身的版本号大就不用更新
} else {

Intent intent = new Intent();
intent.setClass(RenewActivity.this, MainActivity.class);
startActivity(intent);
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

// 异步线程任务结束之后调用
@Override
protected void onCancelled() {

}

}

// 更新版本的异步线程
class banbeigengxin extends AsyncTask<String, Object, File> {
ProgressDialog pd = null;

// 这个异步线程启动之前调用
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = new ProgressDialog(RenewActivity.this);
// 设置标题
pd.setTitle("正在下载最新版本");
// 设置进度条的风格
pd.show();
super.onPreExecute();
}

// 这个异步线程启动之时调用
@Override
protected File doInBackground(String... params) {
serviceActivity = new ServiceActivity(RenewActivity.this);
return serviceActivity.downloadFile(params[0]);

}

// 这个异步线程启动之后调用
@Override
protected void onPostExecute(File result) {
System.out.println(result);
if (result != null) {
pd.cancel();
//调安装方法
install(result);
}
}

// 这个异步线程任务结束之后调用
@Override
protected void onCancelled() {

super.onCancelled();
}

}

// 安装最新版本
public void install(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
startActivity(intent);

}

}

第二步:写服务类方法

package com.geek.sjws.service;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.Serializable;

import java.io.StringReader;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import org.xmlpull.v1.XmlPullParser;

import org.xmlpull.v1.XmlPullParserException;

import com.geek.sjws.entity.Updateinfo;

import android.content.Context;

import android.os.Environment;

import android.util.Xml;

public class ServiceActivity implements Serializable{

    Context context;

    public ServiceActivity(Context context){

    this.context=context;

    }

    //解析Updateinfo.xml

    public Updateinfo jieXiUpdateinfo(String url) throws Exception{

    System.out.println("进来了++++++++++++++++");

    //定义一个实体类

    Updateinfo updateinfo=null;

    //创建一个浏览器

    HttpClient httpClient=new DefaultHttpClient();

    //创建一个HttpPost请求对象

    HttpPost post=new HttpPost(url);

    //// 执行请求(得到相应对象)

    HttpResponse response=httpClient.execute(post);

    // 得到状态行获得状态码(如果==200就表示请求成功)

    if(response.getStatusLine().getStatusCode()==200){

    // 得到XML

    String xml=EntityUtils.toString(response.getEntity());

    //调用 jieXiHttpEntity(String xml)方法返回实体

    updateinfo=jieXiHttpEntity(xml);

    }

    return updateinfo;

    }

    //解析服务器传过来的XML

    public Updateinfo jieXiHttpEntity(String xml) throws Exception{

    //定义一个实体类

    Updateinfo updateinfo=null;

    //获取XmlPullParser实例

    XmlPullParser xpp=Xml.newPullParser();

    //设置编码

    xml=new String(xml.getBytes("ISO-8859-1"),"utf-8");

    //设置输入流

    xpp.setInput(new StringReader(xml));

    //获得状态

    int type=xpp.getEventType();

    //拿到一个实例

    updateinfo=new Updateinfo();

    //如果状态不是文档尾就进while循环

    while (type!=XmlPullParser.END_DOCUMENT) {

    //接收返回的标签名
String filenname=xpp.getName();
//判断状态是不是开始标签
 switch (type) {
 //如果是开始标签
    case XmlPullParser.START_TAG:
   
     if(filenname.equalsIgnoreCase("version")){
     int id=Integer.parseInt(xpp.nextText());
     updateinfo.setVersion(id);
   
     }else if(filenname.equalsIgnoreCase("description")){
             String name=xpp.nextText();
     updateinfo.setDescription(name);
   
     }else if(filenname.equalsIgnoreCase("url")){

     String urii=xpp.nextText();
     updateinfo.setUrl(urii);
   
     }
break;

}
type=xpp.next();
}

    return updateinfo;

    }

    //下载最新版本的软件

    public File downloadFile(String url){

    File file=null;

    File path=null;

    String filename=null;

    InputStream is=null;

    OutputStream os=null;

    try {

    //判断SD卡状态是否存在

    if(Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)){

    //获得sd卡的路径目录

    path=Environment.getExternalStorageDirectory();

    //调用截取字符串的方法  把这个穿进去的路径截取出来文件名

    filename=url.substring(url.lastIndexOf("/")+1);

   

   

    //创建一个文件路径

    file =new File(path,filename);

    //判断如果文件存在的话就删除掉

    if(file.exists()){

    file.delete();

    }

    //在创建这个文件
file.createNewFile();

HttpClient httpClient =new DefaultHttpClient();
HttpPost httpPost=new HttpPost(url);
HttpResponse response=httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode()==200) {
is=response.getEntity().getContent();

os=new FileOutputStream(file);
int leng=0;
byte[] by=new byte[1024];
while ((leng=is.read(by))!=-1) {
os.write(by,0,leng);
}
}

       }
} catch (Exception e) {
e.printStackTrace();
}finally{
//把两个流关闭掉
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

   

    return file;

    }

    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐