Java 如何处理没有互联网和失去连接的 Android?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19050444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle with no Internet and lost connection in Android?
提问by Mansour Fahad
I have an application that needs to connect to the Internet to perform some actions but when no Internet available it will crash. I read that I need to use try catch bracket in case no Internet. I tried to use it as you can see in AsyncTask but it doesn't work. I don't know why. The app crashes. How to deal with try catch where to put it in my code?
我有一个应用程序需要连接到 Internet 来执行某些操作,但是当没有可用的 Internet 时它会崩溃。我读到我需要在没有互联网的情况下使用 try catch 支架。我尝试像您在 AsyncTask 中看到的那样使用它,但它不起作用。我不知道为什么。应用程序崩溃。如何处理 try catch 将它放在我的代码中的什么位置?
One more thing what about if the app lost Internet connection while process is going on. How supposed I to deal with this thing so my app doesn't crash. Thank you very much.
还有一件事,如果应用程序在进程进行时失去了 Internet 连接怎么办。我应该如何处理这件事,以免我的应用程序崩溃。非常感谢。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
lv = (ListView) findViewById(R.id.mybookslistview);
new connectToServer().execute();
}
class connectToServer extends AsyncTask<Void, Void, Void>{
CustomListViewAdapter adapter;
HttpResponse response;
@Override
protected Void doInBackground(Void... params) {
ids_list.clear();
names_list.clear();
writers_list.clear();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair(word, connectionPurpose));
try {
post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
response = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
sb = new StringBuffer();
String tempVar = "";
while((tempVar = br.readLine()) != null){
sb.append(tempVar);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Get data from stringbuffer and put it in array list
if(!sb.toString().trim().contentEquals("null")){
content_array = sb.toString().split(",");
for(int s = 0; s < content_array.length; s++){
if(content_array[s].contains("-")){
String temp[] = content_array[s].split("-");
ids_list.add(temp[0].trim());
names_list.add(temp[1].trim());
writers_list.add(temp[2].trim());
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(!mWifi.isConnected()){
adb = new AlertDialog.Builder(Home.this);
adb.setMessage("?? ???? ??????. ?? ?????? ???????? ?? ???? ??? ????.");
adb.setPositiveButton("???? ?????", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
new connectToServer().execute();
}
});
adb.setNegativeButton("????? ???????", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
//It shows dialog if no connection
adb.create().show();
}else{
list = new ArrayList<Home.ListViewItem>();
for(x = 0; x < ids_list.size(); x++){
list.add(new ListViewItem(){{bookName = names_list.get(x); writerName = writers_list.get(x);}});
}
adapter = new CustomListViewAdapter(Home.this, list);
lv.setAdapter(adapter);
if(sb.toString().trim().contentEquals("null")){
Toast.makeText(Home.this, "?? ???? ?????.", Toast.LENGTH_LONG).show();
}
}
This is my logcat:
这是我的日志:
java.net.UnknownHostException: Unable to resolve host "globalmall.ca": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:1)
at android.os.AsyncTask.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
... 18 more
Caused by: libcore.io.ErrnoException: getaddrinfo failed: ENETUNREACH (Network is unreachable)
... 21 more
threadid=13: thread exiting with uncaught exception (group=0x40e582a0)
采纳答案by Vikalp Patel
You can either create method
or some class may be where you can instantiate method as static
.
您可以创建method
或某个类可以将方法实例化为static
.
Here is a method named isConnectedToInternet()
which checks whether internet is connected or not. Return boolean on the basis of connection back to the calling function.
这是一种名为isConnectedToInternet()
检查互联网是否已连接的方法。在连接回调用函数的基础上返回布尔值。
Snippet:
片段:
public boolean isConnectedToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
You can decide on the basis of return value of isConnectedToInternet()
whether to execute AysncTask
or Throw some pop up. Here i've been added user to brought in his Data Settings
.
您可以根据返回值来isConnectedToInternet()
决定是执行AysncTask
还是抛出一些弹出。在这里,我已添加用户以引入他的Data Settings
.
Something like these:
像这样的东西:
if(isConnectedToInternet())
{
// Run AsyncTask
}
else
{
// Here I've been added intent to open up data settings
Intent intent=new Intent(Settings.ACTION_MAIN);
ComponentName cName = new ComponentName("com.android.phone","com.android.phone.NetworkSetting");
intent.setComponent(cName);
}
As you mentioned what if you looses connection in between. You can check the status code as per the reponse of httpclient and pop up relevant information to user.
You can integrate these snippet under AysncTask
.
正如您所提到的,如果您之间失去联系会怎样。您可以根据httpclient的响应查看状态码,并弹出相关信息给用户。您可以将这些代码片段集成到AysncTask
.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
response = httpclient.execute(httpget);
int code = response.getStatusLine().getStatusCode();
回答by Tassos Bassoukos
Interesting. You have in your stack trace these lines:
有趣的。您在堆栈中跟踪这些行:
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
Which mean that the offending line is
这意味着违规行是
response = client.execute(post);
Which is different from the line that you mentioned. Verify the stack trace & the line that it mentions. Also, see that if you fix it by catching Exception
. If you don't, then you have a bigger problem, because UnknownHostException
is a subclass of IOException
, which you already catch.
这与您提到的线路不同。验证堆栈跟踪和它提到的行。另外,如果您通过捕获Exception
. 如果你不这样做,那么你有一个更大的问题,因为UnknownHostException
是 的一个子类IOException
,你已经抓住了。
回答by mananjani
public class CheckNetClass {
public static Boolean checknetwork(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option, you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
}
Use this class to check internet availability like:
使用此类检查互联网可用性,例如:
if (CheckNetClass.checknetwork(getApplicationContext()))
{
new GetCounterTask().execute();
}
else
{
Toast.makeText(getApplicationContext(),"Sorry,no internet connectivty",1).show();
}
Hope this helps..
希望这可以帮助..