檢測新版本,PullToRefreshListView重新整理,載入
阿新 • • 發佈:2019-02-11
做了一個小Demo,功能有:
應用程式更新實體類
佈局檔案xml
所有的主配置
頭一次寫,請大家
提出意見
檢測新版本
HttpUrlConnection + Thread + Handler完成網路請求
PullToRefreshListView重新整理,載入
效果如圖
程式碼如下:
首先需要匯入關於PullToRefresh的包,
主函式
listview介面卡import java.io.InputStream; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.GridView; import com.bwei.test.adapter.MyBaseAdapter; import com.bwei.test.bean.News; import com.bwei.test.utils.Network; import com.bwei.test.utils.UpdateVersionutil; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshGridView; public class MainActivity extends Activity { private String path="http://www.oschina.net/action/api/news_list?catalog=1&pageIndex=0&pageSize=20"; Handler handler=new Handler(){ public void handleMessage(android.os.Message msg) { if (msg.what==0) { List<News> list=(List<News>) msg.obj; MyBaseAdapter myBaseAdapter = new MyBaseAdapter(list, MainActivity.this); listView.setAdapter(myBaseAdapter); listView.setOnRefreshListener(new OnRefreshListener2<GridView>() { @Override public void onPullDownToRefresh( PullToRefreshBase<GridView> refreshView) { // TODO Auto-generated method stub listView.onRefreshComplete(); } @Override public void onPullUpToRefresh( PullToRefreshBase<GridView> refreshView) { // TODO Auto-generated method stub listView.onRefreshComplete(); } }); } else { } }; }; private PullToRefreshGridView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (PullToRefreshGridView) findViewById(R.id.lv_view); setData("http://www.oschina.net/action/api/news_list?catalog=1&pageIndex=0&pageSize=20"); } private void setData(final String path) { // TODO Auto-generated method stub new Thread(){ public void run() { InputStream getinput = Network.getinput(path); Log.i("tag", getinput.toString()+"**************************"); List<News> pullxml = Network.pullxml(getinput); Log.e("tag", pullxml.toString()); handler.obtainMessage(0, pullxml).sendToTarget(); }; }.start(); } public void button(View view ){ UpdateVersionutil.getUpdataManger(this).startUpdate(); } }
======================================================
bean包import java.util.List; import com.bwei.test.R; import com.bwei.test.bean.News; import android.R.layout; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class MyBaseAdapter extends BaseAdapter { private List<News> list; private Context context; public MyBaseAdapter(List<News> list, Context context) { super(); this.list = list; this.context = context; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder viewHolder; if (convertView==null) { convertView=LayoutInflater.from(context).inflate(R.layout.list_item, null); viewHolder=new ViewHolder(); convertView.setTag(viewHolder); viewHolder.textView=(TextView) convertView.findViewById(R.id.textView1); viewHolder.textView2=(TextView) convertView.findViewById(R.id.textView2); viewHolder.textView3=(TextView) convertView.findViewById(R.id.textView3); viewHolder.textView4=(TextView) convertView.findViewById(R.id.textView4); } else { viewHolder=(ViewHolder) convertView.getTag(); } viewHolder.textView.setText(list.get(position).getTitle()); viewHolder.textView2.setText(list.get(position).getAuthor()); viewHolder.textView3.setText("釋出於:"+list.get(position).getPubDate()); viewHolder.textView4.setText(list.get(position).getCommentCount()+""); return convertView; } class ViewHolder{ TextView textView,textView2,textView3,textView4; } }
================================================================
public class News {
private int id;
private String title;
private String body;
private int commentCount;
private String author;
private String pubDate;
工具類
============================================================================
</pre>版本更新的網址<pre name="code" class="java">public class URLS {
//版本更新
public final static String UPDATE_VERSION="http://www.oschina.net/MobileAppVersion.xml";
}
請求比較
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.bwei.test.bean.News;
import android.util.Log;
import android.util.Xml;
public class Network {
private static int five = 5000;
private static List<News> list;
private static News news;
public static InputStream getinput(String path) {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(five);
connection.setReadTimeout(five);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream();
Log.d("tag", inputStream+"請求失敗++++++++++++++++++++");
return inputStream;
} else {
Log.e("tag", "請求失敗++++++++++++++++++++");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static List<News> pullxml(InputStream inputStream){
//獲得XmlPullParser解析器
XmlPullParser xmlParser = Xml.newPullParser();
try {
xmlParser.setInput(inputStream, "utf-8");
//獲得解析到的事件類別,這裡有開始文件,結束文件,開始標籤,結束標籤,文字等等事件。
int evtType=xmlParser.getEventType();
//一直迴圈,直到文件結束
while(evtType!=XmlPullParser.END_DOCUMENT){
String tag = xmlParser.getName();
switch(evtType){
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<News>();
break;
case XmlPullParser.START_TAG:
//通知資訊
if(tag.equalsIgnoreCase("news"))
{
news = new News();
}else if(tag.equalsIgnoreCase("id"))
{ //字元轉換整數
news.setId(Integer.parseInt(xmlParser.nextText()));
}
else if(tag.equalsIgnoreCase("title"))
{
news.setTitle(xmlParser.nextText());
}
else if(tag.equalsIgnoreCase("body"))
{
news.setBody(xmlParser.nextText());
}
else if(tag.equalsIgnoreCase("commentCount"))
{
news.setCommentCount(Integer.parseInt(xmlParser.nextText()));
}else if (tag.equals("author")) {
news.setAuthor(xmlParser.nextText());
}else if (tag.equals("pubDate")) {
news.setPubDate(xmlParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (tag.equals("news")) {
list.add(news);
}
break;
}
//如果xml沒有結束,則導航到下一個節點
evtType=xmlParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
}
應用程式更新實體類
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
/**
* 應用程式更新實體類
* @author
* @date
*/
@SuppressWarnings("serial")
public class Update implements Serializable{
public final static String UTF8 = "UTF-8";
public final static String NODE_ROOT = "oschina";
private int versionCode;
private String versionName;
private String downloadUrl;
private String updateLog;
public int getVersionCode() {
return versionCode;
}
public void setVersionCode(int 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;
}
/**
* 解析獲取到輸入流
* @param inputStream
* @return
*/
public static Update parse(InputStream inputStream){
Update update = null;
//獲得XmlPullParser解析器
XmlPullParser xmlParser = Xml.newPullParser();
try {
xmlParser.setInput(inputStream, UTF8);
//獲得解析到的事件類別,這裡有開始文件,結束文件,開始標籤,結束標籤,文字等等事件。
int evtType=xmlParser.getEventType();
//一直迴圈,直到文件結束
while(evtType!=XmlPullParser.END_DOCUMENT){
String tag = xmlParser.getName();
switch(evtType){
case XmlPullParser.START_TAG:
//通知資訊
if(tag.equalsIgnoreCase("android"))
{
update = new Update();
}
else if(update != null)
{
if(tag.equalsIgnoreCase("versionCode"))
{ //字元轉換整數
update.setVersionCode(toInt(xmlParser.nextText(),0));
}
else if(tag.equalsIgnoreCase("versionName"))
{
update.setVersionName(xmlParser.nextText());
}
else if(tag.equalsIgnoreCase("downloadUrl"))
{
update.setDownloadUrl(xmlParser.nextText());
}
else if(tag.equalsIgnoreCase("updateLog"))
{
update.setUpdateLog(xmlParser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
break;
}
//如果xml沒有結束,則導航到下一個節點
evtType=xmlParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return update;
}
/**
* 字串轉整數
* @param str
* @param defValue
* @return
*/
public static int toInt(String str, int defValue) {
try{
return Integer.parseInt(str);
}catch(Exception e){}
return defValue;
}
}
更新版本的工具類
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
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 com.bwei.test.url.URLS;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
/**
* 更新版本的工具類
* @author
* @date
*
*/
public class UpdateVersionutil {
private final String TAG = this.getClass().getName();
private final int UPDATA_NONEED = 0;
private final int UPDATA_CLIENT = 1;
private final int GET_UNDATAINFO_ERROR = 2;
private final int SDCARD_NOMOUNTED = 3;
private final int DOWN_ERROR = 4;
private Button getVersion;
private String localVersion;
public static Context mContext;
private static UpdateVersionutil updateVersionutil;
public static boolean mNeedUpdate;
InputStream is;
private Update parse;
public UpdateVersionutil(Context mContext) {
super();
this.mContext = mContext;
}
/**
* 檢測更新
*/
public void startUpdate(){
localVersion = getVersionName();
CheckVersionTask cv = new CheckVersionTask();
new Thread(cv).start();
}
public static UpdateVersionutil getUpdataManger(Context context){
if(updateVersionutil==null){
updateVersionutil=new UpdateVersionutil(context);
}
return updateVersionutil;
}
public static void checkUpdata(){
updateVersionutil.startUpdate();
}
private String getVersionName() {
//getPackageName()是你當前類的包名,0代表是獲取版本資訊
PackageManager packageManager =mContext.getPackageManager();
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(mContext.getPackageName(),
0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return packInfo.versionName;
}
/**
* 網路請求
* 獲取到網路介面的版本號進行對比
* @author
* @date
*/
public class CheckVersionTask implements Runnable {
public void run() {
try {
//這裡URLS.UPDATE_VERSION 是網路介面獲取網路資訊
URL url = new URL(URLS.UPDATE_VERSION);
//*****************************************************
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 從伺服器獲得一個輸入流
is = conn.getInputStream();
}
//*******************************************
//呼叫解析的方法
parse = Update.parse(is);
Url = parse.getDownloadUrl();
//**********************************************
System.out.println("新版版本名:"+parse.getVersionName());
System.out.println("本地版本名:"+localVersion);
//對比版本號
if (parse.getVersionName().equals(localVersion)) {
mNeedUpdate=false;
Log.i(TAG, "版本號相同");
Message msg = new Message();
msg.what = UPDATA_NONEED;
handler.sendMessage(msg);
// LoginMain();
} else {
mNeedUpdate=true;
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_NONEED:
Toast.makeText(mContext, "不需要更新",
Toast.LENGTH_SHORT).show();
case UPDATA_CLIENT:
//對話方塊通知使用者升級程式
showUpdataDialog();
break;
case GET_UNDATAINFO_ERROR:
//伺服器超時
Toast.makeText(mContext, "獲取伺服器更新資訊失敗", 1).show();
break;
case DOWN_ERROR:
//下載apk失敗
Toast.makeText(mContext, "下載新版本失敗", 1).show();
break;
}
}
};
/*
*
* 彈出對話方塊通知使用者更新程式
*
* 彈出對話方塊的步驟:
* 1.建立alertDialog的builder.
* 2.要給builder設定屬性, 對話方塊的內容,樣式,按鈕
* 3.通過builder 建立一個對話方塊
* 4.對話方塊show()出來
*/
protected void showUpdataDialog() {
AlertDialog.Builder builer = new Builder(mContext);
builer.setTitle("版本升級");
//*********************************************
//更新提示語
builer.setMessage("我們的APP做了更多的完善,您需要更新嗎?");
//當點確定按鈕時從伺服器上下載 新的apk 然後安裝 װ
builer.setPositiveButton("立馬更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "下載apk,更新");
downLoadApk();
}
});
builer.setNegativeButton("稍後再說", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//do sth
}
});
AlertDialog dialog = builer.create();
dialog.show();
}
/*
* 從伺服器中下載APK
*/
protected void downLoadApk() {
final ProgressDialog pd; //進度條對話方塊
pd = new ProgressDialog(mContext);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下載更新");
pd.show();
new Thread(){
@Override
public void run() {
try {
File file = DownLoadManager.getFileFromServer(parse.getDownloadUrl(), 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");
mContext.startActivity(intent);
}
public static String Url;
public static String getUrl(){
return Url;
}
/**
* 判斷SD卡是什麼狀態進行下載
* @author
* @date
*/
public static class DownLoadManager {
public static File getFileFromServer(String path, ProgressDialog pd) {
//如果相等的話表示當前的sdcard掛載在手機上並且是可用的
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setConnectTimeout(5000);
//獲取到檔案的大小
pd.setMax(conn.getContentLength());
InputStream is = null;
try {
is = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len ;
int total=0;
try {
while((len =bis.read(buffer))!=-1){
fos.write(buffer, 0, len);
total+= len;
//獲取當前下載量
pd.setProgress(total);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
else{
return null;
}
}
}
}
佈局檔案xml
===================================================================
main的<LinearLayout 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:orientation="vertical"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="button"
android:text="檢測新版本" />
<com.handmark.pulltorefresh.library.PullToRefreshGridView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:id="@+id/lv_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
ptr:ptrMode="both"
></com.handmark.pulltorefresh.library.PullToRefreshGridView>
</LinearLayout>
listview的佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:lines="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
版本升級彈框
<?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="wrap_content"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:orientation="vertical">
<ProgressBar
android:id="@+id/update_progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"/>
<TextView
android:id="@+id/update_progress_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textColor="@color/home_gray"/>
</LinearLayout>
values中的配置
=========================================================
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="home_gray">#808080</color>
</resources>
所有的主配置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bwei.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<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>
頭一次寫,請大家
提出意見