Android Studios位置

时间:2016-11-14 11:39:45

标签: android android-studio location

我正在尝试创建一个小应用程序,可以找到用户当前所在的x和y坐标。问题是我只是在第143行得到一个空指针异常。

double lon = loc.getLongitude();

我认为我的getLastKnownLocation()返回null。我通过虚拟设备运行它。代码如下。

package com.team23.profilebuilder;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.location.LocationManager;

import java.util.List;

public class FindLocationActivity extends CustomActivity
{

// Buttons to be used
private Button locButton, saveButton;
// Textview to be displayed / used
private TextView locText, latText, longText, latVal, longVal;
// Location objects
private LocationManager locMan;
private LocationListener locLis;
private Location loc;

private static final String TAG = "FindLocationActivity";


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

    // Initialise all elements
    initialiseUIElements();
    initialiseOtherElements();

    // Set button listeners
    setListeners();
}

private void initialiseUIElements()
{
    locButton = (Button) findViewById(R.id.locButton);
    saveButton = (Button) findViewById(R.id.saveButton);
    locText = (TextView) findViewById(R.id.locText);
    latText = (TextView) findViewById(R.id.latText);
    longText = (TextView) findViewById(R.id.longText);
    latVal = (TextView) findViewById(R.id.latVal);
    longVal = (TextView) findViewById(R.id.longVal);
}

private void initialiseOtherElements()
{
    // Acquire a reference to the system LocationManager
    locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener which responds to location updates
    locLis = new LocationListener()
    {
        // Method called when a new location is found
        @Override
        public void onLocationChanged(Location location)
        {
            loc = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle)
        {

        }

        @Override
        public void onProviderEnabled(String s)
        {

        }

        @Override
        public void onProviderDisabled(String s)
        {

        }
    };
    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.
        return;
    }
    // Register the listener with Location Manager to receive updates
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locLis);
}

private void setListeners()
{
    locButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            findLocation();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            saveLocation();
        }
    });
}

private void findLocation()
{
    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.
        return;
    }
    // Retrieve last known location
    loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    // Retrieve values
    double lon = loc.getLongitude();
    double lat = loc.getLatitude();

    // Set TextView values
    longVal.setText(Double.toString(lon));
    latVal.setText(Double.toString(lat));
}

private void saveLocation()
{
    Log.v(TAG, "SaveLocation Method");
}
}

1 个答案:

答案 0 :(得分:0)

我在没有运行时权限的情况下使用目标22测试了下面的源代码,它对我来说很好。

检查 null 位置,然后检查设备中的 GPS 是否已开启..

package com.team23.profilebuilder;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.location.LocationManager;

import java.util.List;

public class FindLocationActivity extends CustomActivity
{

// Buttons to be used
private Button locButton, saveButton;
// Textview to be displayed / used
private TextView locText, latText, longText, latVal, longVal;
// Location objects
private LocationManager locMan;
private LocationListener locLis;
private Location loc;

private static final String TAG = "FindLocationActivity";


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

    // Initialise all elements
    initialiseUIElements();
    initialiseOtherElements();

    // Set button listeners
    setListeners();
}

private void initialiseUIElements()
{
    locButton = (Button) findViewById(R.id.locButton);
    saveButton = (Button) findViewById(R.id.saveButton);
    locText = (TextView) findViewById(R.id.locText);
    latText = (TextView) findViewById(R.id.latText);
    longText = (TextView) findViewById(R.id.longText);
    latVal = (TextView) findViewById(R.id.latVal);
    longVal = (TextView) findViewById(R.id.longVal);
}

private void initialiseOtherElements()
{
    // Acquire a reference to the system LocationManager
    locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener which responds to location updates
    locLis = new LocationListener()
    {
        // Method called when a new location is found
        @Override
        public void onLocationChanged(Location location)
        {
            loc = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle)
        {

        }

        @Override
        public void onProviderEnabled(String s)
        {

        }

        @Override
        public void onProviderDisabled(String s)
        {

        }
    };
    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.
        return;
    }
    // Register the listener with Location Manager to receive updates
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locLis);
}

private void setListeners()
{
    locButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            findLocation();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            saveLocation();
        }
    });
}

private void findLocation()
{
    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.
        return;
    }
    // Retrieve last known location
    loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

   if (loc!=null) {
        // Retrieve values
        double lon = loc.getLongitude();
        double lat = loc.getLatitude();
        // Set TextView values
        longVal.setText(Double.toString(lon));
        latVal.setText(Double.toString(lat));
    }
}

private void saveLocation()
{
    Log.v(TAG, "SaveLocation Method");
}
}