Android GPS服务每次都返回0.0

时间:2017-07-05 08:15:39

标签: android gps

我一直在寻找几天,但找不到问题所在。当我点击按钮A时,我想知道我当前的位置,当我点击按钮B时也知道我的位置。问题是这样,当我点击B它似乎工作正常,但不是A.我使用完全相同的代码,但在某种程度上它只是不适用于A.

这是我的GetGPSLocation代码 `

package com.example.eandl.gps;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;



public class GetGPSLocation {
    private Context context;
    private static double lat;
    private static double lang;

    public GetGPSLocation(Context context){
        this.context = context;
        this.lat = 0.0;
        this.lang = 0.0;
    }



    public void setLat(double lat) {
        this.lat = lat;
    }



    public void setLang(double lang) {
        this.lang = lang;
    }

    public Boolean displayGpsStatus() {
        final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );

        if ( !manager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) {
            return false;
        }else{
            return true;
        }
    }

    public double[] getLatLong(){
        double[] latLong = new double[2];
        if(displayGpsStatus()){

            LocationManager locationMangaer = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
            LocationListener locationListener = new MyLocationListener(context, this);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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((Activity)context,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }
            if(checkLocationPermission()){
                locationMangaer.requestLocationUpdates(LocationManager
                        .NETWORK_PROVIDER, 0, 0, locationListener);
            }

            Log.d("findError", getLang() + "");
            latLong[0] = getLat();
            latLong[1] = getLang();

        }else{
            alertbox("Gps status", "Your Device's GPS is Disable");
        }


        return latLong;
    }

    public boolean checkLocationPermission()
    {
        String permission = "android.permission.ACCESS_FINE_LOCATION";
        int res = context.checkCallingOrSelfPermission(permission);

        return (res == PackageManager.PERMISSION_GRANTED);
    }


    protected void alertbox(String title, String mymessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(mymessage)
                .setCancelable(false)
                .setTitle(title)
                .setPositiveButton("Gps On",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                context.startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

}

`

Listiener

package com.example.eandl.gps;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;



public class MyLocationListener implements LocationListener {

    private Context context;
    private GetGPSLocation getGPSLocation;


    public MyLocationListener(Context context, GetGPSLocation getGPSLocation) {
        this.context = context;
        this.getGPSLocation = getGPSLocation;
    }


    @Override
    public void onLocationChanged(Location loc) {
        if(loc != null){
            getGPSLocation.setLat(loc.getLatitude());
            getGPSLocation.setLang(loc.getLongitude());
        }
    }



    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

我试图调用它的方式是通过新的GetGPSLocation(上下文).getLatLong,但正如我所说,有时它会返回我的位置,有时会返回0.0

谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,首先我在创建像这样的视图时设置它

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    //Fixa vit med blå text
    myView = inflater.inflate(R.layout.fragment_signup, container, false);
    placements = new ArrayList<CheckBox>();
    GetPlacements getPlacements = new GetPlacements(this);
    getPlacements.execute();

    getGPSLocation = new GetGPSLocation(myView.getContext());
    getGPSLocation.getLatLong();

然后这是按钮A上的onclicklistener

                getGPSLocation.getLatLong();
                DatabasSender databasSender = new DatabasSender(myView.getContext());
                User user = new User(name.getText().toString(), email.getText().toString(), 0);
                user.setSignup(true);
                user.setEdu(edu.getText().toString());
                user.setPhone(phone.getText().toString());
                user.setPlacements(places);
                databasSender.execute(user);

这是我使用AsyncTask

的数据存储器
public DatabasSender(Context context) {
    this.context = context;
    getGPSLocation = new GetGPSLocation(context);

}

@Override
protected void onPreExecute() {
    latLong = getGPSLocation.getLatLong();
}
@Override
protected Object doInBackground(Object[] objects) {
    urlPatten = "..../"+latLong[0]+"&"+latLong[1];
}

我使用与Button B完全相同的代码。