腾讯公益赛个人冲刺博客7(2024.5.1)
今天处理sos的定位功能,但自动定位功能不稳定,需要手动定位
import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.baidu.location.BDAbstractLocationListener; import com.baidu.location.BDLocation; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; public class MainActivity extends AppCompatActivity { private LocationClient mLocationClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化定位客户端 mLocationClient = new LocationClient(getApplicationContext()); // 配置定位选项 LocationClientOption option = new LocationClientOption(); option.setIsNeedAddress(true); // 获取详细地址信息 mLocationClient.setLocOption(option); // 设置定位监听器 mLocationClient.registerLocationListener(new MyLocationListener()); // 请求定位权限 requestLocationPermission(); } // 请求定位权限 private void requestLocationPermission() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } else { // 开始定位 mLocationClient.start(); } } // 定位权限回调处理 @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 用户同意授权,开始定位 mLocationClient.start(); } else { Toast.makeText(this, "需要定位权限才能使用定位功能", Toast.LENGTH_SHORT).show(); } } } // 定位结果监听器 private class MyLocationListener extends BDAbstractLocationListener { @Override public void onReceiveLocation(BDLocation location) { // 获取定位结果 StringBuilder sb = new StringBuilder(); sb.append("纬度:").append(location.getLatitude()).append("\n"); sb.append("经度:").append(location.getLongitude()).append("\n"); sb.append("地址:").append(location.getAddrStr()).append("\n"); // 在这里处理定位结果,比如更新UI显示 Toast.makeText(MainActivity.this, sb.toString(), Toast.LENGTH_SHORT).show(); } } @Override protected void onDestroy() { super.onDestroy(); // 停止定位 mLocationClient.stop(); } }