Android 基於百度定位sdk ,獲取城市,使用json解析天氣
阿新 • • 發佈:2019-02-01
關於百度定位sdk的使用 參考官方文件 https://lbsyun.baidu.com/index.php?title=android-locsdk
JSON 解析 參考了 https://blog.csdn.net/double2hao/article/details/68482900
使用的 天氣介面 http://wthrcdn.etouch.cn/weather_mini?city=北京
demo下載:https://download.csdn.net/download/weixin_42447313/10483975
實現後的效果
佈局程式碼
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.yazz.yaweather.MainActivity"> <TextView android:id="@+id/location_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="16dp" /> <EditText android:id="@+id/et1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_below="@+id/location_view" android:hint="請輸入城市名稱:" /> <RelativeLayout android:id="@+id/rl1" android:layout_width="match_parent" android:layout_height="100dp" android:layout_below="@id/et1" android:layout_marginTop="20dp"> <TextView android:id="@+id/weather_view" android:layout_width="192dp" android:layout_height="match_parent" android:gravity="center" android:textSize="16dp" /> <ImageView android:id="@+id/iv1" android:layout_width="192dp" android:layout_height="match_parent" android:layout_toRightOf="@+id/weather_view" /> </RelativeLayout> <RelativeLayout android:id="@+id/rl2" android:layout_width="match_parent" android:layout_height="100dp" android:layout_below="@id/rl1" android:layout_marginTop="20dp"> <TextView android:id="@+id/weather1_view" android:layout_width="192dp" android:layout_height="match_parent" android:gravity="center" android:textSize="16dp" /> <ImageView android:id="@+id/iv2" android:layout_width="192dp" android:layout_height="match_parent" android:layout_toRightOf="@+id/weather1_view" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="100dp" android:layout_below="@id/rl2" android:layout_marginTop="20dp"> <TextView android:id="@+id/weather2_view" android:layout_width="192dp" android:layout_height="match_parent" android:gravity="center" android:textSize="16dp" /> <ImageView android:id="@+id/iv3" android:layout_width="192dp" android:layout_height="match_parent" android:layout_toRightOf="@+id/weather2_view" /> </RelativeLayout> <Button android:id="@+id/start_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" android:text="定位並獲取天氣" /> <Button android:id="@+id/start_weather" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignTop="@+id/start_location" android:text="獲取指定位置天氣" /> </RelativeLayout>
定位程式碼
public Context context; public static String City= ""; public LocationClient mLocationClient = null; //LocationClient類是定位SDK的核心類 public BDLocationListener myListener = new MyLocationListener(); public BDLocationUtils(Context context){ this.context = context; } public void doLocation(){ //宣告LocationClient類 mLocationClient = new LocationClient(context.getApplicationContext()); //註冊監聽函式 mLocationClient.registerLocationListener( myListener ); //初始化定位 initLocation(); //呼叫initLocation方法 } private void initLocation(){ LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); //可選,預設高精度,設定定位模式,高精度,低功耗,僅裝置 option.setIsNeedAddress(true); //可選,設定是否需要地址資訊,預設不需要 option.setOpenGps(true); //可選,預設false,設定是否使用gps mLocationClient.setLocOption(option); } private class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { //獲取定位結果 StringBuffer sb = new StringBuffer(256); sb.append(location.getCity()); //獲取城市 City = location.getCity().replace("市","");//replace 切割字元 去掉“市” } } }
解決安卓6.0以上權問題:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // 申請一個(或多個)許可權,並提供用於回撥返回的獲取碼(使用者定義) requestPermissions(new String[]{ Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,}, BAIDU_READ_PHONE_STATE); } bdLocationUtils.doLocation();//開啟定位 bdLocationUtils.mLocationClient.start();//開始定位 textView.setText("當前位置:"+BDLocationUtils.City);} else { Log.e("Permissions", "已經有許可權了"); }
@Override public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions,grantResults); switch(requestCode) { //requestCode即所宣告的許可權獲取碼,在checkSelfPermission時傳入 case 1: BAIDU_READ_PHONE_STATE: if(grantResults[0] == PackageManager.PERMISSION_GRANTED) { //獲取到許可權,做相應處理 //呼叫定位SDK應確保相關許可權均被授權,否則會引起定位失敗 bdLocationUtils.doLocation();//開啟定位 bdLocationUtils.mLocationClient.start();//開始定位 } else{ //沒有獲取到許可權,做特殊處理 Log.e("Permissions","沒有許可權定位失敗"); } break; default: break; } }
JSON解析
mRequestQueue = Volley.newRequestQueue(this); final String city = BDLocationUtils.City; String city_encode = null; try { city_encode = URLEncoder.encode(city,"utf-8");//城市名轉為中文
} catch (UnsupportedEncodingException e) { e.printStackTrace(); } JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest( "http://wthrcdn.etouch.cn/weather_mini?city="+city_encode,// 根據城市名獲取天氣JSon
null, new Response.Listener< JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONObject data = new JSONObject(response.getString("data")); JSONArray forecast = data.getJSONArray("forecast"); JSONObject todayWeather = forecast.getJSONObject(0); String wendu = data.getString("wendu") + "\n"; //String ganmao = data.getString("ganmao") + "\n"; String high = todayWeather.getString("high") + "\n"; String low = todayWeather.getString("low") + "~"; String date = todayWeather.getString("date") + ""; String type = todayWeather.getString("type")+"\n"; String city = data.getString("city") + "\n"; textView1.setText(city+date+type+"實時溫度:"+wendu + low + high );
天氣圖示:
if (todayWeather.getString("type").toString().contains("多雲")){ imageView1.setImageResource(R.drawable.duoyun1); }else if(todayWeather.getString("type").toString().contains("晴")){ imageView1.setImageResource(R.drawable.qingtian); }else if(todayWeather.getString("type").toString().contains("陰")){ imageView1.setImageResource(R.drawable.yintian);