Android Weather APP (b) to obtain location information

Previous: Android Weather APP (a) the development of preparation

Second, write code

1. Get the current location information

First modify activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
	<!--显示详细定位信息-->
    <TextView
        android:id="@+id/tv_address_detail"
        android:padding="20dp"
        android:gravity="center"
        android:textColor="#000"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</LinearLayout>

① bound control

And then proceeds to MainActivity.java
right click and select Generate layout files activity_main
Here Insert Picture Description

Here Insert Picture Description
Now you can use this plug-in, click on the red border in the Generate ButterKnife Iniertions
Here Insert Picture Description
then Confirm submit to
Here Insert Picture Description

② Android version of the judgment

Before runtime permissions have to say, we must first determine what version mentioned later Android6.0. Before Toast to write a utility class.
A new package for storing tools utils class.
Here Insert Picture Description

Tools code is as follows:

package com.llw.goodweather.utils;

import android.content.Context;
import android.widget.Toast;

/**
 * 消息提示工具类
 */
public class ToastUtils {
    public static void showLongToast(Context context, CharSequence llw) {
        Toast.makeText(context.getApplicationContext(), llw, Toast.LENGTH_LONG).show();
    }

    public static void showShortToast(Context context, CharSequence llw) {
        Toast.makeText(context.getApplicationContext(), llw, Toast.LENGTH_SHORT).show();
    }
}

Then make a judgment in the version of the business logic code.

	//权限判断
    private void permissionVersion(){
        if(Build.VERSION.SDK_INT >= 23){//6.0或6.0以上
            //动态权限申请
            
        }else {//6.0以下
            //发现只要权限在AndroidManifest.xml中注册过,均会认为该权限granted  提示一下即可
            ToastUtils.showShortToast(this,"你的版本在Android6.0以下,不需要动态申请权限。");
        }
    }

After calling in the onCreate method

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        permissionVersion();//权限判断
    }

③ Access Request

	private RxPermissions rxPermissions;//权限请求框架
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        rxPermissions = new RxPermissions(this);//实例化这个权限请求框架,否则会报错
        permissionVersion();//权限判断

    }
	//动态权限申请
    private void permissionsRequest() {
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(granted -> {
                    if (granted) {//申请成功
                        //得到权限之后开始定位

                    } else {//申请失败
                        ToastUtils.showShortToast(this, "权限未开启");
                    }
                });
    }

Then apply permissions inside permissionVersion () method
Here Insert Picture DescriptionHere Insert Picture Description

The idea is quite clear, and inter-related, the benefits of this writing is easy to understand, do not put everything into onCreate stuffed, would not only increase the difficulty of reading the code will increase the frequency of occurrence of BUG.

④ class initialization LocationClient

Please declare LocationClient class object in the main thread, the object initialization parameters to be passed in Context type.

	//定位器
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
	//开始定位
    private void startLocation() {
        //声明LocationClient类
        mLocationClient = new LocationClient(this);
        //注册监听函数
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();

        //如果开发者需要获得当前点的地址信息,此处必须为true
        option.setIsNeedAddress(true);
        //可选,设置是否需要最新版本的地址信息。默认不需要,即参数为false
        option.setNeedNewVersionRgc(true);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
        mLocationClient.setLocOption(option);
        //启动定位
        mLocationClient.start();

    }

At this point, you will find myListener have red error, because we do not implement this interface, to achieve the following

⑤ achieve BDAbstractLocationListener Interface

	/**
     * 定位结果返回
     */
    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度,默认值为0.0f
            String coorType = location.getCoorType();
            //获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准
            int errorCode = location.getLocType();//161  表示网络定位结果
            //获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            String locationDescribe = location.getLocationDescribe();    //获取位置描述信息
            tvAddressDetail.setText(addr);//设置文本显示
        }
    }

⑥ display positioning results

In ** permissionsRequest () ** method call positioning method after obtaining permission, the positioning data to obtain detailed return address inside the listener.
Here Insert Picture Description
Run it (PS: If you run error, please put stickers on your error message number to determine what the problem is I)

Here Insert Picture Description
Click permit during use only or to always allow and then you can get locate the address.
Here Insert Picture Description
Now the position has got, the next step is to check the weather by the position of the day.

Next: Android Weather APP (c) API to access weather data requests

Published 51 original articles · won praise 17 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_38436214/article/details/105328603