1.網絡請求,在android系統中,網絡請求主要有兩種實現方式,URLConnection和httpClient,這兩種方式都可以實現網絡請求。
(1)URLConnection
URL url = new URL(path);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
String list = buffer.readLine();
while (list != null) {
xml += list;
list = buffer.readLine();
}
這裏的path就是我們要訪問的網址,這樣我們就可以將網頁上的內容按照字符形式讀取下來。存到list這個字符串中。(別忘了還要在註冊文件中添加訪問網絡權限)(2)HttpClient
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream reader = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
String list = buffer.readLine();
while (list != null) {
xml += list;
list = buffer.readLine();
}
}
這裏的path同樣是網絡地址,code是服務器給我們返回的一個值,如果是200,就說明訪問成功,404就表示客戶端異常,505就表示服務器端異常。不過用這種方式請求的話需要導入兩個包httpclient和httpcore,這兩個包都在studio文件夾的bin目錄下,複製到你項目的libs目錄下,還要進行導入,File-project structure-app-dependencies-'+'-File dependency,按照順序然後選中你要導入的包,確認,就可以了。在導入這兩個包後可能還要在build-grade目錄下加入以下內容packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
這樣我們就可以訪問網絡上的資源了。對於免費的天氣api,網上有很多,我用的是這個:http://www.k780.com/api/weather.future,很好用,提供的數據也很全面,實時天氣,未來5-7天的,PM2.5和空氣指數都有提供,我們只需要對需要的數據進行訪問然後獲取,接下來就是取出我們所需要的數據了,也就是JSON解析。2.JSON解析
JSON類型數據是很常見的數據類型,它比起XML來方便很多,它是以鍵值對的形式來存儲數據的,所以很常用。解析起來非常容易,實例化一個JSONObject類,讀取到網頁上的內容,也就是上邊的list傳進去,即JSONObject json = new JSONObject(list),然後直接調用getString()把你需要的信息的鍵傳進去,就能得到對應的值了,很容易。這就是我們實現天氣預報的基本過程。下面是博主的一個小小的例子。
public class MainActivity extends Activity {
private TextView temperature;
private TextView weather;
private TextView aqi;
private TextView humidity;
private TextView degree;
private TextView location;
private Button add;
private Message msg;
public static Handler handler;
public static String position = "";
public static boolean start = false;
LocationClient locationClient = null;
BDLocationListener myListener = new MyLocationListener();
SwipeRefreshLayout swipeRefreshLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.buttonId);
temperature = (TextView) findViewById(R.id.tempId);
weather = (TextView) findViewById(R.id.weatherId);
aqi = (TextView) findViewById(R.id.aqiId);
humidity = (TextView) findViewById(R.id.humidityId);
degree = (TextView) findViewById(R.id.degreeId);
location = (TextView) findViewById(R.id.city);
add.setOnClickListener(new ButtonListener());
handler = new Myhandler();
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setColorSchemeColors(android.R.color.background_light);
swipeRefreshLayout.setSize(10);
swipeRefreshLayout.setProgressBackgroundColor(android.R.color.white);
swipeRefreshLayout.setOnRefreshListener(new reFreshListener());
getLocationThread g = new getLocationThread();
thread t = new thread();
Thread T = new Thread(t, "Refresh");
T.start();
}
public static String getURLConnection(String path) {
String xml = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream reader = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
String list = buffer.readLine();
while (list != null) {
xml += list;
list = buffer.readLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
public class reFreshListener implements SwipeRefreshLayout.OnRefreshListener {<span>
@Override
public void onRefresh() {
thread t = new thread();
Thread T = new Thread(t, "Refresh");
T.start();<span style="white-space:pre">
}
}
private class thread implements Runnable {
@Override
public void run() {
String todayXML = "http://api.k780.com:88/?app=weather.today&weaid=";
String aqiXMl = "http://api.k780.com:88/?app=weather.pm25&weaid=";
String futureXML = "http://api.k780.com:88/?app=weather.future&weaid=";
String suffixXML = "&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
String todayWeather = getURLConnection(todayXML + position + suffixXML);
String todayAqi = getURLConnection(aqiXMl + position + suffixXML);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("todayWeather", todayWeather);
bundle.putString("todayAqi", todayAqi);
msg.setData(bundle);
try {
Thread.sleep(1000);
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Myhandler extends Handler {
public void handleMessage(Message msg) {
swipeRefreshLayout.setRefreshing(false);
String todayWeather = msg.getData().getString("todayWeather");
if (todayWeather != null) {
try {
todayWeather = String.valueOf(new JSONObject(todayWeather).getJSONObject("result"));
JSONObject json = new JSONObject(todayWeather);
location.setText(json.getString("citynm"));
String temp = json.getString("temp_curr");
final float scale = getApplicationContext().getResources().getDisplayMetrics().density;
if (temp.length() == 2) {
temperature.setWidth((int) (84 * scale + 0.5f));
System.out.println((int) (84 * scale + 0.5f));
} else if (temp.length() == 3) {
temperature.setWidth((int) (140 * scale + 0.5f));
}
temperature.setText(temp);
degree.setText("o");
weather.setText(json.getString("weather"));
humidity.setText("溼度" + json.getString("humidity") + " " + json.getString("wind") + json.getString("winp"));
} catch (Exception e) {
e.printStackTrace();
}
}
String todayAqi = msg.getData().getString("todayAqi");
if (todayAqi != null) {
try {
todayAqi = String.valueOf(new JSONObject(todayAqi).getJSONObject("result"));
JSONObject json = new JSONObject(todayAqi);
aqi.setText("空氣指數" + json.getString("aqi") + " " + json.getString("aqi_levnm") + " " + json.getString("aqi_remark"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
上面就是實現獲取實時天氣的主要內容,其實很容易,但是要想實現更全面的功能就比較複雜了,本來我還想做一下定位功能,結果由於閱碼能力太渣,讀不懂大神們的代碼,所以暫時沒有實現這個功能,後續會跟進。不過關於定位大家可以用百度地圖API,http://developer.baidu.com/map/index.php?title=android-locsdk上面有詳細介紹,也可以下載它的Demo來仔細研讀。