LocationManager` 是 Android 提供的一个用于获取当前位置信息和卫星信息的服务。要使用它,首先需要获取系统提供的 `location_service`。以下是如何在 Android 中使用 `LocationManager` 的示例:
1. 获取 `LocationManager` 实例:
```java
LocationManager lm;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
```
2. 常用的定位服务提供者有三种:
* GPS_PROVIDER:通过 GPS 获得位置信息。
* NETWORK_PROVIDER:通过网络提供位置信息。
* PASSIVE_PROVIDER:被动地从其他应用程序获取位置信息。
3. 通过 `getAllProviders()` 方法获取当前支持的定位服务模式:
```java
List
for (String provider : providers) {
Log.d("LocationManager", "Provider: " + provider);
}
```
以下是一个完整的代码示例:
**AndroidManifest.xml**
``` xml
package="com.example.locationexample"> ...
```
**activity_main.xml**
``` xml
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> TextView textView; Button button; Button button2; TextView textView2; TextView textView3; TextView textView4; TextView textView5; TextView textView6; TextView textView7; TextView textView8; TextView textView9; TextView textView10; TextView textView11;
```
**MainActivity.java**
``` java
package com.example.locationexample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; //添加这个库来显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此行。//导入所需的包以显示Toast提示框。如果已经导入,请忽略此
根据您提供的XML内容,这是一个Android的ConstraintLayout布局文件。它包含一个ListView控件,宽度为368dp,高度为495dp,并设置了相对于父布局的绝对位置。以下是重构后的代码文件:
```xml
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> android:id="@+id/pro" android:layout_width="368dp" android:layout_height="495dp" tools:layout_editor_absoluteX="20dp" tools:layout_editor_absoluteY="20dp" />
```
以下是重构后的代码,同时附带了完整的项目结构。
```java
package com.example.user.location;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LocationListener {
private static final int PERMISSION_REQUEST_CODE = 1001;
private ListView providers;
private LocationManager lm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
providers = (ListView) findViewById(R.id.pro);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List
ArrayAdapter
providers.setAdapter(adapter);
requestPermissions();
}
private void requestPermissions() {
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}, PERMISSION_REQUEST_CODE);
} else {
startLocationUpdates();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
} else {
// TODO: Handle permission denied case
}
break;
}
}
private void startLocationUpdates() {
lm.requestLocationUpdates(lm.getBestProvider(null), 30 * 1000, 10, this);
}
@Override
public void onLocationChanged(@NonNull Location location) {
// TODO: Handle location update event and update UI accordingly
}
}
```
以下是重构后的内容:
```xml
package="com.example.user.gps"> android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
```
```java
package com.example.user.gps;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.user.gps", appContext.getPackageName());
}
}
```
```java
package com.example.user.gps;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView positionTextView;
private TextView positionLatLng;
private LocationManager locationManager;
private String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
positionTextView=(TextView)findViewById(R.id.position_text_view);
positionLatLng=(TextView)findViewById(R.id.position_plain_text);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
provider=LocationManager.GPS_PROVIDER;
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null){
//显示当前设备的位置信息
Log.d("lidu---","location!=null");
showLocation(location);
}else{
Log.d("lidu---","location==null");
}
locationManager.requestLocationUpdates(provider, 1000, 1, locationListener);
}
//LocationListener用于当位置信息变化时由locationManager调用
LocationListener locationListener=new LocationListener(){
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d("test","onLocationChanged");
//更新当前设备的位置信息
showLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub }
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub }
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub } };
private void showLocation(final Location location){
StringBuilder sb = new StringBuilder();
sb.append(location.getLatitude());
positionTextView.setText(sb.toString()); } }
```