package com.tools.update;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.app.ProgressDialog;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Xml;

public class DownLoadManager
{

 public static File getFileFromServer(String path, ProgressDialog pd) throws Exception
 { 
  //如果相等的话表示当前的sdcard挂载在手机上并且是可用的 
  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
  { 
   URL url = new URL(path); 
   HttpURLConnection conn =  (HttpURLConnection) url.openConnection(); 
   conn.setConnectTimeout(5000); 
   //获取到文件的大小  
   pd.setMax(conn.getContentLength()); 
   InputStream is = conn.getInputStream(); 
   File file = new File(Environment.getExternalStorageDirectory(), "updata.apk"); 
   FileOutputStream fos = new FileOutputStream(file); 
   BufferedInputStream bis = new BufferedInputStream(is); 
   byte[] buffer = new byte[1024]; 
   int len ; 
   int total=0; 
   while((len =bis.read(buffer))!=-1)
   { 
    fos.write(buffer, 0, len); 
    total+= len; 
    //获取当前下载量 
    pd.setProgress(total); 
   } 
   fos.close(); 
   bis.close(); 
   is.close(); 
   return file; 
  } 
  else{ 
   return null; 
  } 
 } 
}

 

 

UpdataInfo.java

 

package com.tools.update;
 public class UpdataInfo
 { 
  private String version; 
  private String url; 
  private String description; 
  
  public String getVersion()
  { 
   return version; 
  }
  
  public void setVersion(String version)
  { 
   this.version = version; 
  }
  
  public String getUrl()
  { 
   return url; 
  }
  
  public void setUrl(String url)
  { 
   this.url = url; 
  }
    
  public String getDescription()
  { 
   return description; 
  }
     
  public void setDescription(String description)
  { 
   this.description = description; 
  } 
 } 

 

UpdataInfoParser.java

 

package com.tools.update;

import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class UpdataInfoParser
{
 
  
 public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{ 
  XmlPullParser  parser = Xml.newPullParser();   
  parser.setInput(is, "utf-8");//设置解析的数据源  
  int type = parser.getEventType(); 
  UpdataInfo info = new UpdataInfo();//实体 
  while(type != XmlPullParser.END_DOCUMENT )
  { 
   switch (type)
   { 
    case XmlPullParser.START_TAG: 
     if("version".equals(parser.getName()))
     { 
      info.setVersion(parser.nextText()); //获取版本号 
     }else if ("url".equals(parser.getName()))

 

     { 
      info.setUrl(parser.nextText()); //获取要升级的APK文件 
     }else if ("description".equals(parser.getName()))
     { 
      info.setDescription(parser.nextText()); //获取该文件的信息 
     } 
     break; 
   } 
    type = parser.next(); 
  } 
   return info; 
 }  
}

 

 

 

update.java

 

package com.tools.update;


import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.tools.update.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class update extends Activity {
 
 
 private UpdataInfo info = new UpdataInfo();
 private final String TAG = "updataActivity";
 private final int UPDATA_CLIENT = 1;
 private final int GET_UNDATAINFO_ERROR = 2;
 private final int DOWN_ERROR = 3; 
 private String versionname;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        try {
   versionname = getVersionName();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        CheckVersionTask CheckVersionTask_test =  new CheckVersionTask();
        CheckVersionTask_test.run();
      
    }
   
  
 private String getVersionName() throws Exception{ 
     //获取packagemanager的实例  
     PackageManager packageManager = getPackageManager(); 
     //getPackageName()是你当前类的包名,0代表是获取版本信息 
     PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0); 
     return packInfo.versionName;  
 }    

  
 public class CheckVersionTask implements Runnable
 { 
  public void run()
  { 
   try
   { 
    Log.i(TAG,"CheckVersionTask!!!!!!!!!!!!");
    //从资源文件获取服务器 地址  
    String path = getResources().getString(R.string.serverurl); 
    //包装成url的对象  
    URL url = new URL(path); 
    HttpURLConnection conn =  (HttpURLConnection) url.openConnection();  
    conn.setConnectTimeout(5000); 
    InputStream is =conn.getInputStream();  
    info =  UpdataInfoParser.getUpdataInfo(is); 
 
    if(info.getVersion().equals(versionname))
    { 
     Log.i(TAG,"版本号相同无需升级"); 
     LoginMain(); 
    }
    else
    { 
     Log.i(TAG,"版本号不同 ,提示用户升级 "); 
     Message msg = new Message(); 
     msg.what = UPDATA_CLIENT; 
     handler.sendMessage(msg); 
    } 
   }
   catch (Exception e)
   { 
    // 待处理  
    Message msg = new Message(); 
    msg.what = GET_UNDATAINFO_ERROR; 
    handler.sendMessage(msg); 
    e.printStackTrace(); 
   }  
  } 
 } 
 
 
 Handler handler = new Handler(){  
  @Override 
  public void handleMessage(Message msg)
  { 
   // TODO Auto-generated method stub 
   super.handleMessage(msg); 
   switch (msg.what)
   { 
    case UPDATA_CLIENT: 
     //对话框通知用户升级程序  
     showUpdataDialog(); 
     break; 
    case GET_UNDATAINFO_ERROR: 
     //服务器超时  
     Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", 1).show(); 
     LoginMain(); 
     break;   
    case DOWN_ERROR: 
     //下载apk失败 
     Toast.makeText(getApplicationContext(), "下载新版本失败", 1).show(); 
     LoginMain(); 
     break;   
   } 
  } 
 }; 

  
  
 protected void showUpdataDialog()
 { 
  AlertDialog.Builder builer = new Builder(this) ;  
  builer.setTitle("版本升级"); 
  builer.setMessage(info.getDescription()); 
  //当点确定按钮时从服务器上下载 新的apk 然后安装  
  builer.setPositiveButton("确定", new OnClickListener()
  { 
   public void onClick(DialogInterface dialog, int which)
   { 
    Log.i(TAG,"下载apk,更新"); 
    downLoadApk(); 
   }    
  }); 
  //当点取消按钮时进行登录 
  builer.setNegativeButton("取消", new OnClickListener()
  { 
   public void onClick(DialogInterface dialog, int which)
   { 
     // TODO Auto-generated method stub 
     LoginMain(); 
   } 
  }); 
  AlertDialog dialog = builer.create(); 
  dialog.show(); 
 } 
  
  
 protected void downLoadApk() { 
   final ProgressDialog pd;    //进度条对话框 
   pd = new  ProgressDialog(this); 
   pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
   pd.setMessage("正在下载更新"); 
   pd.show(); 
   new Thread(){ 
    @Override 
    public void run() { 
     try { 
      File file = DownLoadManager.getFileFromServer(info.getUrl(), pd); 
      sleep(3000); 
      installApk(file); 
      pd.dismiss(); //结束掉进度条对话框 
     } catch (Exception e) { 
      Message msg = new Message(); 
      msg.what = DOWN_ERROR; 
      handler.sendMessage(msg); 
      e.printStackTrace(); 
     } 
    }}.start(); 
  } 

 

 
 //安装apk  
 protected void installApk(File file) { 
   Intent intent = new Intent(); 
   //执行动作 
   intent.setAction(Intent.ACTION_VIEW); 
   //执行的数据类型 
   intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); 
   startActivity(intent); 
 } 
 
  
 private void LoginMain(){ 
  // Intent intent = new Intent(this,MainActivity.class); 
  // startActivity(intent); 
   //结束掉当前的activity  
   this.finish(); 
 }     
}

 

 

main.xml

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

 

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, updata!</string>
    <string name="app_name">Updata_samples</string>
    <string name="serverurl">http://172.16.129.122:9000/update.xml</string>    
    <!--  string name="serverurl">http://192.168.1.187:8080/</string-->  
</resources>

 

AndroidManifest.xml

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tools.update"
    android:versionCode="1"
    android:versionName="1.0.0" >

    <uses-sdk android:minSdkVersion="8" />
   
 <!--  permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/-->
    <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.tools.update.update"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

update.xml

该文件是放在服务器上,该文件维护最新版本信息,及最新文件的地址

<?xml version="1.0" encoding="utf-8"?> 
<info> 
 <version>2.0</version> 
 <url>http://172.16.129.122:9000/updata_samples.apk</url> 
 <description>检测到最新版本,请及时更新!</description> 
</info> 

    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()