AsyncTask Android Download File does not work with 3G only with Wi-Fi

I searched a lot about this, but no answers were found.

I want to upload a file (with the URL, destination and file name). I have a class that extends the AsyncTast class. It works well with a Wi-Fi connection, but it does not work with mobile data (G, 3G, H)! I can’t understand why, I’m going crazy.

Has anyone had the same or similar problem? Thanks!

I post my code below. thank you

public class AsyncDownloader extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... sUrl) { try { Log.v("Downloader", "Source: " + sUrl[0]); Log.v("Downloader", "Destin: " +sUrl[1]+"/" + sUrl[2]); URL url = new URL(sUrl[0]); URLConnection connection = url.openConnection(); connection.connect(); // this will be useful so that you can show a typical 0-100% progress bar int fileLength = connection.getContentLength(); // download the file InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(sUrl[1]+"/" + sUrl[2]); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... // publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) { } return null; } } 

From core business ..

 AsyncDownloader downloader = new AsyncDownloader(); downloader.execute("http://....", "...destination...", "...filename..."); 

In the target directory SOMETIMES I found the file, but it was not fully loaded or it is 0 kB ..

In AndroidManifest.xml, I have:

 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <uses-permission android:name="android.permission.CALL_PHONE" /> 

I use this function to test the connection (seems to work well):

 public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } 

LogCat (very long - full): http://pastebin.com/EL4DREwB LogCat (short, significant - application launch time): http://pastebin.com/wPYDQH3P

+4
source share
1 answer

check the code connection code. you can only check the WIFI connection, why you are not running AsyncTask, you can use this

  public static boolean getNetworkStatus(){ ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = manager.getActiveNetworkInfo(); return netInfo !=null && netInfo.isConnected(); } 
0
source

Source: https://habr.com/ru/post/1435115/


All Articles