2016年10月14日 星期五

location address

Ref : https://github.com/googlesamples/android-play-location/tree/master/LocationAddress


裡面的code 有一個  service class


public class FetchAddressIntentService  extends IntentService {


}


必須要實作這個function ...
@Overrideprotected void onHandleIntent(Intent intent) {

mReceiver = intent.getParcelableExtra(Constants.RECEIVER);

// Get the location passed to this service through an extra.Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);


//  產生一個新的 Geocoder
Geocoder geocoder = new Geocoder(this, Locale.getDefault());


//  開始解碼....根據你傳進來的 精度和緯度
addresses = geocoder.getFromLocation(
        location.getLatitude(),
        location.getLongitude(),
        // In this sample, we get just a single address.        1);

  Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();

   addressFragments.add(address.getCountryName());  // 台灣
addressFragments.add(address.getFeatureName());  // 121addressFragments.add(address.getLocality());    //  士林區//addressFragments.add(address.getSubLocality());addressFragments.add(address.getThoroughfare()); // 社中街

deliverResultToReceiver(Constants.SUCCESS_RESULT,
        TextUtils.join(System.getProperty("line.separator"), addressFragments));
}

再來看   deliverResultToReceiver()

//  透過傳送  bundle 的物件... 呼叫mReceiver.send()

private void deliverResultToReceiver(int resultCode, String message) {
    Bundle bundle = new Bundle();
    bundle.putString(Constants.RESULT_DATA_KEY, message);
    mReceiver.send(resultCode, bundle);
}


記得在    AndroidManifest.xml 裡面加入這個Service 

<application

>
<service    android:name=".FetchAddressIntentService"    android:exported="false"/>


</application>



接下來看  MainActivity


按下Button   會呼叫     fetchAddressButtonHandler()

public void fetchAddressButtonHandler(View view) {
    // We only start the service to fetch the address if GoogleApiClient is connected.    if (mGoogleApiClient.isConnected() && mLastLocation != null) {
        startIntentService();
    }
    // If GoogleApiClient isn't connected, we process the user's request by setting    // mAddressRequested to true. Later, when GoogleApiClient connects, we launch the service to    // fetch the address. As far as the user is concerned, pressing the Fetch Address button    // immediately kicks off the process of getting the address.    mAddressRequested = true;
    updateUIWidgets();
}


重點是會呼叫     startIntentService();

protected void startIntentService() {
    // Create an intent for passing to the intent service responsible for fetching the address.    Intent intent = new Intent(this, FetchAddressIntentService.class);

    // Pass the result receiver as an extra to the service.    intent.putExtra(Constants.RECEIVER, mResultReceiver);

    // Pass the location data as an extra to the service.    intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);

    // Start the service. If the service isn't already running, it is instantiated and started    // (creating a process for it if needed); if it is running then it remains running. The    // service kills itself automatically once all intents are processed.    startService(intent);
}


然後就會啟動   FetchAddressIntentService  這個Service....

 
當    連接上的時候...也會去呼叫   startIntentService();
@Overridepublic void onConnected(Bundle connectionHint) {
    // Gets the best and most recent location currently available, which may be null    // in rare cases when a location is not available.    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        // Determine whether a Geocoder is available.        if (!Geocoder.isPresent()) {
            Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_LONG).show();
            return;
        }
        // It is possible that the user presses the button to get the address before the        // GoogleApiClient object successfully connects. In such a case, mAddressRequested        // is set to true, but no attempt is made to fetch the address (see        // fetchAddressButtonHandler()) . Instead, we start the intent service here if the        // user has requested an address, since we now have a connection to GoogleApiClient.        if (mAddressRequested) {
            startIntentService();
        }
    }
}

至於傳回來的結果要怎模得到....

首先要先看這個變數...

private AddressResultReceiver mResultReceiver;


因為    // Pass the result receiver as an extra to the service.
    intent.putExtra(Constants.RECEIVER, mResultReceiver);   

它的變數實作在

// 這一行要加..不能會說找不道這個ParcelCreator function
@SuppressLint("ParcelCreator")
class AddressResultReceiver extends ResultReceiver {
    public AddressResultReceiver(Handler handler) {
        super(handler);
    }
    /**     *  Receives data sent from FetchAddressIntentService and updates the UI in MainActivity.     */    @Override    protected void onReceiveResult(int resultCode, Bundle resultData) {

        // Display the address string or an error message sent from the intent service.        mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
        displayAddressOutput();

        // Show a toast message if an address was found.        if (resultCode == Constants.SUCCESS_RESULT) {
            showToast(getString(R.string.address_found));
        }

        // Reset. Enable the Fetch Address button and stop showing the progress bar.        mAddressRequested = false;
        updateUIWidgets();
    }
}

然後  displayAddressOutput()  就是把 mAddressOutput  這個String 設到TextView上面

protected void displayAddressOutput() {
    mLocationAddressTextView.setText(mAddressOutput);
}






沒有留言:

張貼留言