警报对话框冻结了我的应用 [英] Alert dialog freeze my app
问题描述
这里有代码检查Internet连接,然后如果isconnected为false,则在allert对话框中显示一条消息.问题是,如果isconnected为true,并且(我尝试放置if(isconnected)子句,而不是if(!isconnected)),每个方法都可以工作.但是,如果我在VM执行show()每次冻结时都关闭了手机上的每个网络.为什么?感谢所有人:
Here there is the code that check the internet connection and then if the isconnected is false show a message in a allert dialog. The problem is that if isconnected is true and (i tried to put if(isconnected) clause instead if(!isconnected)) every works. But if i put off every network on my phone when VM execute show() every freeze. Why? Thanks to all:
final AlertDialog.Builder dialog= new AlertDialog.Builder(this);
((Button)findViewById(R.id.listabutton)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTask asyncTask= new AsyncTask() {
boolean isconnected=true;
@Override
protected Object doInBackground(Object[] params) {
ConnectivityManager conMgr = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
isconnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
Log.i("StateNet",isconnected+"");
return null;
}
@Override
protected void onPostExecute(Object o) {
if(!isconnected){
dialog.setMessage("Controlla la tua conessione a internet")
.setTitle("Ops problemino con internet")
.setPositiveButton("Ok", ok)
.show();
}
super.onPostExecute(o);
}
};
推荐答案
您不需要AsyncTask来检查Internet连接,因此请保持简单.
You do not need AsyncTask to check the internet connection, so please keep it simple.
我认为您的onClick方法应如下所示:
I think that your onClick method should looks like this:
@Override
public void onClick(View v) {
if (isConnectionAvailable(context)) {
// connected
} else {
// not connected
}
};
public static boolean isConnectionAvailable(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}
不要忘记清单中的ACCESS_NETWORK_STATE和INTERNET权限.
Do not forget the ACCESS_NETWORK_STATE and INTERNET permissions in your Manifest.
这篇关于警报对话框冻结了我的应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!