Android-CallBack实战(用作Listener和Activity数据传递)

一、实现效果

百度地图获取定位

二、实现细节

1.activity

private final MyLocationListener myListener = new MyLocationListener(new MyLocationListener.LocationCallback() {
        @Override
        public void onLocationChanged(BDLocation location) {
            textView.append("验证信息:" + location.getCountry()+"\n");
        }
    });

2.Listener

    public interface LocationCallback{
        void onLocationChanged(BDLocation location);
    }
    LocationCallback locationCallback;

    public MyLocationListener(LocationCallback locationCallback) {
        this.locationCallback = locationCallback;
    }

3.详解

LocationCallback是一个接口,在这段代码中用于接收百度定位结果并进行特定处理。在MyLocationListener类中定义了LocationCallback接口,该接口只有一个方法onLocationChanged,用于在定位结果发生变化时被调用。

BaiduSDKActivity中,创建了一个MyLocationListener的实例,并通过匿名内部类实现了LocationCallback接口,在onLocationChanged方法中,将定位结果中的国家信息追加到TextView中。

总结:LocationCallback接口在这个示例中起到了传递定位结果并进行特定处理的作用,通过在BaiduSDKActivity中实现该接口的方法,实现了对定位结果的定制化处理,将国家信息显示在TextView中。

三、完整demo

1.activity

package com.example.testbaidusdk;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import androidx.appcompat.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.Manifest;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class BaiduSDKActivity extends AppCompatActivity {
    private static final String[] REQUEST_PERMISSIONS = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    public LocationClient mLocationClient = null;

    private final MyLocationListener myListener = new MyLocationListener(new MyLocationListener.LocationCallback() {
        @Override
        public void onLocationChanged(BDLocation location) {
            textView.append("验证信息:" + location.getCountry()+"\n");
        }
    });
    private static String LOCATION_PROXY_ADDRESS = "";
    private static int LOCATION_PROXY_PORT = 0;
    private static final int REQUEST_LOCATION_PERMISSION = 100;
    private static String LOCATION_PROXY_NAME = "";
    private static String LOCATION_PROXY_PASSWORD = "";
    private static final String TAG = "LocationActivity";
    private TextView textView;
    private Button buttonStart;
    private Button buttonSet;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baidu_sdk);
        initView();
        try {
            LocationClient.setAgreePrivacy(true);
        } catch (Exception e) {
            // 处理异常情况,例如记录日志、提示用户等
            Log.e("PrivacyError", "Error setting privacy agreement", e);
        }
        try {
            mLocationClient = new LocationClient(getApplicationContext());
            //声明LocationClient类
            mLocationClient.registerLocationListener(myListener);
            //注册监听函数
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        option.setFirstLocType(LocationClientOption.FirstLocType.ACCURACY_IN_FIRST_LOC);
        option.setScanSpan(5000);
        option.setOpenGnss(true);
        option.setNeedNewVersionRgc(true);
        option.setIsNeedAddress(true);
        option.setHttpProxyUsernameAndPassword("","");

        buttonSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 带两个输入栏的弹窗
                TwoInputDialogFragment.onCreateDialog(BaiduSDKActivity.this).show();
                textView.append("弹窗显示" +"\n");
            }
        });

        buttonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermissions(option);
            }
        });

    }

    private void initView() {
        textView = findViewById(R.id.location_text);
        buttonSet = findViewById(R.id.location_set_proxy);
        buttonStart = findViewById(R.id.location_information_start);
        if (textView!= null) {
            textView.setMovementMethod(ScrollingMovementMethod.getInstance());
        }
    }

    //检查定位信息
    private void checkPermissions(LocationClientOption option) {
        boolean permissionGranted = true;
        for (String permission : REQUEST_PERMISSIONS) {
            final int cameraPermission = ContextCompat.checkSelfPermission(this, permission);
            Log.i("Permission", permission + ": " + cameraPermission);
            if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, REQUEST_PERMISSIONS, REQUEST_LOCATION_PERMISSION);
                permissionGranted = false;
            }
        }
        if (permissionGranted) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                textView.append("定位权限:已开启前台权限");
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    textView.append("   已获取后台权限\n");
                } else {
                    textView.append("   未获取后台权限,如果需要请手动授权位置“始终允许”\n");
                }
            } else {
                textView.append("定位权限:已开启前台权限\n");
            }
            option.setProxy(LOCATION_PROXY_ADDRESS,LOCATION_PROXY_PORT);
            option.setHttpProxyUsernameAndPassword(LOCATION_PROXY_NAME,LOCATION_PROXY_PASSWORD);
            textView.append("代理信息(地址:端口):" + LOCATION_PROXY_ADDRESS + ":" + LOCATION_PROXY_PORT +"\n");
            textView.append("定位信息(账号:密码)" + LOCATION_PROXY_NAME + ":" + LOCATION_PROXY_PASSWORD +"\n");
            // 权限已授予,可以进行定位操作
            mLocationClient.setLocOption(option);
            mLocationClient.start();
        } else {
            textView.append("定位权限:未授予定位权限,请手动开启,以免影响定位准确\n");
            return;
        }
    }

    public void onDialogPositiveClick(String address, int port, String name, String password) {
        textView.append("代理信息:" + address + ":" + port + "\n");
        LOCATION_PROXY_ADDRESS = address;
        LOCATION_PROXY_PORT = port;
        LOCATION_PROXY_NAME = name;
        LOCATION_PROXY_PASSWORD = password;
    }
}

2.Listener

package com.example.testbaidusdk;

import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;

public class MyLocationListener extends BDAbstractLocationListener {
    private static final String TAG = "MyLocationListener";
    private static final String locationInfo = "定位信息";

    public interface LocationCallback{
        void onLocationChanged(BDLocation location);
    }
    LocationCallback locationCallback;

    public MyLocationListener(LocationCallback locationCallback) {
        this.locationCallback = locationCallback;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        //此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
        //以下只列举部分获取经纬度相关(常用)的结果信息
        //更多结果信息获取说明,请参照类参考中BDLocation类中的说明

        double latitude = location.getLatitude();    //获取纬度信息
        double longitude = location.getLongitude();    //获取经度信息
        float radius = location.getRadius();    //获取定位精度,默认值为0.0f

        String coorType = location.getCoorType();
        //获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准

        int errorCode = location.getLocType();
        //获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
        Log.i("MyLocationListener", "定位信息1:" + location.toString());
        Log.i("MyLocationListener", "定位信息2:" + location.getCoorType());
        Log.i("MyLocationListener", "定位信息3:" + location.getLatitude());
        Log.i("MyLocationListener", "定位信息4:" + location.getLongitude());
        Log.i("MyLocationListener", "定位信息5:" + location.getAddrStr());
        Log.i("MyLocationListener", "定位信息6:" + location.getCountry());
        locationCallback.onLocationChanged(location);
    }

    public String getLocationInfo() {
        Log.i("MyLocationListener", "定位信息:" + locationInfo);
        return locationInfo;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L.2626

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值