用于隔离代码的隐藏片段

时间:2017-03-24 08:49:03

标签: java android android-fragments

我的问题是如何自定义将活动所需的某些功能分离为隐藏片段,在本例中为位置服务。

我最初的想法是将与位置服务相关的样板回调传递到单独的普通Java实用程序类中,并且只在活动中保留onLocationChanged的侦听器。这样会更清洁 问题是这导致循环依赖,因为pojo需要对某些调用的活动上下文的引用,并且Activity将具有对实用程序类的引用,从而导致循环依赖,这导致紧密耦合。

因此,我的想法是创建一个隐藏的片段并将代码存储在那里;这样可以保持主要活动中的代码清洁 通常的方法是什么?

我使用的当前代码:

public class HomeActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener{
    private static final String TAG = "HOME_ACTIVITY"; // Logging

    private GoogleApiClient     mGoogleApiClient;
    private Location            mLocation;
    private LocationManager     mLocationManager;
    private LocationRequest     mLocationRequest;
    private com.google.android.gms.location.LocationListener listener;

    private double mLatCurLoc;
    private double mLngCurLoc;

    private float  MIN_DISTANCE = 200.0f;
    private long   UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
    private long   FASTEST_INTERVAL = 2000; /* 2 sec */

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

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

        mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

    }

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

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    public void onConnected(Bundle bundle) {
        // Android Studio complains that we should check the permissions before getting last location
        // However, we have already checked permissions in the previous activity
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        startLocationUpdates();
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if(mLocation == null){
            startLocationUpdates();
        }
        if (mLocation != null) {

        } else {
            Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setSmallestDisplacement(MIN_DISTANCE)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        mLatCurLoc = location.getLatitude();
        mLngCurLoc = location.getLongitude();
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        Log.i("LOCATION_CHANGED", msg);
    }


}

1 个答案:

答案 0 :(得分:0)

我认为这是OOP中的继承之美。您只需要一项活动来处理位置服务,并使您想要处理位置的其他活动延伸,例如LocationAwareActivity。当其中一个活动对您刚刚更改父类的位置不感兴趣时​​,反之亦然,当您的某个活动希望了解位置时 - 它将扩展LocationAwareActivity