2017-09-18 5 views
-2

この機能を実行すると、接続とファイルをダウンロードしてアプリをクラッシュさせたいと思っています。私はこの関数をデバッグしています。墜落した エラー:スレッドまたはインターネット用のAndroidエラー

FATAL EXCEPTION: main 
Process: com.idegostaran.user.testqrsavedata, PID: 8500 
android.os.NetworkOnMainThreadException 
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273) 

これを修正するにはどうすればよいですか?

public Bitmap download(String path){ 


    try { 
     URL url=new URL(path); 
     HttpURLConnection connection=(HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 

     InputStream input=connection.getInputStream(); 
     Bitmap bitmap= BitmapFactory.decodeStream(input); 


     String root= Environment.getExternalStorageDirectory().toString(); 
     String fileName="test.jpg"; 
     File file = new File(root,fileName); 
     if (file.exists()){ 
      file.delete(); 
     } 
     FileOutputStream out=new FileOutputStream(file); 
     bitmap.compress(Bitmap.CompressFormat.JPEG,90,out); 
     out.flush(); 
     out.close(); 

     return bitmap; 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 
+0

答えは[this](https://stackoverflow.com/a/19941745/7413139)のリンクを参照できます – vaibhav

答えて

0

以下を使用してください。

Runnable runnable; 
Handler handler; 

newHandler = new Handler(); 
runnable = new Runnable() { 
@Override 
public void run() { 
    try { 
     //Put your code here 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
}; 
handler.post(runnable); 
0

あなたのonCreateメソッドでこれらの行を書く:

if (android.os.Build.VERSION.SDK_INT > 8) 
{ 
     StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(threadPolicy); 
} 

私は、これはあなたを助けることを願っています。

関連する問題