2015-07-05 2 views
38

मेरे ऐप का हिस्सा स्थान सेवाओं की आवश्यकता है, इसलिए यदि स्थान वर्तमान में बंद हो गया है, तो ऐप उपयोगकर्ता को इसे सक्षम करने के लिए संकेत देगा। (इसके अलावा this स्टैक ओवरफ़्लो जवाब में देखा)स्थान सेटिंग सेटिंग्स जीपीएस सक्षम करने के लिए संवाद संवाद - onActivityResult() छोड़ दिया

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
      .addLocationRequest(mLocationRequest); 
builder.setAlwaysShow(true); 

PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

result.setResultCallback(new ResultCallback<LocationSettingsResult>() 
{ 
    @Override 
    public void onResult(LocationSettingsResult result) 
    { 
     final Status status = result.getStatus(); 
     final LocationSettingsStates = result.getLocationSettingsStates(); 
     switch (status.getStatusCode()) 
     { 
      case LocationSettingsStatusCodes.SUCCESS: 
       // All location settings are satisfied. The client can initialize location 
       // requests here. 
       ... 
       Log.d("onResult", "SUCCESS"); 
       break; 
      case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
       // Location settings are not satisfied. But could be fixed by showing the user 
       // a dialog. 
       Log.d("onResult", "RESOLUTION_REQUIRED"); 
       try 
       { 
        // Show the dialog by calling startResolutionForResult(), 
        // and check the result in onActivityResult(). 
        status.startResolutionForResult(OuterClass.this, REQUEST_LOCATION); 
       } 
       catch (SendIntentException e) 
       { 
        // Ignore the error. 
       } 
       break; 
      case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
       // Location settings are not satisfied. However, we have no way to fix the 
       // settings so we won't show the dialog. 
       ... 
       Log.d("onResult", "UNAVAILABLE"); 
       break; 
     } 
    } 
}); 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    // This log is never called 
    Log.d("onActivityResult()", Integer.toString(resultCode)); 

    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); 
    switch (requestCode) 
    { 
     case REQUEST_LOCATION: 
      switch (resultCode) 
      { 
       case Activity.RESULT_OK: 
       { 
        // All required changes were successfully made 
        break; 
       } 
       case Activity.RESULT_CANCELED: 
       { 
        // The user was asked to change settings, but chose not to 
        break; 
       } 
       default: 
       {  
        break; 
       } 
      } 
      break; 
    } 
} 

इस कोड काम करता है अच्छी तरह से, हालांकि, onActivityResult() हमेशा होता है छोड़ा गया: Here मैं इसे कैसे कर रहा हूँ है। , onActivityResult() से उपयोगकर्ता Yes, No, या back दबाता है या नहीं, onActivityResult() नहीं चलता है।

मुझे onActivityResult() पर कॉल करने के लिए एंड्रॉइड की आवश्यकता है ताकि उपयोगकर्ता स्थान सेवाओं को चालू न करने का विकल्प चुनता है, तो मैं इसे उचित तरीके से संभाल सकता हूं।

Google के डेवलपर पृष्ठ (और उपरोक्त कोड) स्पष्ट रूप से कहता है कि onActivityResult() को कॉल किया जाना चाहिए। किसी को पता है कि यह क्यों छोड़ा जा रहा है?

मैं भी नहीं पता है कि इस लाइन का उद्देश्य है:

final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);

धन्यवाद!

संपादित करें: मेरे ऐप की संरचना पर बुनियादी जानकारी:

  • यह कोड Fragment जो GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, और LocationListener लागू करता स्थान अपडेट प्राप्त करने के onResume() विधि भीतर निहित है। उदाहरण here देखा गया।
  • onLocationChanged()Fragment में एक कस्टम View कॉल invalidate() होगा और अद्यतन जानकारी के साथ स्वयं को फिर से खींचा जाएगा।

उत्तर

85

ऐसा लगता है कि मुख्य मुद्दा यह है कि आपके पास फ्रैगमेंट में सभी कोड हैं, और startResolutionForResult() में उस गतिविधि को पारित करने की आवश्यकता है, गतिविधि onActivityResult() कॉलबैक प्राप्त करती है।

एक तरीका यह है कि चारों ओर पाने के लिए, तकनीक here वर्णित उपयोग करने के लिए मैन्युअल रूप से गतिविधि से टुकड़ा के onActivityResult() विधि कॉल जब परिणाम में आता है।

मैं सिर्फ इस सरल काम कर उदाहरण मिला है।

पहले, गतिविधि, जो टुकड़ा कहते हैं, और यह भी टुकड़ा करने के लिए onActivityResult() का नतीजा साथ दी जाने वाली कार्यक्षमता है:

public class MainActivity extends AppCompatActivity{ 

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

     lFrag = LocationFragment.newInstance(); 
     getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, lFrag).commit(); 

    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == LocationFragment.REQUEST_LOCATION){ 
      lFrag.onActivityResult(requestCode, resultCode, data); 
     } 
     else { 
      super.onActivityResult(requestCode, resultCode, data); 
     } 
    } 
} 

यहाँ टुकड़ा है, जो कार्यक्षमता के सभी दिखाने के लिए होता है संवाद, और परिणाम संभाल लें। इस सरल उदाहरण में मैंने टोस्ट संदेशों का उपयोग यह सत्यापित करने के लिए किया कि यह अपेक्षित काम कर रहा है। ध्यान दें कि आपके प्रश्न में कोड से मैंने जो मुख्य परिवर्तन किया है वह getActivity() का उपयोग startResolutionForResult() पर कॉल के लिए आवश्यक गतिविधि संदर्भ प्राप्त करने के लिए है।

public class LocationFragment extends Fragment 
     implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener { 


    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 
    PendingResult<LocationSettingsResult> result; 
    final static int REQUEST_LOCATION = 199; 

    public static LocationFragment newInstance() { 
     LocationFragment fragment = new LocationFragment(); 
     return fragment; 
    } 

    public LocationFragment() { 
     // Required empty public constructor 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 

     mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this).build(); 
     mGoogleApiClient.connect(); 

     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment_location, container, false); 
    } 


    @Override 
    public void onResume() { 
     super.onResume(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 

     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(30 * 1000); 
     mLocationRequest.setFastestInterval(5 * 1000); 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 
     builder.setAlwaysShow(true); 

     result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

     result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
      @Override 
      public void onResult(LocationSettingsResult result) { 
       final Status status = result.getStatus(); 
       //final LocationSettingsStates state = result.getLocationSettingsStates(); 
       switch (status.getStatusCode()) { 
        case LocationSettingsStatusCodes.SUCCESS: 
         // All location settings are satisfied. The client can initialize location 
         // requests here. 
         //... 
         break; 
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
         // Location settings are not satisfied. But could be fixed by showing the user 
         // a dialog. 
         try { 
          // Show the dialog by calling startResolutionForResult(), 
          // and check the result in onActivityResult(). 
          status.startResolutionForResult(
            getActivity(), 
            REQUEST_LOCATION); 
         } catch (IntentSender.SendIntentException e) { 
          // Ignore the error. 
         } 
         break; 
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
         // Location settings are not satisfied. However, we have no way to fix the 
         // settings so we won't show the dialog. 
         //... 
         break; 
       } 
      } 
     }); 

    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     Log.d("onActivityResult()", Integer.toString(resultCode)); 

     //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); 
     switch (requestCode) 
     { 
      case REQUEST_LOCATION: 
       switch (resultCode) 
       { 
        case Activity.RESULT_OK: 
        { 
         // All required changes were successfully made 
         Toast.makeText(getActivity(), "Location enabled by user!", Toast.LENGTH_LONG).show(); 
         break; 
        } 
        case Activity.RESULT_CANCELED: 
        { 
         // The user was asked to change settings, but chose not to 
         Toast.makeText(getActivity(), "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show(); 
         break; 
        } 
        default: 
        { 
         break; 
        } 
       } 
       break; 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

} 

यहाँ परिणाम नेत्रहीन हैं, पहला संवाद नहीं दिखाया जाता है, तो स्थान मोड अक्षम किया गया है:

enter image description here

फिर, यदि उपयोगकर्ता कोई क्लिक करता है तो परिणाम की गतिविधि से करने के लिए पारित हो जाता है टुकड़ा है, जो एक टोस्ट पता चलता है: जब उपयोगकर्ता हाँ क्लिक करता है

enter image description here

यही बात, ख एक सफलता परिणाम के साथ केन्द्र शासित प्रदेशों, और स्थान मोड सक्षम है:

enter image description here

ध्यान दें कि यह सिर्फ गतिविधि में इस कार्यक्षमता के सभी रखने के लिए एक बेहतर विकल्प हो सकता है, और फिर टुकड़ा में एक सार्वजनिक विधि में फोन जब परिणाम आता है।

गतिविधि में कार्यक्षमता को बनाए रखने के लिए यहां पूरी तरह से काम करने वाला कोड है। बेशक इस समाधान में, आपको onActivityResult() के बाद स्थान मोड की स्थिति अपडेट करने के लिए फ्रैगमेंट में कॉल जोड़ने की आवश्यकता होगी।

public class MainActivity extends AppCompatActivity 
     implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener { 


    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 
    PendingResult<LocationSettingsResult> result; 
    final static int REQUEST_LOCATION = 199; 

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

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this).build(); 
     mGoogleApiClient.connect(); 

    } 

    @Override 
    public void onConnected(Bundle bundle) { 

     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(30 * 1000); 
     mLocationRequest.setFastestInterval(5 * 1000); 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 
     builder.setAlwaysShow(true); 

     result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

     result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
      @Override 
      public void onResult(LocationSettingsResult result) { 
       final Status status = result.getStatus(); 
       //final LocationSettingsStates state = result.getLocationSettingsStates(); 
       switch (status.getStatusCode()) { 
        case LocationSettingsStatusCodes.SUCCESS: 
         // All location settings are satisfied. The client can initialize location 
         // requests here. 
         //... 
         break; 
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
         // Location settings are not satisfied. But could be fixed by showing the user 
         // a dialog. 
         try { 
          // Show the dialog by calling startResolutionForResult(), 
          // and check the result in onActivityResult(). 
          status.startResolutionForResult(
            MainActivity.this, 
            REQUEST_LOCATION); 
         } catch (SendIntentException e) { 
          // Ignore the error. 
         } 
         break; 
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
         // Location settings are not satisfied. However, we have no way to fix the 
         // settings so we won't show the dialog. 
         //... 
         break; 
       } 
      } 
     }); 

    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     Log.d("onActivityResult()", Integer.toString(resultCode)); 

     //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); 
     switch (requestCode) 
     { 
      case REQUEST_LOCATION: 
       switch (resultCode) 
       { 
        case Activity.RESULT_OK: 
        { 
         // All required changes were successfully made 
         Toast.makeText(MainActivity.this, "Location enabled by user!", Toast.LENGTH_LONG).show(); 
         break; 
        } 
        case Activity.RESULT_CANCELED: 
        { 
         // The user was asked to change settings, but chose not to 
         Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show(); 
         break; 
        } 
        default: 
        { 
         break; 
        } 
       } 
       break; 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 
} 
+0

ActivityResult –

+0

पर स्थान को रीफ्रेश कैसे करें उपयोगकर्ता ने स्थान सेवाओं को सक्षम करने के बाद आपको स्थान अपडेट का अनुरोध करने की आवश्यकता होगी। यहां देखें: http://stackoverflow.com/questions/34582370/how-can-i-use-google-maps-and-locationmanager-to-show-current-location-on-androi –

+0

हाय @DanielNugent पोस्ट के लिए धन्यवाद । मेरे पास एक ऐसी स्थिति है जहां मैं जांच कर रहा हूं कि प्रत्येक बार जब मैं बटन पर क्लिक करता हूं तो उपयोगकर्ता की सेटिंग्स की अपेक्षा की जाती है। जिसका अर्थ है, मैं यह देखने के लिए हर बार परिणाम.setResultCallback बुला रहा हूं कि उपयोगकर्ता ने सेटिंग बदल दी है या नहीं। आश्चर्यजनक रूप से, यह केवल पहली बार काम करता है। onResult कभी नहीं बुलाया जाएगा। मेरे पास एक ही सवाल है http://stackoverflow.com/questions/38151650/android-fusedlocations-settingsapi-does-not-work-more-than-once। क्या आप कृपया –

0

मुझे लगता है कि आप अनुरोध कोड के लिए विभिन्न स्थिरांक REQUEST_CHECK_SETTINGS और REQUEST_LOCATION का उपयोग करते हैं। क्या उनके पास समान मूल्य है?

कोड के लिए: final LocationSettingsStates states = LocationSettingsStates.fromIntent(intent);
उपरोक्त कोड का उद्देश्य सेटिंग बदलने के बाद स्थान सेटिंग (जैसे नेटवर्क, जीपीएस, ...) की वर्तमान स्थिति प्राप्त करना है।
इसके अलावा, आपके कोड में, मुझे लगता है कि यह LocationSettingsStates.fromIntent(data); होना चाहिए क्योंकि intent यहां exixst नहीं है, शायद यह सिर्फ एक टाइपो है।

+0

धन्यवाद। इस प्रश्न के लिए, मैंने सीधे Google के डेवलपर पृष्ठों से कोड कॉपी किया। वे त्रुटियां मेरे ऐप में मौजूद नहीं थीं, लेकिन वे वैसे भी समस्या नहीं थीं। यदि आप अब 'atctivityResult()' देखते हैं, तो आपको 'लॉग' फ़ंक्शन दिखाई देगा जिसे कभी भी नहीं कहा जाता है। – pez

0

इसकी वजह से टुकड़े में मौजूद .. प्रयास करें सभी Google API कोड निम्नलिखित इसे दूर करने में मदद मिलेगी ...

अपने टुकड़े के लिए 1. बनाएँ एक खाली निर्माता। onCreateView() से पहले

2.need OnCreate() विधि ...

OnCreate() के अंदर गूगल एपीआई कोड 3.paste ....

public mainFragment(){ 

} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    try { 
     buildGoogleApiClient(); 
     buildLocationSettingsRequest(); 

     checkLocationSettings(); 
     mGoogleApiClient.connect(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

के लिए अपने संदर्भ ...

Click here...

19

आप को यह जोड़ने की जरूरत है अपने परिणाम कॉलबैक:

case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
    try { 
     fragment.startIntentSenderForResult(status.getResolution().getIntentSender(), REQUEST_CHECK_SETTINGS, null, 0, 0, 0, null); 
    } catch (IntentSender.SendIntentException e) { 
     // Ignore the error. 
    } 
    break; 

onActivityResult अपने टुकड़ा पर बुलाया जाएगा, आप अपनी गतिविधि में मैन्युअल रूप से इसे कॉल करने के लिए की जरूरत नहीं है। यह अनिवार्य रूप से startResolutionForResult काम करता है।

+0

कृपया अपने इनलाइन कोड बिट – YakovL

+1

के आस-पास बैकटिक्स रैपर जोड़ें, मैंने इस पंक्ति पर टिप्पणी की थी: status.startResolutionForResult (hostActivity, REQUEST_CHECK_SETTINGS); और मुख्य गतिविधि मेंActiivtyResult पर ओवरराइड किए बिना अपने कोड और इसके काम का उपयोग किया। –

+0

मेरे साथ काम किया। धन्यवाद दोस्त। –

0

गतिविधि में खंड क्षेत्र को सहेजना (जैसा कि डैनियल सुझाया गया है) अक्सर एक अच्छा निर्णय नहीं होता है, क्योंकि कल्पना करें कि आपके पास कई टुकड़े हैं और प्रत्येक में स्थान कोड है।मैं एक अलग ढंग से किया था:

public class MainActivity extends Activity implements PlaceFragment.SettingsModifyHandler { 

    private static final int LOCATION_SETTINGS_RESULT = 1; 
    private OnResultCallback placeCallback; 

    ... 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == LOCATION_SETTINGS_RESULT) { 
      if (resultCode == Activity.RESULT_OK) { 
       placeCallback.resultOk(); 
      } else { 
       placeCallback.resultFail(); 
      } 
     placeCallback = null; 
     } 
    } 

    @Override 
    public void handle(IntentSender intentSender, OnResultCallback callback) { 
     placeCallback = callback; 
     try { 
      startIntentSenderForResult(intentSender, LOCATION_SETTINGS_RESULT, null, 0, 0, 0); 
     } catch (IntentSender.SendIntentException e) { 
      callback.resultFail(); 
     } 
    } 
} 

public class PlaceFragment extends Fragment { 

    private SettingsModifyHandler settingsModifyHandler; 

    ... 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     if (context instanceof SettingsModifyHandler) { 
      settingsModifyHandler = (SettingsModifyHandler) context; 
     } else { 
      throw new RuntimeException("Parent activity must implement PlaceFragment.SettingsModifyHandler interface"); 
     } 
    } 

    /* Callback from module, where you implemented status.getStatusCode().LocationSettingsStatusCodes.RESOLUTION_REQUIRED case 
    (status is instance of com.google.android.gms.common.api.Status) 
    You provide intentSender here through status.getResolution().getIntentSender() */ 
    @Override 
    public void placeLoadError(IntentSender sender) { 
     TextView view_text = (TextView) root.findViewById(R.id.text_error); 
     TextView view_btn = (TextView) root.findViewById(R.id.btn_reply); 

     view_text.setText("Need to change location settings"); 
     view_btn.setText("Change"); 
     view_btn.setOnClickListener(v -> { 
      settingsModifyHandler.handle(sender, new SettingsModifyHandler.OnResultCallback() { 
       @Override 
       public void resultOk() { 
        presenter.loadPlace(placeId); 
       } 

       @Override 
       public void resultFail() { 
        ToastUtils.show("You should change location settings!"); 
       } 
      }); 
     }); 
    } 

    public interface SettingsModifyHandler { 
     void handle(IntentSender intentSender, OnResultCallback callback); 

     interface OnResultCallback { 
      void resultOk(); 
      void resultFail(); 
     } 
    } 
} 
0

स्रोत कोड

https://drive.google.com/open?id=0BzBKpZ4nzNzUOXM2eEhHM3hOZk0

build.gradle फ़ाइल में निर्भरता

संकलन 'com.google.android.gms: खेल-सेवाएं-स्थान: 7.8.0 '

मैनिफेस्ट फ़ाइल में अनुमति

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 


package com.keshav.enablelocationwithokcancelbuttoncontrol; 

import android.content.Context; 
import android.location.Address; 
import android.location.Geocoder; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.util.Log; 

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

public class LocationAddress 
{ 
    private static final String TAG = "LocationAddress"; 

    public static void getAddressFromLocation(final double latitude, final double longitude, 
               final Context context, final Handler handler) { 
     Thread thread = new Thread() { 
      @Override 
      public void run() { 
       Geocoder geocoder = new Geocoder(context, Locale.getDefault()); 
       String result = null; 
       try { 
        List<Address> addressList = geocoder.getFromLocation(
          latitude, longitude, 1); 
        if (addressList != null && addressList.size() > 0) { 
         Address address = addressList.get(0); 
         StringBuilder sb = new StringBuilder(); 
         for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { 
          sb.append(address.getAddressLine(i)).append("\n"); 
         } 
         sb.append(address.getLocality()).append("\n"); 
         sb.append(address.getPostalCode()).append("\n"); 
         sb.append(address.getCountryName()); 
         result = sb.toString(); 
        } 
       } catch (IOException e) { 
        Log.e(TAG, "Unable connect to Geocoder", e); 
       } finally { 
        Message message = Message.obtain(); 
        message.setTarget(handler); 
        if (result != null) { 
         message.what = 1; 
         Bundle bundle = new Bundle(); 
         result = "Latitude: " + latitude + " Longitude: " + longitude + 
           "\n\nAddress:\n" + result; 
         bundle.putString("address", result); 
         message.setData(bundle); 
        } else { 
         message.what = 1; 
         Bundle bundle = new Bundle(); 
         result = "Latitude: " + latitude + " Longitude: " + longitude + 
           "\n Unable to get address for this lat-long."; 
         bundle.putString("address", result); 
         message.setData(bundle); 
        } 
        message.sendToTarget(); 
       } 
      } 
     }; 
     thread.start(); 
    } 
} 

package com.keshav.enablelocationwithokcancelbuttoncontrol; 

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.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

public class GPSTracker extends Service implements LocationListener 
{ 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

    public GPSTracker(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 status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        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 (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 

       // if GPS Enabled get lat/long using GPS Services 
       if (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 
    * */ 

    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    /** 
    * Function to get latitude 
    * */ 

    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 

    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * @return boolean 
    * */ 

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

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    * */ 

    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog = new AlertDialog.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", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
      } 
     }); 

     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

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

    @Override 
    public void onLocationChanged(Location location) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

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

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


package com.keshav.enablelocationwithokcancelbuttoncontrol; 

import android.content.Context; 
import android.location.Address; 
import android.location.Geocoder; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.util.Log; 

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

public class LocationAddress 
{ 
    private static final String TAG = "LocationAddress"; 

    public static void getAddressFromLocation(final double latitude, final double longitude, 
               final Context context, final Handler handler) { 
     Thread thread = new Thread() { 
      @Override 
      public void run() { 
       Geocoder geocoder = new Geocoder(context, Locale.getDefault()); 
       String result = null; 
       try { 
        List<Address> addressList = geocoder.getFromLocation(
          latitude, longitude, 1); 
        if (addressList != null && addressList.size() > 0) { 
         Address address = addressList.get(0); 
         StringBuilder sb = new StringBuilder(); 
         for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { 
          sb.append(address.getAddressLine(i)).append("\n"); 
         } 
         sb.append(address.getLocality()).append("\n"); 
         sb.append(address.getPostalCode()).append("\n"); 
         sb.append(address.getCountryName()); 
         result = sb.toString(); 
        } 
       } catch (IOException e) { 
        Log.e(TAG, "Unable connect to Geocoder", e); 
       } finally { 
        Message message = Message.obtain(); 
        message.setTarget(handler); 
        if (result != null) { 
         message.what = 1; 
         Bundle bundle = new Bundle(); 
         result = "Latitude: " + latitude + " Longitude: " + longitude + 
           "\n\nAddress:\n" + result; 
         bundle.putString("address", result); 
         message.setData(bundle); 
        } else { 
         message.what = 1; 
         Bundle bundle = new Bundle(); 
         result = "Latitude: " + latitude + " Longitude: " + longitude + 
           "\n Unable to get address for this lat-long."; 
         bundle.putString("address", result); 
         message.setData(bundle); 
        } 
        message.sendToTarget(); 
       } 
      } 
     }; 
     thread.start(); 
    } 
} 
संबंधित मुद्दे