网上有好多获取天气预报接口的方法和获取大致位置的方法,个人感觉实现自动获取位置并播报天气的功能没有必要加入地图SDK和天气预报的SDK,今天实现一下AndroiSDK自带的定位方法和中华万年历上提供的天气预报接口。
先说一下整体思路:
1.用AndroidSDK获取自己所在的城市
2.根据城市名获取该位置的天气信息
3.将天气信息循放在RecyclerView中环播放
首先,准备获取天气接口的材料
中华万年历提供了两个返回JSON的查询天气的接口:
1.http://wthrcdn.etouch.cn/weather_mini?city=北京
2.http://wthrcdn.etouch.cn/weather_mini?citykey=101010100
两者不同之处就是根据城市名或者城市编码获取天气信息,我们只需要获取城市名获取城市的编码就可以进行网络请求了。
第一步,获取位置
此处写了一个工具类GetLocationUtils.java
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import com.szkl.android.complaints.asynctasks.GetCityNameByGeocoder;
import java.util.Locale;
public class GetLocationUtils {
public static Geocoder geocoder; //获取并解析位置用
public static RecyclerView weatherRecycler; //用于循环播放天气信息的RecyclerView,会被传到获取天气的异步请求类中
public static Context mContext;
public static void getCityByLocation(Context context, RecyclerView recyclerView){
mContext = context;
weatherRecycler = recyclerView;
geocoder = new Geocoder(context, Locale.getDefault());
LocationManager locationManager; //管理Location及其他信息
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) context.getSystemService(serviceName);
//privider类型
String provider = LocationManager.NETWORK_PROVIDER;
//定位设置
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW);//低精度
criteria.setAltitudeRequired(false);//不要求海拔
criteria.setBearingRequired(false);//不要求方位
criteria.setCostAllowed(false);//不允许资费
criteria.setPowerRequirement(Criteria.POWER_LOW);//低耗电
Location location = null;
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
location = locationManager.getLastKnownLocation(provider);
//获取位置需要访问Google提供的服务进行位置解析,比较耗时所以就放在task中,(其实在Android6.0及以下,可以直接放在主线程中执行,Android8.0必须放在Task中)
new GetCityNameByGeocoder(context,geocoder,weatherRecycler).execute(location);
}
//第一个参数提供的类型,第二个参数更新周期(毫秒),第三个最小距离间隔500m
locationManager.requestLocationUpdates(provider,300000,500,locationListener);
}
private final static LocationListener locationListener = new LocationListener() {
@Override
public void