【问题标题】:Location of the phone when user clicks on a button用户单击按钮时手机的位置
【发布时间】:2013-03-11 09:30:00
【问题描述】:

在我的应用程序中,一旦用户单击按钮,我就需要获取电话位置。这是我的代码。

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 因为我只想要一次位置。即当用户启动应用程序时。请帮忙。

【问题讨论】:

  • 我猜你是在模拟器上运行的。如果是这样 AFAIK 它总是在模拟器上返回 null 。您是否在实际设备上尝试过?
  • 是的。我做到了。结果相同。

标签: android android-location


【解决方案1】:

您必须在您的 android manifest xml 文件中设置以下权限才能访问位置。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

【讨论】:

  • @shrigurunayak 关注此tutorial
  • 谢谢:)。我通过给出一个 + 来否定它:P
猜你喜欢
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多