当没有互联网连接时,应用程序崩溃
我正在开发一个用户尝试上传文件到AWS S3的Android项目。开发人员身份验证使用AWS Cognito完成。因此,在此过程是在用户尝试将文件上传到S3之前,用户必须使用AWS Cogntio获取凭证。之后用户上传文件。这个过程发生在用户选择文件的背景,然后单击确定。如果互联网可用,一切都会好起来。否则,应用程序崩溃。 这是代码的一部分。当没有互联网连接时,应用程序崩溃
这里Auth类扩展了AWSAbstractCognitoDeveloperIdentityProvider。
Auth developerProvider = new Auth(
null,
"ap-northeast-1:a871fa5f-2-480d-baa6-b4ed31437244",
Regions.AP_NORTHEAST_1);
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
this.ctx.getApplicationContext(),
developerProvider,
Regions.AP_NORTHEAST_1);
HashMap<String, String> loginsMap = new HashMap<String, String>();
loginsMap.put("login.cool.app", "7386872");
credentialsProvider.setLogins(loginsMap);
credentialsProvider.refresh();
应用在该行
credentialsProvider.refresh();
错误它显示崩溃:
I/AmazonHttpClient: Unable to execute HTTP request: Unable to resolve host "cognito-identity.ap-northeast-1.amazonaws.com": No address associated with hostname
java.net.UnknownHostException: Unable to resolve host "cognito-identity.ap-northeast-1.amazonaws.com": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:427)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
at com.amazonaws.http.UrlHttpClient.writeContentToConnection(UrlHttpClient.java:128)
at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:65)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:353)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:196)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:533)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getCredentialsForIdentity(AmazonCognitoIdentityClient.java:406)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:627)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:553)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:503)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:462)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getIdentityId(CognitoCachingCredentialsProvider.java:413)
at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:620)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:553)
at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:503)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:462)
at com.example.sandesh.filer.UpDown.upload.doInBackground(upload.java:89)
at com.example.sandesh.filer.UpDown.upload.doInBackground(upload.java:27)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
反正有没有尝试抓住它?或任何解决方案,以避免崩溃?
谢谢。
经过很多的斗争,我想到了它。这个问题是由于互联网连接低而脆弱造成的。虽然应用程序连接到互联网,但这不是一个活跃的互联网连接。无法访问。所以我通过检查应用程序是否连接到互联网来解决问题,并通过ping google.com来查找互联网是否可访问。谢谢。
public class internetchek extends AsyncTask<Void,Void,Void> {
public boolean connection;
Context ctx;
public internetchek(Context context){
this.ctx = context;
}
public internetchek(){
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
if(isNetworkAvailable(this.ctx))
{
Log.d("NetworkAvailable","TRUE");
if(connectGoogle())
{
Log.d("GooglePing","TRUE");
connection=true;
}
else
{
Log.d("GooglePing","FALSE");
connection=false;
}
}
else {
connection=false;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.d("GooglePing","IOEXCEPTION");
e.printStackTrace();
return false;
}
}
}
有时你可能会被重定向。更好地使用'return(httpURLConnection.getResponseCode()> = 200 && httpURLConnection.getResponseCode() CodeWalker
一旦我在我的应用程序中实施了检查,看看是否有任何互联网连接。你可以看看这个,并决定是否要实现这一点。
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context cont){
this.context = cont;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.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;
}
}
您可以在OnCreate
方法来初始化这个类的一个对象。
最后在你上传文件之前调用这个类的方法。
Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
//upload files here
}
希望这会有所帮助。
你可以用try/catch来包围你的代码。
try {
//your code
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "Error connecting to network.", Toast.LENGTH_SHORT).show();
}
但是可以通过做你运行它的权利之前,网络检查可以防止你的代码的运行不必要的。
http://developer.android.com/reference/android/net/NetworkInfo.html#isConnected%28%29 – F43nd1r
你为什么不先检查互联网连接? –
栈跟踪不是来自崩溃,而是INFO级别的日志消息。系统使用ERROR日志级别记录崩溃。 – laalto