我在文档中读到connect方法“立即返回,并在后台连接到服务”。但我认为情况并非如此,至少对我而言。
我甚至为connect方法创建了一个单独的线程,但是每次调用UI时,仍会冻结onStart方法(我正在尝试连接)。
注意:只有在没有互联网连接时才会发生这种情况。
那么我该如何解决这个问题呢?谢谢
答案 0 :(得分:1)
如上所述检查您是否有互联网连接.. !!
private void CheckConnection() {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
answer="You are connected to a WiFi Network";
System.out.println(answer);
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
answer="You are connected to a Mobile Network";
}
else
answer = "No internet Connectivity";
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();
}
在清单文件中添加
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
如果在活动中
@Override
protected void onStart() {
super.onStart();
if (!googleApiClient.isConnecting() || !googleApiClient.isConnected()) {
googleApiClient.connect();
}
}
和 Oncreate function
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
服务类中的在 Oncreate 上执行上述操作。