Post:2021-01-29 17:25:00
Visit:
11.05学习
定位信息获取
写了一个定位获取的功能应用,模拟一下app获取定位时具体代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package cn.twle.android.GPSUpdate;
import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity;
import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.widget.TextView; import android.widget.Toast;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MainActivity extends AppCompatActivity {
private LocationManager lm; private TextView ms_msg; private String loc_msg;
private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { if(msg.what == 0x001){ ms_msg.setText(loc_msg); } return false; } });
private LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(@NonNull Location location) { updataShow(location); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ms_msg = (TextView)findViewById(R.id.ms_msg);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationUpdata(); } public void onResume(){ super.onResume(); locationUpdata(); } public void onPause() { super.onPause(); lm.removeUpdates(mLocationListener); } public void locationUpdata(){ if(checkCallingOrSelfPermission(ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ Toast.makeText(MainActivity.this,"请打开GPS",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent,0); return; } Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); updataShow(location); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000,8,mLocationListener); }
private void updataShow(Location location) { if(location != null){ StringBuilder sb = new StringBuilder(); sb.append("当前位置信息:\n"); sb.append("精度:"+location.getLongitude()+"\n"); sb.append("纬度"+location.getLatitude()+"\n"); sb.append("高度"+location.getAltitude()+"\n"); sb.append("定位精度:"+location.getAccuracy()+"\n");
loc_msg = sb.toString(); } else loc_msg = ""; handler.sendEmptyMessage(0x001); }
}
|
成果展示: