在我的应用程序中,一旦用户单击按钮,我就需要获取电话位置。这是我的代码。
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");
}
}
});
}
}
但它没有返回我的位置。它只是将“位置不可用”字符串附加到文本 TextView。我知道这是因为它返回最后一个存储的位置,它是空的。但我不想使用 LocationListener 因为我只想要一次位置。即当用户启动应用程序时。请帮忙。