查找位置

时间:2016-05-14 11:53:36

标签: android service gps locationlistener

我正在编写一个程序,我需要协调我的位置,纬度和经度。我的问题是我无法得到位置和我的日志拉特 和lng是0和0,我正在尝试在运行android M 6.0.1的nexus 6P设备上运行它。

这是我的GPSTracker班级

package es.euphrat.clover.compass;

import android.Manifest;
import android.app.Service;
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.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;


public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    private Location mLocation;

    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;

    protected LocationManager mLocationManager;

    public GPSTracker(Context context) {
        mContext = context;
        getLocation();
    }

    private Location getLocation() {

        try {
            mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {

            } else {

                this.canGetLocation = true;

                if (isNetworkEnabled) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    }

                }
                if (mLocationManager != null) {
                    mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if (mLocation != null) {
                        latitude = mLocation.getLatitude();
                        longitude = mLocation.getLongitude();
                    }
                }
            }

            if (isGPSEnabled) {
                if (mLocation == null) {

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    }
                    if (mLocationManager != null) {
                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if (mLocation != null) {
                            latitude = mLocation.getLatitude();
                            longitude = mLocation.getLongitude();
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return mLocation;
    }

    public void stopUsingGPS() {
        if (mLocationManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                mLocationManager.removeUpdates(GPSTracker.this);
            }

        }
    }

    public double getLatitude(){
        if (mLocation != null){
            latitude = mLocation.getLatitude();
        }
        return latitude;
    }
    public double getLongitude(){
        if (mLocation != null){
            longitude = mLocation.getLongitude();
        }
        return longitude;
    }


    public boolean canGetLocation(){
        return this.canGetLocation;
    }

    @Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

这是我在主要活动中记录结果的主要方法

package es.euphrat.clover.compass.activity;

import android.Manifest;
import android.content.Context;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import es.euphrat.clover.compass.GPSTracker;
import es.euphrat.clover.compass.R;
import es.euphrat.clover.compass.adapters.CityAdapter;
import es.euphrat.clover.compass.boxes.CityBox;
import es.euphrat.clover.compass.boxes.CompassAndCityBox;
import es.euphrat.clover.compass.boxes.DateBox;
import es.euphrat.clover.compass.boxes.DayAndNight;
import es.euphrat.clover.compass.database.City;
import es.euphrat.clover.compass.database.DataBaseHelper;
import info.alqiblah.taqwim.MA6;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;


public class MainActivity extends AppCompatActivity implements      SensorEventListener {

public final String TAG = this.getClass().getSimpleName();

protected DataBaseHelper mDataBaseHelper;
protected CompassAndCityBox mCompassAndCityBox;
protected DateBox mDateBox;
protected CityBox mCityBox;
protected DayAndNight mDayAndNight;
protected SensorManager mSensorManager;
protected LinearLayout myRoot;
protected DrawerLayout drawerLayout;
protected RelativeLayout gpsDrawer;
protected RelativeLayout cityListDrawer;
protected ArrayList<String> mCityNames;
protected ListView cityListView;
protected EditText searchCity;
protected City[] mCities;
private CityAdapter mCityListAdapter;
protected City currentCity;
protected GPSTracker mGPSTracker;



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

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

    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
            .setDefaultFontPath(getTypeface())
            .setFontAttrId(R.attr.fontPath)
            .build());

    myRoot = (LinearLayout) findViewById(R.id.my_root);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    gpsDrawer = (RelativeLayout) findViewById(R.id.gps_drawer);
    cityListDrawer = (RelativeLayout) findViewById(R.id.city_list_drawer);
    cityListView = (ListView) findViewById(R.id.listView);
    searchCity = (EditText) findViewById(R.id.search_city);

    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    MA6.InitPlanetsTerms(this);
    mGPSTracker = new GPSTracker(this);
    mCityNames = new ArrayList<>();
    mDataBaseHelper = new DataBaseHelper(this);
    mCityBox = new CityBox(this);
    mDateBox = new DateBox(this);
    mCompassAndCityBox = new CompassAndCityBox(this);
    mDayAndNight = new DayAndNight(this);

    myRoot.addView(mCityBox);
    myRoot.addView(mDateBox);
    myRoot.addView(mCompassAndCityBox);
    myRoot.addView(mDayAndNight);

    searchCityTextView();
    createTheDataBase();


    double a = mGPSTracker.getLatitude();
    if (mGPSTracker.canGetLocation()) {

        Log.d(TAG, String.valueOf(mGPSTracker.canGetLocation()));
        Log.d(TAG, a + "," + mGPSTracker.getLongitude());
    }
}




private void createTheDataBase() {
    try {
        mDataBaseHelper.createDataBase();
    } catch (IOException e) {
        Log.e(TAG , "Cannot Create DataBase", e);
    }
}

private void searchCityTextView() {
    searchCity.clearComposingText();
    searchCity.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Cursor cursor =     mDataBaseHelper.selectOrSearchAllCities(searchCity.getText().toString());
            updateList(cursor);

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

private void updateList(Cursor cursor) {
    mCityNames.clear();

    final int cityName = cursor.getColumnIndex(DataBaseHelper.CITY_NAME);
    int timeZone = cursor.getColumnIndex(DataBaseHelper.CITY_TIMEZONE);
    int countryName = cursor.getColumnIndex(DataBaseHelper.COUNTRY_NAME);
    int lat = cursor.getColumnIndex(DataBaseHelper.CITY_LATITUDE);
    int lng = cursor.getColumnIndex(DataBaseHelper.CITY_LONGITUDE);

    mCities = new City[cursor.getCount()];
    int c = 0;
    cursor.moveToFirst();
    while (!cursor.isAfterLast()){

        String city = cursor.getString(cityName);
        String tZone = cursor.getString(timeZone);
        String country = cursor.getString(countryName);
        float latitude = cursor.getFloat(lat);
        float longitude = cursor.getFloat(lng);

        mCities[c] = new City(city,tZone,country,latitude,longitude);
        c++;
        cursor.moveToNext();
    }

    mCityListAdapter = new CityAdapter(this, mCities);
    cityListView.setAdapter(mCityListAdapter);
    cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            currentCity = new City(mCities[position]);
            drawerLayout.closeDrawer(cityListDrawer);
            mCityBox.setCurrentCityName(currentCity);
            hideKeyboard();
        }
    });
}

private void hideKeyboard() {
    InputMethodManager inputManager =
            (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
}


public void antenaClick(View view) {

    drawerLayout.openDrawer(gpsDrawer);
}

public void pinpointClick (View view){

    drawerLayout.openDrawer(cityListDrawer);
}



@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
            SensorManager.SENSOR_DELAY_GAME);

    mDataBaseHelper.openDataBase();

    Cursor cursor = mDataBaseHelper.selectOrSearchAllCities(searchCity.getText().toString());
    updateList(cursor);

}

@Override
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);

    mDataBaseHelper.close();
}

@Override
public void onSensorChanged(SensorEvent event) {
    float degree = Math.round(event.values[0]);
    mCompassAndCityBox.setDegreeFromNorth(degree,currentCity);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

private String getTypeface(){

    if( Locale.getDefault().getDisplayLanguage().toLowerCase().startsWith("en")) return "fonts/Roboto-Medium.ttf";

    else return "fonts/IRAN Sans.ttf";
}

}

这是我的清单

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="es.euphrat.clover.compass">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme"
            >
            <activity android:name=".activity.MainActivity"
                android:screenOrientation="portrait">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>

                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
        </application>

        </manifest>

任何人都可以帮我找到解决问题的方法。

0 个答案:

没有答案