Android 服務器之更新

剛剛做完一個關於服務器升級的demo,在此和大家分享下。
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
步聚一:
Manifest.xml
先給Manifest.xml添加聯網權限,讀寫SD卡權限,版本號versionCode和版本名versionName,其中versionCode用來比較版本使用的變量,versionName爲用於顯示在界面上的版本字符串。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.android.com/apk/res/android"
    package="com.example.servertest2"
    android:versionCode="1"
    android:versionName="1.0" >
 <uses-permission android:name='android.permission.INTERNET'/> <!-- 聯網權限 -->  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  <!-- 寫入SD卡權限 -->  
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    <!-- 在SD卡中創建和刪除文件的權限 -->  
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>

步二:
activity_main.xml
佈局文件,簡單的幾個控件。
代碼:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.eric.androidupdatedemo.MainActivity" >
<TextView
android:id="@+id/textview_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"         android:text="@string/hello_world" />

 <Button 
android:id="@+id/button_id"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_below="@id/textview_id"
android:textColor="#FFF"
android:text="檢查更新"
android:background="@android:color/black"
/>
<ProgressBar 
android:id="@+id/progressBar_id"
style="@android:style/Widget.ProgressBar.Small"  
android:layout_width="match_parent" android:layout_height="40dp"
android:layout_below="@id/button_id"
android:layout_marginTop="10dp"
android:visibility="gone"/>
</RelativeLayout>

步三:
MainActivity.Java
界面初始化,調用更新類的方法,刷新頁面數據
代碼:

packagecom.example.servertest2;
import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
private TextView textView;
public static int version, serverVersion;
public static String versionName, serverVersionName, downloadResult;
private Button btn;
private ProgressBar proBar;
public static receiveVersionHandler handler;
private UpdateManager manager =UpdateManager.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView = (TextView) findViewById(R.id.textview_id);
btn = (Button) findViewById(R.id.button_id);
proBar = (ProgressBar) findViewById(R.id.progressBar_id);
Context c = this;
version = manager.getVersion(c);
textView.setText("當前版本號:" + version );
handler = new receiveVersionHandler();
// 檢查更新按鈕點擊事件
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
manager.compareVersion(MainActivity.this);
}
});
}
public class receiveVersionHandler extends Handler {
@Override
public void handleMessage(Message msg) {
final ProgressDialog p = new ProgressDialog(MainActivity.this);
p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
p.setTitle("正在下載");
p.setIndeterminate(true);
p.setButton("取消", new ProgressDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
p.dismiss();
}
});
p.show();
if (msg.arg1 == 1) {
p.dismiss();
ProgressDialog t = new ProgressDialog(MainActivity.this);
t.setProgressStyle(ProgressDialog.STYLE_SPINNER);
t.setTitle("下載成功");
t.setIndeterminate(true);
t.setButton("確定", new ProgressDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = Environment.getExternalStorageDirectory() + "/CarsailSDK.apk";
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
startActivity(intent);
}
});
t.show();
}
}
}
}

步四:
UpdateManager.java
更新工具類,包含獲取本地版本信息,服務器版本信息,下載apk文件等方法。
代碼:

packagecom.example.servertest2;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.integer;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.ContactsContract.Contacts.Data;
import android.renderscript.Int2;
import android.util.Log;

public class UpdateManager {
int version = 0;
int versionnxt = 0;
private static UpdateManager manager = null;
public int getVersionnxt() {
return versionnxt;
}

public void setVersionnxt(int versionnxt) {
this.versionnxt = versionnxt;
}
private UpdateManager() {

}

public static UpdateManager getInstance() {

manager = new UpdateManager();

return manager;

}
// 獲取版本號
public int getVersion(Context context) {
try {

version =context.getPackageManager().getPackageInfo("com.eric.androidupdatedemo", 0).versionCode;

} catch (Exception e) {

System.out.println("獲取版本號異常!");

}

return version;

}

// 獲取版本名

public String getVersionName(Context context) {

String versionName = null;

try {

versionName = context.getPackageManager().getPackageInfo("com.eric.androidupdatedemo", 0).versionName;

} catch (Exception e) {

System.out.println("獲取版本名異常!");

}

return versionName;

}

// 獲取服務器版本號

public String getServerVersion() {

String serverJson = null; 
byte[] buffer = new byte[1024];

try {
URL serverURL = new URL("http://192.168.199.218/ver.aspx");
HttpURLConnection connect = (HttpURLConnection) serverURL.openConnection();
BufferedInputStream bis = new BufferedInputStream(connect.getInputStream());
int n = 0;
while ((n = bis.read(buffer)) != -1) {
serverJson = new String(buffer);
}
} catch (Exception e) {
System.out.println("獲取服務器版本號異常!" + e);
}
return serverJson;
}

// 比較服務器版本與本地版本彈出對話框

public boolean compareVersion(Context context) {
final Context contextTemp = context;
new Thread() {
public void run() {
Looper.prepare();
String serverJson = manager.getServerVersion();
// 解析Json數據
try {

JSONArray array = new JSONArray(serverJson);

JSONObject object = array.getJSONObject(0);

String getServerVersion = object.getString("version");

String getServerVersionName = object.getString("versionName");

Integer serverversion = new Integer(getServerVersion);

int versionnxt = serverversion;

System.out.println("serverversion" + serverversion + "!!version+" + version);

if (version < serverversion) {

// 彈出一個對話框

AlertDialog.Builder builder = new Builder(contextTemp);

builder.setTitle("版本更新");

builder.setMessage("當前版本:" + version + "\n" +
"服務器版本:" + serverversion);

builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int arg1) {

// 開啓線程下載apk

new Thread() {

public void run() {

Looper.prepare();

downloadApkFile(contextTemp);

Looper.loop();

};

}.start();

}

});

builder.setNegativeButton("下次再說", null);

builder.show();

} else {

AlertDialog.Builder builder = new Builder(contextTemp);

builder.setTitle("版本信息");

builder.setMessage("當前已經是最新版本");

builder.setPositiveButton("確定", null);

builder.show();

}

} catch (JSONException e) {

e.printStackTrace();

System.out.println("獲取服務器版本線程異常!" + e);

}

Looper.loop();

};

}.start();

return false;

}

// 下載apk文件

public void downloadApkFile(Context context) {

String savePath = Environment.getExternalStorageDirectory() + "/test.apk";

String serverFilePath = "http://192.168.199.218/test.png";

try {

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

URL serverURL = new URL(serverFilePath);

HttpURLConnection connect = (HttpURLConnection) serverURL.openConnection();

BufferedInputStream bis = new BufferedInputStream(connect.getInputStream());

File apkfile = new File(savePath);

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(apkfile));

long fileLength = connect.getContentLength();

Log.e("fileLength", "" + fileLength);

int downLength = 0;

int progress = 0;

int n;

byte[] buffer = new byte[1024];

while ((n = bis.read(buffer)) != -1) {

bos.write(buffer, 0, n);

downLength += n;

}

bis.close();

bos.close();

connect.disconnect();

Message msg = new Message();

msg.arg1 = 1;

MainActivity.handler.sendMessage(msg);

}

} catch (Exception e) {

System.out.println("下載出錯!" + e);

}

}

}

最後導入commons-net-2.2.jar。
注:
downloadApkFile(Context context)下載apk文件:
設置文件保存路徑,服務器訪問路徑,通過HTTP協議下載文件,這裏測試的時候,apk文件無法下載,故將服務器的apk修改擴展名爲png格式,下載完成後保存爲apk文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章