package com.example.longfei.monthexam;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//获取Xml
private List<User> data = new ArrayList<>();
//获取版本
private List<Version> aa = new ArrayList<>();
private String path = "http://www.oschina.net/action/api/news_list?catalog=1&pageIndex=0&pageSize=20";
private String path1 = "http://www.oschina.net/MobileAppVersion.xml";
private Button button;
private ListView listView;
private BaseAdapter mAdapter;
private User mUser;
private Version mVersion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
getVersion();
getHttp();
mAdapter = new BaseAdapter() {
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, null);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView context = (TextView) convertView.findViewById(R.id.context);
TextView date = (TextView) convertView.findViewById(R.id.date);
User user = data.get(position);
title.setText(user.getTitle());
context.setText(user.getBody());
date.setText(user.getPubDate());
return convertView;
}
};
listView.setAdapter(mAdapter);
}
private void getVersion() {
HttpUtils utils = new HttpUtils();
utils.send(HttpRequest.HttpMethod.GET, path1, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
System.out.println(responseInfo.result.toString());
getVersionCode(responseInfo.result.toString());
mAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(HttpException e, String s) {
}
});
}
private void getVersionCode(String s) {
try {
XmlPullParser pullParser = Xml.newPullParser();
ByteArrayInputStream stream = new ByteArrayInputStream(s.getBytes());
pullParser.setInput(stream, "utf-8");
int type = pullParser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
String name = pullParser.getName();
switch (type) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if (name.equals("android")) {
mVersion = new Version();
} else if (name.equals("versionCode")) {
mVersion.setVersionCode(pullParser.nextText());
} else if (name.equals("versionName ")) {
mVersion.setVersionName(pullParser.nextText());
} else if (name.equals("downloadUrl")) {
mVersion.setDownloadUrl(pullParser.nextText());
} else if (name.equals("updateLog")) {
mVersion.setUpdateLog(pullParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (name.equals("android")) {
aa.add(mVersion);
}
break;
}
type = pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getHttp() {
HttpUtils utils = new HttpUtils();
utils.send(HttpRequest.HttpMethod.GET, path, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
getXMl(responseInfo.result.toString());
mAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(HttpException e, String s) {
}
});
}
private void getXMl(String s) {
try {
XmlPullParser pullParser = Xml.newPullParser();
ByteArrayInputStream stream = new ByteArrayInputStream(s.getBytes());
pullParser.setInput(stream, "utf-8");
int type = pullParser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
String name = pullParser.getName();
switch (type) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if (name.equals("news")) {
mUser = new User();
} else if (name.equals("title")) {
mUser.setTitle(pullParser.nextText());
} else if (name.equals("body")) {
mUser.setBody(pullParser.nextText());
} else if (name.equals("pubDate")) {
mUser.setPubDate(pullParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (name.equals("news")) {
data.add(mUser);
}
break;
}
type = pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
showDialog();
break;
}
}
private void showDialog() {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setMessage(aa.get(0).getUpdateLog())
.setTitle("软件版本更新").setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
downLoadApk();
}
}
).setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
dialog.show();
}
private 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 = getFileFromServer(aa.get(0).getDownloadUrl(), pd);
sleep(3000);
installApk(file);
pd.dismiss(); //结束掉进度条对话框
} catch (Exception e) {
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);
}
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;
int read = is.read(buffer);
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;
}
}
}
//User
package com.example.longfei.monthexam;
/**
* Created by longfei on 2016/8/24.
*/
public class User {
private String title;
private String body;
private String pubDate;
@Override
public String toString() {
return "User{" +
"title='" + title + '\'' +
", body='" + body + '\'' +
", pubDate='" + pubDate + '\'' +
'}';
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public User() {
}
public User(String title, String body, String pubDate) {
this.title = title;
this.body = body;
this.pubDate = pubDate;
}
}
//Verson
package com.example.longfei.monthexam;
/**
* Created by longfei on 2016/8/24.
*/
public class Version {
private String versionCode;
private String versionName;
private String downloadUrl;
private String updateLog;
@Override
public String toString() {
return "Version{" +
"versionCode='" + versionCode + '\'' +
", versionName='" + versionName + '\'' +
", downloadUrl='" + downloadUrl + '\'' +
", updateLog='" + updateLog + '\'' +
'}';
}
public String getVersionCode() {
return versionCode;
}
public void setVersionCode(String versionCode) {
this.versionCode = versionCode;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public String getUpdateLog() {
return updateLog;
}
public void setUpdateLog(String updateLog) {
this.updateLog = updateLog;
}
public Version() {
}
public Version(String versionCode, String versionName, String downloadUrl, String updateLog) {
this.versionCode = versionCode;
this.versionName = versionName;
this.downloadUrl = downloadUrl;
this.updateLog = updateLog;
}
}