gpt4 book ai didi

java - 获取 Java 类内部的上下文

转载 作者:行者123 更新时间:2023-12-02 04:37:47 26 4
gpt4 key购买 nike

我创建了以下类

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 编程初学者

最佳答案

定义全局变量:

 Context context = null;

将构造函数更改为:

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

现在正在调用 Activity :

  CurrentGeolocation obj = new CurrentGeolocation(this);

或 fragment :

 CurrentGeolocation obj = new CurrentGeolocation(getActivity());

关于java - 获取 Java 类内部的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com