Android融合位置提供程序API每次都不返回正确的地址

时间:2016-03-12 19:02:51

标签: android android-asynctask location google-play-services fusedlocationproviderapi

我是Android的初学者,我正在使用Fused Location Provider Api构建基于位置的应用。应用程序采用坐标并使用反向地理编码来获取稍后使用所需的确切地址。但问题是它有时将纬度和经度都返回为0。同时大多数情况下它无法获得确切的地址,就好像它失败一样调用asyncTask类。请帮助,因为我无法想到它的任何解决方案。我在下面发布我的代码。

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;

import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;


import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks, com.google.android.gms.location.LocationListener {
    private String LOG_STRING="Connection";
    private  GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    Location mlocation;
    LocationManager location;
    double Latitude,Longitude;
    private Button messageSend;
    Intent in;
    boolean isGpsOn;
    DBAction dbcheck=new DBAction(MainActivity.this);


    public void onStart()
    {
        super.onStart();
        mGoogleApiClient.connect();
    }

    public void onDestroy()
    {
        if(mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();
        super.onDestroy();
    }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        messageSend=(Button)findViewById(R.id.sendMessage);
        location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //Checking for Google Play Services
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        if(status==ConnectionResult.SUCCESS)
            buildGoogleApiClient();
        else{
            Toast.makeText(this,"Google Play Services Not Available",Toast.LENGTH_SHORT).show();
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        }

        messageSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isGpsOn=location.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (dbcheck.isDBEmpty())
                    Toast.makeText(MainActivity.this, "No Contacts Saved", Toast.LENGTH_SHORT).show();
                else if(!isGpsOn)
                {
                    Toast.makeText(getApplicationContext(), "GPS is off!!Please turn it On", Toast.LENGTH_SHORT).show();
                    Intent GPSIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(GPSIntent);
                }
                else {

                    AsyncTry obj = new AsyncTry(getBaseContext());
                    obj.execute();
                }

            }
        });


    }



    protected synchronized void buildGoogleApiClient()
    {
        mGoogleApiClient=new GoogleApiClient.Builder(this)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
    }


    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest= LocationRequest.create();
       mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000);


        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

       // mlocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

//          if(mlocation!=null) {
//              Latitude = mlocation.getLatitude();
//              Longitude = mlocation.getLongitude();
//          }

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d(LOG_STRING,"Connetion Suspended");


    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(LOG_STRING,"Connection Failed");

    }

    @Override
    public void onLocationChanged(Location location) {
        mlocation=location;
        if(location!=null) {
            Latitude = mlocation.getLatitude();
            Longitude = mlocation.getLongitude();
        }


    }




    public void sendMessage(String add)
    {  List<DBAction> arrylist=new ArrayList<DBAction>();
        arrylist=dbcheck.readFromDB();
        SmsManager sm = SmsManager.getDefault();
        for(DBAction db:arrylist)
            sm.sendTextMessage(db.cNumber, null, add, null, null);
    }


    public class AsyncTry extends AsyncTask<Void, Integer, String> {
        Context context;
        String add;
        ProgressDialog pd;


        public AsyncTry(Context context) {

            this.context = context;
        }

        @Override
        protected String doInBackground(Void... params)
        {
            StringBuilder str = new StringBuilder();

            try {

                Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
                if (geocoder.isPresent()) {
                    List<Address> addresses = geocoder.getFromLocation(Latitude,Longitude, 1);
                    if (addresses != null)
                    {
                        Address fetchedAddress = addresses.get(0);
                        for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++)
                        {
                            str.append(fetchedAddress.getAddressLine(i)).append("\n");
                        }

                    }

                }
                add=str.toString();

            } catch (Exception e) {
                Log.d("Exception:", e.toString());
            }
            finally {
                if(add!=null)
                    add="Latitude:"+Latitude+"\nLongitude:"+Longitude+"\n"+add;
                else
                    add="Latitude:"+Latitude+"\nLongitude:"+Longitude+"\nCant Find Address for this location";
            }

            return add;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd=new ProgressDialog(MainActivity.this);
            pd.setMessage("Getting Location...");
            pd.setCancelable(false);
            pd.show();
        }


        protected void onPostExecute(String result) {
            if (pd.isShowing())
                pd.dismiss();

            if (result != null) {

              sendMessage(result);
                Toast.makeText(context,result,Toast.LENGTH_SHORT).show();
            }

        }
    }


}

1 个答案:

答案 0 :(得分:0)

@ p.matthew13根据此文件Getting the Last Known Location

  

为了让融合位置提供商检索精确的街道地址,请将应用清单中的位置权限设置为 ACCESS_FINE_LOCATION ,如以下示例所示:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gms.location.sample.basiclocationsample" >

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>

另一个事实:

  

PRIORITY_HIGH_ACCURACY 的优先级,以及您在应用清单中定义的 ACCESS_FINE_LOCATION 权限设置,以及5000毫秒(5秒)的快速更新间隔,使融合位置提供程序返回精确到几英尺内的位置更新。此方法适用于映射实时显示位置的应用程序。

获取位置的示例代码:

private void updateUI() {
mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
}

请仔细阅读本文档Making Your App Location-Aware,我无法确定您的错误,因为API工作只需要一些代码修订。使用该指南回溯您的代码,并比较您是否遵循相同的步骤/程序。