我有这种情况:
工作完美,但问题来自于设备没有互联网连接,在这种情况下始终展示进度对话框,当设备没有互联网时我想做的是关闭进度和显示错误信息。
这是我的代码:
showProgessDialog();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("hello");
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
Log.d(Constans.LOG,"1.- datachange connected");
hideProgressDialog();
} else {
Log.d(Constans.LOG,"2.- datachange disconnected");
showProgessDialog();
}
}
@Override
public void onCancelled(DatabaseError error) {
System.err.println("3.- datachange cancelled");
}
});
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(Constans.LOG,"4.- myRef addListenerForSingleValueEvent onDataChange");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(Constans.LOG,"5.- myRef addListenerForSingleValueEvent cancell");
}
});
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(Constans.LOG,"6.- myRef addValueEventListener onDataChange");
String value = dataSnapshot.getValue(String.class);
mAboutMe.setText(value);
}
@Override
public void onCancelled(DatabaseError error) {
Log.d(Constans.LOG,"7.- myRef addValueEventListener error"+error.getDetails());
}
});
正如您所看到的,所有调用的方法在日志行中都有一个数字,当设备具有互联网时,方法调用顺序为:
2,1,6,4
当没有互联网时,只需要调用
2
我无法关闭打开它的进度。
关于使用Firebase框架可以做什么的任何想法?
答案 0 :(得分:1)
您可以使用此类的isConnected方法检查设备的互联网连接。然后在没有互联网连接时关闭进度对话框
public class InternetConnectionDetector
{
private Context context;
public InternetConnectionDetector(Context context)
{
this.context = context;
}
public boolean isConnected()
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//There are changes after apk lollipop while detecting internet connection:
//if user's os newer then lollipop:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for(Network mNetwork : networks)
{
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if(networkInfo.getState().equals(NetworkInfo.State.CONNECTED))
{
return true;
}
}
}
//if user's os older then lollipop:
else
{
//getAllNetworkInfo method work for only before API 19:
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if(info != null)
{
for(NetworkInfo anInfo : info)
{
if(anInfo.getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}