Получить контекст внутри класса Java

Я создал следующий класс

package com.salvo.weather.android.geolocation;

import android.location.Location;
import android.os.Bundle;


import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;
import com.salvo.weather.android.entity.CurrentGeolocationEntity;

/**
 * Created by mazzy on 30/05/15.
 */
public class CurrentGeolocation implements ConnectionCallbacks, OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;

    private CurrentGeolocationEntity mCurrentGeolocationEntity;

    public CurrentGeolocation() {
        buildGoogleApiClient();
        this.mCurrentGeolocationEntity = new CurrentGeolocationEntity();
    }

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

    public GoogleApiClient getmGoogleApiClient() {
        return mGoogleApiClient;
    }

    @Override
    public void onConnected(Bundle bundle) {
        this.mCurrentGeolocationEntity.setmLastLocation(LocationServices
                .FusedLocationApi
                .getLastLocation(this.mGoogleApiClient));

        Location mLastLocation = this.mCurrentGeolocationEntity.getmLastLocation();

        if (mLastLocation != null) {
            this.mCurrentGeolocationEntity.setmLongitude(mLastLocation.getLongitude());
            this.mCurrentGeolocationEntity.setmLatitude(mLastLocation.getLatitude());
        } else {
            // TODO: Add toast
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
    }
}

и мне нужно получить контекст, чтобы передать его внутри GoogleApiClient. О чем вы говорите? Это хороший способ? Я новичок в программировании для Android


person Mazzy    schedule 30.05.2015    source источник
comment
Хорошо, я только что нашел ответ stackoverflow.com/questions/17917968/   -  person Mazzy    schedule 30.05.2015
comment
То, что я делаю, считается хорошим шаблоном проектирования?   -  person Mazzy    schedule 30.05.2015


Ответы (1)


Определите глобальную переменную:

 Context context = null;

Измените конструктор на:

public CurrentGeolocation(Context context) { 
        buildGoogleApiClient(); 
        this.context = context;
        this.mCurrentGeolocationEntity = new CurrentGeolocationEntity();
    } 

Теперь при вызове Activity :

  CurrentGeolocation obj = new CurrentGeolocation(this);

или Фрагмент:

 CurrentGeolocation obj = new CurrentGeolocation(getActivity());
person Karan    schedule 30.05.2015
comment
только один! Передача контекста Activity через конструктор настоятельно рекомендуется и является хорошей практикой. Примите этот ответ, если он работает для вас. - person Karan; 30.05.2015
comment
Хорошая практика, пока ваш класс создается из вашей Activity и умирает вместе с ним, когда Activity уничтожается. - person ci_; 30.05.2015