HTTP網路請求GSON解析網路不可用跳轉到設定
阿新 • • 發佈:2018-11-06
//1主 mainactivity介面
package com.example.guoxinyu20181101; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.net.UrlQuerySanitizer; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView listView; private Button button; private ConnectionBase mBase; private final int UPDATE_UI = 1; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_UI: // List<ConnectionBean.Result> lists = (List<ConnectionBean.Result>) msg.obj; List<List<String>> lists = (List<List<String>>) msg.obj; mBase.setmlists(lists); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取資源id listView = findViewById(R.id.lv_list); button = findViewById(R.id.btn); mBase = new ConnectionBase(MainActivity.this); listView.setAdapter(mBase); //點選載入資料 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //判斷網路是否可用 if (!NetUtil.hasNetWork(MainActivity.this)) { showNotNetWork(); return; } new Thread(new Runnable() { @Override public void run() { requestConnection(); } }).start(); } }); //點選監聽 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { List<String> data = mBase.getItem(position); Toast.makeText(MainActivity.this, data.get(0) + ":" + data.get(1), Toast.LENGTH_SHORT).show(); } }); } //彈框提示網路的方法 private void showNotNetWork() { new AlertDialog.Builder(MainActivity.this) .setTitle("無網路") .setMessage("當前網路不可用,是否去設定?") .setPositiveButton("確認", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent("android.settings.WIRELESS_SETTINGS"); startActivity(intent); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } //載入資料的方法 private String urlStr = "https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA"; public void requestConnection() { try { //定義url地址 URL url = new URL(urlStr); //開啟連線 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //設定請求方式 urlConnection.setRequestMethod("GET"); //設定超時 urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); //獲取請求碼 int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { String json = stream2String(urlConnection.getInputStream()); //得到gson Gson gson = new Gson(); ConnectionBean connectionBean = gson.fromJson(json, ConnectionBean.class); handler.sendMessage(handler.obtainMessage(UPDATE_UI, connectionBean.getResult())); } } catch (Exception e) { e.printStackTrace(); } } //位元組流轉換為字元流 public String stream2String(InputStream is) throws IOException { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder builder = new StringBuilder(); for (String tem = br.readLine(); tem != null; tem = br.readLine()) { builder.append(tem); } return builder.toString(); } }
//介面卡介面
package com.example.guoxinyu20181101; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class ConnectionBase extends BaseAdapter { private List<List<String>> lists; private Context mContext; public ConnectionBase(Context mContext) { this.mContext = mContext; //初始化 lists = new ArrayList<>(); } public void setmlists(List<List<String>> lists) { this.lists = lists; notifyDataSetChanged(); } @Override public int getCount() { return lists.size(); } @Override public List<String> getItem(int position) { return lists.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false); holder = new ViewHolder(); holder.text = convertView.findViewById(R.id.text); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(getItem(position).get(0)); return convertView; } class ViewHolder { private TextView text; } }
//判斷是否有網路的類
package com.example.guoxinyu20181101; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class NetUtil { //判斷是否有網路 public static boolean hasNetWork(Context context){ ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo(); return activeNetworkInfo!=null && activeNetworkInfo.isAvailable(); } }
//存放資料的BEAN類
package com.example.guoxinyu20181101;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetUtil {
//判斷是否有網路
public static boolean hasNetWork(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo!=null && activeNetworkInfo.isAvailable();
}
}
//配置檔案
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guoxinyu20181101">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<!--跳轉到網路設定的許可權-->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</activity>
</application>
</manifest>