내 애플리케이션에서 사용자가 버튼을 클릭하면 전화 위치를 알아야합니다. 여기 내 코드가있다.사용자가 버튼을 클릭 할 때의 위치
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 텍스트에 "Location not available"문자열을 추가하기 만하면됩니다. null 인 마지막 저장된 위치를 반환하기 때문에 그것이 있다는 것을 알고 있습니다. 하지만 LocationListener를 한 번만 사용하면됩니다. 즉 사용자가 앱을 시작할 때 도와주세요.
에뮬레이터에서 실행 중이라고 생각합니다. 그렇다면 AFAIK 항상 에뮬레이터에서 null을 반환합니다. 실제 장치에서 해봤습니까? –
예. 나는 그랬다. 같은 결과. –