android如何定位不提示信息,安卓6.0 ,第一行代码11章节,获取位置信息不显示...

安卓6.0 ,获取位置信息,不显示

MainActivity.java

public class MainActivity extends AppCompatActivity {

private TextView positionTextView;

private LocationManager locationManager;

private String provider;

private Location location;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

positionTextView = (TextView) findViewById(R.id.position_text_view);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

//获取所有可用的位置提供器

List providerList = locationManager.getProviders(true);

if (providerList.contains(LocationManager.GPS_PROVIDER)) {

provider = LocationManager.GPS_PROVIDER;

} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {

provider = LocationManager.NETWORK_PROVIDER;

} else {

//当没有可用的位置提供器时,提示用户,并结束程序

Toast.makeText(this, "No Location Provider to use", Toast.LENGTH_SHORT).show();

return;

}

try {

location = locationManager.getLastKnownLocation(provider);

} catch (SecurityException e) {

e.printStackTrace();

}

if (location != null) {

showLocation(location);

}

try {

//实时更新地理信息

locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);

} catch (SecurityException e) {

e.printStackTrace();

}

}

LocationListener locationListener = new LocationListener() {

@Override

public void onLocationChanged(Location location) {

showLocation(location);

}

@Override

public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override

public void onProviderEnabled(String s) {

}

@Override

public void onProviderDisabled(String s) {

}

};

//设置positionTextView的值并显示

private void showLocation(Location location) {

String currentPosition = "latitude" + location.getLatitude() +

"\n" + "longitude is" + location.getLongitude();

positionTextView.setText(currentPosition);

}

@Override

protected void onDestroy() {

super.onDestroy();

if (locationManager != null) {

//关闭程序时将监听器移除

try {

locationManager.removeUpdates(locationListener);

} catch (SecurityException e) {

e.printStackTrace();

}

}

}

}

XML布局

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="com.xhq.locationtest.MainActivity">

android:id="@+id/position_text_view"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值