【发布时间】:2016-05-26 17:25:44
【问题描述】:
在这堂课中:
public class Presence implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener
我有以下构造函数:
private Presence(Context context)
{
this.context = context;
gApiClient = new GoogleApiClient.Builder(context, this, this)
.addApi(LocationServices.API)
.build();
if (!gApiClient.isConnecting() && !gApiClient.isConnected())
{
gApiClient.connect();
}
} // of constructor()
我用它来返回一个Singleton 实例:
public static synchronized Presence getInstance(Context context)
{
if (presenceSingleton == null)
presenceSingleton = new Presence(context);
return presenceSingleton;
}
onConnected() 看起来像这样:
@Override
public void onConnected(Bundle connectionHint)
{
Log.e(LOG_TAG, "In onConnected(), gApiClient.isConnected(): " +
gApiClient.isConnected());
createLocationRequest();
getLocation();
getSubLocality();
} // of onConnected()
基于用户可以在应用程序中进行的设置,我调用以下方法将应用程序置于所谓的自动驾驶模式,开始跟踪用户的位置:
public void startLocationUpdates()
{
// Prints 'false' in the logs:
Log.e(LOG_TAG, "In startLocationUpdates(), gApiClient.isConnected(): " + gApiClient.isConnected());
Intent locationChangeIntent = new Intent(context, LocationTracker.class);
pendingIntent = PendingIntent.getService(context, 188, locationChangeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Crash points to the following line:
LocationServices.FusedLocationApi.requestLocationUpdates(gApiClient, locationRequest, pendingIntent);
} // of startLocationUpdates()
在主要活动中,我在onCreate()中创建了上述类的一个实例:
public class MainClass extends AppCompatActivity implements
OnSharedPreferenceChangeListener
{
....
....
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getAppSettings();
presence = Presence.getInstance(getApplicationContext());
....
....
startApp();
....
}
private void startApp()
{
if (pref_autoPilot)
presence.startLocationUpdates();
}
....
....
....
} // of class MainClass
当用户设置自动驾驶偏好时,应用程序崩溃并出现以下异常:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
在上述方法startLocationUpdates()指示的行处。
我阅读了很多答案,但无法找到解决此问题的方法。你能指出我做错了什么吗?是不是Presence类应该在AppCompatActivity或FragmentActivity或类似的,不能像这里那样独立?请帮我解决这个烦人的问题。
提前非常感谢!
【问题讨论】:
-
位置更新方法有两种调用方式。 1.如果您没有获得定位,那么您必须调用位置更新。 2. 如果你想要更新,那么在 public void onConnected(Bundle connectionHint) 方法中调用该方法。
-
感谢@Kedi!你的意思是我把
LocationServices.FusedLocationApi.requestLocationUpdates(gApiClient, locationRequest, pendingIntent);从startLocationUpdates()移到onConnected()?这不会总是让应用程序处于自动驾驶模式吗? -
你应该调用presence.startLocationUpdates();此方法来自 onConnected() 方法。并检查您的位置是否为空,然后它会调用。试一次
-
@Kedi,做到了,异常消失了。万分感谢!如果你能给出答案,我会接受。
标签: java android google-api-client