在我的应用程序中,我需要在用户点击按钮后获取手机位置。这是我的代码。
import android.location.*;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private double latitude;
private double longitude;
private Button sendrequest;
private TextView text;
private LocationManager locationManager;
private String provider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViews();
}
private void setViews() {
text = (TextView) findViewById(R.id.textView);
sendrequest = (Button) findViewById(R.id.button);
sendrequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
text.append("Provider " + provider + " has been selected.");
//onLocationChanged(location);
} else {
text.append("Location not avilable");
}
}
});
}
}
但它没有归还我的位置。它只是将“Location not available”字符串附加到文本TextView。我知道这是因为它返回的最后一个存储位置为null。但我不想使用LocationListener,因为我只想要一次该位置。即当用户启动应用程序时。请帮忙。
答案 0 :(得分:-1)
您必须在Android清单xml文件中设置以下权限才能访问位置。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />