Skip to content Skip to sidebar Skip to footer

I M Trying To Develop An Android App To Get The Location Using Googleapi. But It Is Showing Error Like Could Not Get The Connection Factory Client

MainActivity.java package com.example.checkgps; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import android.os.Bundle; public c

Solution 1:

Use my code to get the location. Turn your gps and wifi on before :-

Use my Code. I have successfully found my current address using coordinates but for that you have to enable wifi and gps. first add all these permissions in your android manifest file

<uses-permissionandroid:name="android.permission.INTERNET" /><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.CHANGE_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /><uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE" /><uses-permissionandroid:name="android.permission.WAKE_LOCK" /><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" />

AndroidGPSTrackingActivity.java*

package com.example.gpstracking;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

publicclassAndroidGPSTrackingActivityextendsActivity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;
    ToggleButton gpstoggle,wifitoggle;
    static WifiManager wifiManager;
    LocationManager lm;
    WebView web;
    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        gpstoggle = (ToggleButton) findViewById(R.id.gps);
        wifitoggle = (ToggleButton) findViewById(R.id.wifi);

        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);

        //gps toggle
        gpstoggle.setOnCheckedChangeListener(newOnCheckedChangeListener() {

            @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    finalIntentpoke=newIntent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
                else{
                    finalIntentpoke=newIntent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
            }
        });
        //wifi toggle
        wifitoggle.setOnCheckedChangeListener(newOnCheckedChangeListener() {

            @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    wifiManager.setWifiEnabled(true);
                }
                else{
                    wifiManager.setWifiEnabled(false);
                }
            }
        });


        // show location button click event
        btnShowLocation.setOnClickListener(newView.OnClickListener() {

            @OverridepublicvoidonClick(View arg0) {        
                // create class object
                gps = newGPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     if(gps.canGetLocation()){

                    doublelatitude= gps.getLatitude();
                    doublelongitude= gps.getLongitude();

                    Geocodergcd=newGeocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = null;
                    try {
                        addresses = gcd.getFromLocation(latitude, longitude, 1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(!(addresses == null)){
                        if (!addresses.isEmpty() ){
                            System.out.println(addresses.get(0).getLocality());

                            Addressaddress= addresses.get(0);

                            StringaddressText= String.format("%s, %s, %s, %s, %s, %s",
                                    address.getAddressLine(0),
                                    address.getAddressLine(1),
                                    address.getAddressLine(2),
                                    address.getAddressLine(3),
                                    address.getPhone(),
                                    address.getPremises());

                            System.out.println(addressText);

                            // \n is for new line
                            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                        }else{
                            // can't get location// GPS or Network is not enabled// Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }
                    }else{
                        // can't get location// GPS or Network is not enabled// Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                }

            }
        });
    }

}

GPSTracker.java

package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

publicclassGPSTrackerextendsServiceimplementsLocationListener {

    privatefinal Context mContext;

    // flag for GPS statusbooleanisGPSEnabled=false;

    // flag for GPS statusbooleancanGetLocation=false;

    Location location; // locationdouble latitude; // latitudedouble longitude; // longitude// The minimum distance to change Updates in metersprivatestaticfinallongMIN_DISTANCE_CHANGE_FOR_UPDATES=10; // 10 meters// The minimum time between updates in millisecondsprivatestaticfinallongMIN_TIME_BW_UPDATES=1000 * 60 * 1; // 1 minute// Declaring a Location Managerprotected LocationManager locationManager;

    publicGPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network statusbooleanwifiEnabled= AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

            ConnectivityManagercm= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfoactiveNetwork= cm.getActiveNetworkInfo();

            this.canGetLocation = true;

            // if DATA Enabled get lat/long using WIFI Servicesif (activeNetwork.isConnected()) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if WIFI Enabled get lat/long using WIFI Servicesif (wifiEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if GPS Enabled get lat/long using GPS Servicesif (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

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

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

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */publicvoidstopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */publicdoublegetLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitudereturn latitude;
    }

    /**
     * Function to get longitude
     * */publicdoublegetLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitudereturn longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */publicbooleancanGetLocation() {
        returnthis.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */publicvoidshowSettingsAlert(){
        AlertDialog.BuilderalertDialog=newAlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", newDialogInterface.OnClickListener() {
            publicvoidonClick(DialogInterface dialog,int which) {
                Intentintent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
            publicvoidonClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @OverridepublicvoidonLocationChanged(Location location) {
    }

    @OverridepublicvoidonProviderDisabled(String provider) {
    }

    @OverridepublicvoidonProviderEnabled(String provider) {
    }

    @OverridepublicvoidonStatusChanged(String provider, int status, Bundle extras) {
    }

    @Overridepublic IBinder onBind(Intent arg0) {
        returnnull;
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><Buttonandroid:id="@+id/btnShowLocation"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Show Location"android:layout_centerVertical="true"android:layout_centerHorizontal="true"/><ToggleButtonandroid:id="@+id/gps"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/btnShowLocation"android:layout_alignRight="@+id/btnShowLocation"android:layout_marginBottom="49dp"android:layout_marginRight="72dp"android:text="GPS"
         /><ToggleButtonandroid:id="@+id/wifi"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/gps"android:layout_alignBottom="@+id/gps"android:layout_alignLeft="@+id/btnShowLocation"android:layout_marginLeft="79dp"android:text="WIFI" /><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/gps"android:layout_alignLeft="@+id/btnShowLocation"android:text="GPS"android:textSize="15sp" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView1"android:layout_alignBottom="@+id/textView1"android:layout_marginLeft="61dp"android:layout_toRightOf="@+id/textView1"android:text="WIFI"android:textSize="15sp" /></RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-sdkandroid:minSdkVersion="8" /><uses-permissionandroid:name="android.permission.INTERNET" /><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.CHANGE_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /><uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE" /><uses-permissionandroid:name="android.permission.WAKE_LOCK" /><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name" ><activityandroid:name=".AndroidGPSTrackingActivity"android:label="@string/app_name" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permissionandroid:name="android.permission.INTERNET" /></manifest>

Post a Comment for "I M Trying To Develop An Android App To Get The Location Using Googleapi. But It Is Showing Error Like Could Not Get The Connection Factory Client"