如何使用LocationManager在android中获取当前位置

如何使用LocationManager在android中获取当前位置,android,location,locationmanager,locationlistener,Android,Location,Locationmanager,Locationlistener,每当我使用LocationManager和LocationListener时, 在使用AndroidSimulator时,我得到了位置, 设置纬度和经度时使用额外的工具 我查看了其他问题的答案,但我对Android开发还不熟悉,所以我真的无法理解答案。所以我提出了一个新的问题,我希望能对我的代码进行审查。谢谢 但是,当我在物理设备上运行时,我的代码在启动时不会给出我的当前位置。如何获取当前位置?我还尝试了getLastKnownLocation,但即使这样也不起作用 package com.lo

每当我使用LocationManager和LocationListener时, 在使用AndroidSimulator时,我得到了位置, 设置纬度和经度时使用额外的工具

我查看了其他问题的答案,但我对Android开发还不熟悉,所以我真的无法理解答案。所以我提出了一个新的问题,我希望能对我的代码进行审查。谢谢

但是,当我在物理设备上运行时,我的代码在启动时不会给出我的当前位置。如何获取当前位置?我还尝试了getLastKnownLocation,但即使这样也不起作用

package com.londonappbrewery.climapm;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
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.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;


public class WeatherController extends AppCompatActivity {

    // Constants:
    final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
    // App ID to use OpenWeather data
    final String APP_ID = "5563c6a4ddd7d7181b257988cc2b1ad1";
    // Time between location updates (5000 milliseconds or 5 seconds)
    final long MIN_TIME = 5000;
    // Distance between location updates (1000m or 1km)
    final float MIN_DISTANCE = 1000;
    //Request Code
    final int REQUEST_CODE = 123;

    // TODO: Set LOCATION_PROVIDER here:
    String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;


    // Member Variables:
    TextView mCityLabel;
    ImageView mWeatherImage;
    TextView mTemperatureLabel;

    // TODO: Declare a LocationManager and a LocationListener here:
    LocationManager mLocationManager;
    LocationListener mLocationListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_controller_layout);

        // Linking the elements in the layout to Java code
        mCityLabel = (TextView) findViewById(R.id.locationTV);
        mWeatherImage = (ImageView) findViewById(R.id.weatherSymbolIV);
        mTemperatureLabel = (TextView) findViewById(R.id.tempTV);
        ImageButton changeCityButton = (ImageButton) findViewById(R.id.changeCityButton);


        // TODO: Add an OnClickListener to the changeCityButton here:
        changeCityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WeatherController.this, ChangeCityController.class);
                startActivity(intent);
            }
        });

    }


    // TODO: Add onResume() here:
    @Override
    protected void onResume() {
        super.onResume();

        Log.d("Clima", "onResume() called");

        Intent intent = getIntent();
        String cityName = intent.getStringExtra("cityName");

        if (cityName != null) {

            //Log.d("Clima", cityName);
            getWeatherForNewCity(cityName);

        } else {
            Log.d("Clima", "Getting weather for current location");
            getWeatherForCurrentLocation();
        }


    }


    // TODO: Add getWeatherForNewCity(String city) here:
    private void getWeatherForNewCity(String city) {

        RequestParams params = new RequestParams();
        params.put("q", city);
        params.put("appid", APP_ID);
        letsDoSomeNetworking(params);

    }

    // TODO: Add getWeatherForCurrentLocation() here:
    private void getWeatherForCurrentLocation() {

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                //Log.d("Clima", "");

                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());

                Log.d("Clima", "onLocationChanged() callback received");
                Log.d("Clima", "Latitude is " + latitude);
                Log.d("Clima", "Longitude is " + longitude);

                RequestParams params = new RequestParams();
                params.put("lat", latitude);
                params.put("lon", longitude);
                params.put("appid", APP_ID);
                letsDoSomeNetworking(params);


            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

                Log.d("Clima", "onProviderDisabled() callback received");

            }
        };

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);

            return;
        }

        mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
        Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER);
        if(location != null) {
            RequestParams params = new RequestParams();
            params.put("lat", location.getLatitude());
            params.put("lon", location.getLongitude());
            params.put("appid", APP_ID);
            letsDoSomeNetworking(params);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Log.d("Clima", "onRequestPermissionResult(): Permission Granted!");
                //mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
                getWeatherForCurrentLocation();


            }

        }

    }

    // TODO: Add letsDoSomeNetworking(RequestParams params) here:
    private void letsDoSomeNetworking(RequestParams params) {

        AsyncHttpClient client = new AsyncHttpClient();

        client.get(WEATHER_URL, params, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] header, JSONObject response) {

                Log.d("Clima", "Success! JSON : " + response.toString());

                WeatherDataModel weatherData = WeatherDataModel.fromJSON(response);

                // Log.d("Clima", weatherData.getTemperature()); << WORKING

                updateUI(weatherData);
            }

            @Override
            public void onFailure(int statusCode, Header[] header, Throwable e, JSONObject response) {
                Log.e("Clima", e.toString());
                Log.d("Clima", String.valueOf(statusCode));
                Toast.makeText(WeatherController.this, "Request Failed!", Toast.LENGTH_SHORT).show();

            }

        });

    }


    // TODO: Add updateUI() here:
    private void updateUI(WeatherDataModel weatherData){

        mTemperatureLabel.setText(weatherData.getTemperature());
        mCityLabel.setText(weatherData.getCity());

        int resourceID = getResources().getIdentifier(weatherData.getIconName(), "drawable", getPackageName());
        mWeatherImage.setImageResource(resourceID);



    }


    // TODO: Add onPause() here:



}
package com.londonappbrewery.climapm;
导入android.Manifest;
导入android.content.Context;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.support.annotation.NonNull;
导入android.support.v4.app.ActivityCompat;
导入android.support.v7.app.AppActivity;
导入android.util.Log;
导入android.view.view;
导入android.widget.ImageButton;
导入android.widget.ImageView;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.loopj.android.http.AsyncHttpClient;
导入com.loopj.android.http.JsonHttpResponseHandler;
导入com.loopj.android.http.RequestParams;
导入org.json.JSONObject;
导入cz.msebera.android.httpclient.Header;
公共类WeatherController扩展AppCompative活动{
//常数:
最终字符串WEATHER_URL=”http://api.openweathermap.org/data/2.5/weather";
//使用OpenWeather数据的应用程序ID
最终字符串APP_ID=“5563C6A4DD7D7181B257988CC2B1AD1”;
//位置更新之间的时间(5000毫秒或5秒)
最终长最小时间=5000;
//位置更新之间的距离(1000米或1公里)
最终浮动最小距离=1000;
//请求代码
最终int请求_代码=123;
//TODO:在此处设置位置\u提供程序:
字符串LOCATION\u PROVIDER=LocationManager.GPS\u PROVIDER;
//成员变量:
文本视图mCityLabel;
ImageView mWeatherImage;
text查看MTTemperatureLabel;
//TODO:在此处声明LocationManager和LocationListener:
地点经理M地点经理;
LocationListener mLocationListener;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.weather\u controller\u layout);
//将布局中的元素链接到Java代码
mCityLabel=(TextView)findViewById(R.id.locationTV);
mWeatherImage=(ImageView)findViewById(R.id.V);
MTTemperatureLabel=(TextView)findViewById(R.id.v);
ImageButton changeCityButton=(ImageButton)findViewById(R.id.changeCityButton);
//TODO:在此处向changeCityButton添加OnClickListener:
changeCityButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意向意向=新意向(WeatherController.this、ChangeCityController.class);
星触觉(意向);
}
});
}
//TODO:在此处添加onResume():
@凌驾
受保护的void onResume(){
super.onResume();
d(“Clima”,“onResume()调用”);
Intent=getIntent();
String cityName=intent.getStringExtra(“cityName”);
if(cityName!=null){
//Log.d(“Clima”,cityName);
getWeatherForNewCity(城市名称);
}否则{
Log.d(“Clima”,“获取当前位置的天气”);
getWeatherForCurrentLocation();
}
}
//TODO:在此处添加getWeatherForNewCity(字符串城市):
NewCity(StringCity)的私人酒店{
RequestParams params=新的RequestParams();
参数put(“q”,城市);
参数put(“appid”,APP_ID);
letsDoSomeNetworking(参数);
}
//TODO:在此处添加getWeatherForCurrentLocation():
私有void getWeatherForCurrentLocation(){
mLocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
mlLocationListener=新位置Listener(){
@凌驾
已更改位置上的公共无效(位置){
//Log.d(“Clima”,“Clima”);
String latitude=String.valueOf(location.getLatitude());
String longitude=String.valueOf(location.getLongitude());
d(“收到Clima”、“onLocationChanged()回调”);
Log.d(“高潮”,“纬度是”+纬度);
Log.d(“Clima”,“经度为”+经度);
RequestParams params=新的RequestParams();
参数put(“纬度”,纬度);
参数put(“lon”,经度);
参数put(“appid”,APP_ID);
letsDoSomeNetworking(参数);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
d(“收到Clima”、“onProviderDisabled()回调”);
}
};
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
考虑到呼叫
//ActivityCompat#请求权限
//在此处请求缺少的权限,然后覆盖
//public void onRequestPermissionsResult(int-requestCode,字符串[]权限,
//国际[]格兰特雷苏
    LocationManager locationManager =
    (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    Location location;

    if(networkEnabled){
        longitude=location.getLongitude();
        latitude=location.getLatitude();
      }
    }
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>