JSON_Message_Thread_AlterDialog_HTTP

知識點:

1 AlterDialog

2 使用GET方式請求HTTP服務信息

3 解析JSON

4 利用Handler來進行Message消息處理

5 多線程Thread進行網絡獲取數據

詳細解釋:

1 AlterDialog:

	/**
	 * 展示更新對話框
	 */
	protected void ShowDialog() {
		AlertDialog.Builder Dialog = new AlertDialog.Builder(this);
		
		Dialog.setTitle("檢查更新");
		Dialog.setMessage(mDescription);
	
		Dialog.setPositiveButton("立即更新", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});				
		Dialog.setNegativeButton("以後再說", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		
		Dialog.show();
	}	


2, 3使用GET方式請求HTTP服務信息與JSON解析數據

/**
	 * 檢查版本
	 * 知識點:message使用,HTTP獲得網絡數據,JSON對象的解析
	 */
	private void CheckVerison()
	{		
		
		 System.out.println("Thread!!!");
		new Thread(){			

			@Override
			public void run() {
				Message message = Message.obtain(); 
				System.out.println("Run!!!");
				try {					
					
					//建立HTTP連接 並使用GET方法進行獲取數據
					URL url = new URL("http://192.168.56.1:8080/updata.json");
					HttpURLConnection connection = (HttpURLConnection)url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(5000);
					connection.setReadTimeout(5000);
					connection.connect();
					
					//服務器連接正常
					int responseCode = connection.getResponseCode();
					System.out.println("responseCode : "+responseCode+"!!!!");
					if(responseCode==200)
					{
						//獲取數據,並將數據保存到result中
						InputStream inputStream = connection.getInputStream();
						String result = StreamUtils.readFromStream(inputStream);
						System.out.println("網絡數據: "+result);
						
						
						//解析json
						JSONObject json;
						try {
							json = new JSONObject(result);
							mVersionName = json.getString("VersionName");
							mVersionCode = json.getString("VersionCode");
							mDescription = json.getString("Description");							
							mDownLoadUrl = json.getString("DownLoadUrl");
							
							System.out.println("Version _ json : "+mVersionName);
							System.out.println("description _ json "+ mDescription);
							if(GetVerisonCode()<Integer.parseInt(mVersionCode))
							{
								message.what=CODE_NEDD_UPDATA;
								
								System.out.println("需要更新");
							}							
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							message.what=CODE_JSON_ERROR;
							e.printStackTrace();
						}
						
					}					
					
					System.out.println("URL: "+connection.getDate()+"");
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					message.what=CODE_URL_ERROR;
					e.printStackTrace();
					System.out.println("CODE_URL_ERROR");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					message.what=CODE_NET_ERROR;
					e.printStackTrace();
					System.out.println("CODE_NET_ERROR");
				}
				finally{
					mhandler.sendMessage(message);
					
				}
			}
			
		}.start();
	}

3 利用Handler來進行Message消息處理

(1)聲明全局handler變量,重新handlemessage消息處理函數

// 消息處理handler
		private Handler mhandler = new Handler(){
			public void handleMessage(android.os.Message msg) {
				
				switch (msg.what) {
				case CODE_NEDD_UPDATA:
					ShowDialog();				
					break;
				case CODE_JSON_ERROR:
					Toast.makeText(getBaseContext(), "Json_ERROR", Toast.LENGTH_SHORT).show();
					break;
				case CODE_URL_ERROR:
					Toast.makeText(getBaseContext(), "URL錯誤", Toast.LENGTH_SHORT).show();
					break;
				case CODE_NET_ERROR:
					Toast.makeText(getBaseContext(), "網絡錯誤", Toast.LENGTH_SHORT).show();
					System.out.println("handler net error!!!");
					break;

				default:
					break;
				}
			};
			
			
		};


(2)獲取message,並將數據放入到message中:

Message message = Message.obtain(); 
message.what=CODE_NEDD_UPDATA;
message.what=CODE_JSON_ERROR;
message.what=CODE_URL_ERROR;
message.what=CODE_NET_ERROR;

(3)在handler中發送message消息

mhandler.sendMessage(message);

5 Thread獲取網絡數據:

new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
			}
		}.start();




整體代碼:

在splashAcitivty中先檢查版本,如果有版本更新,使用handlermessage進行消息處理,並彈窗提示更新。

package com.example.mobliesoft.Activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.mobliesoft.R;
import com.example.mobliesoft.R.id;
import com.example.mobliesoft.R.layout;
import com.example.mobliesoft.utils.StreamUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class SplashActivity extends Activity {

	
	 protected static final int CODE_NEDD_UPDATA = 1; //更新
	protected static final int CODE_JSON_ERROR = 0;//json錯誤
	protected static final int CODE_URL_ERROR = 2;//URL錯誤
	protected static final int CODE_NET_ERROR = 3;//網絡錯誤

	private String mVersionName;
	private String mDescription;
	private String mVersionCode;
	private String mDownLoadUrl;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView Version = (TextView)findViewById(R.id.tv_version);		
		Version.setText("Version " + GetVerisonName());
		CheckVerison();
		
	}
	/**
	 * 獲取版本名稱
	 * @return
	 */
	private String GetVerisonName(){
		
			PackageManager packageManager = getPackageManager();
			try {
				PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
				int versionCode = packageInfo.versionCode;
				String versionName = packageInfo.versionName;
				System.out.println("versionName" + versionName + "versionCode "+ versionCode +";");
				return versionName;
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
			return "";
	}
	
	/**
	 * 獲取版本號
	 * @return
	 */
	private int GetVerisonCode(){
	
			PackageManager packageManager = getPackageManager();
			try {
				PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
				int versionCode = packageInfo.versionCode;			
				return versionCode;
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
			return -1;
	}
	
	  // 消息處理handler
		private Handler mhandler = new Handler(){
			public void handleMessage(android.os.Message msg) {
				
				switch (msg.what) {
				case CODE_NEDD_UPDATA:
					ShowDialog();				
					break;
				case CODE_JSON_ERROR:
					Toast.makeText(getBaseContext(), "Json_ERROR", Toast.LENGTH_SHORT).show();
					break;
				case CODE_URL_ERROR:
					Toast.makeText(getBaseContext(), "URL錯誤", Toast.LENGTH_SHORT).show();
					break;
				case CODE_NET_ERROR:
					Toast.makeText(getBaseContext(), "網絡錯誤", Toast.LENGTH_SHORT).show();
					System.out.println("handler net error!!!");
					break;

				default:
					break;
				}
			};
			
			
		};
	/**
	 * 檢查版本
	 * 知識點:message使用,HTTP獲得網絡數據,JSON對象的解析
	 */
	private void CheckVerison()
	{		
		
		 System.out.println("Thread!!!");
		new Thread(){			

			@Override
			public void run() {
				Message message = Message.obtain(); 
				System.out.println("Run!!!");
				try {					
					
					//建立HTTP連接 並使用GET方法進行獲取數據
					URL url = new URL("http://192.168.56.1:8080/updata.json");
					HttpURLConnection connection = (HttpURLConnection)url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(5000);
					connection.setReadTimeout(5000);
					connection.connect();
					
					//服務器連接正常
					int responseCode = connection.getResponseCode();
					System.out.println("responseCode : "+responseCode+"!!!!");
					if(responseCode==200)
					{
						//獲取數據,並將數據保存到result中
						InputStream inputStream = connection.getInputStream();
						String result = StreamUtils.readFromStream(inputStream);
						System.out.println("網絡數據: "+result);
						
						
						//解析json
						JSONObject json;
						try {
							json = new JSONObject(result);
							mVersionName = json.getString("VersionName");
							mVersionCode = json.getString("VersionCode");
							mDescription = json.getString("Description");							
							mDownLoadUrl = json.getString("DownLoadUrl");
							
							System.out.println("Version _ json : "+mVersionName);
							System.out.println("description _ json "+ mDescription);
							if(GetVerisonCode()<Integer.parseInt(mVersionCode))
							{
								message.what=CODE_NEDD_UPDATA;
								
								System.out.println("需要更新");
							}							
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							message.what=CODE_JSON_ERROR;
							e.printStackTrace();
						}
						
					}					
					
					System.out.println("URL: "+connection.getDate()+"");
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					message.what=CODE_URL_ERROR;
					e.printStackTrace();
					System.out.println("CODE_URL_ERROR");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					message.what=CODE_NET_ERROR;
					e.printStackTrace();
					System.out.println("CODE_NET_ERROR");
				}
				finally{
					mhandler.sendMessage(message);
					
				}
			}
			
		}.start();
	}
	
	/**
	 * 展示更新對話框
	 */
	protected void ShowDialog() {
		AlertDialog.Builder Dialog = new AlertDialog.Builder(this);
		
		Dialog.setTitle("檢查更新");
		Dialog.setMessage(mDescription);
	
		Dialog.setPositiveButton("立即更新", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});				
		Dialog.setNegativeButton("以後再說", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		
		Dialog.show();
	}	
};





發佈了310 篇原創文章 · 獲贊 37 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章