¿Cómo descargar el archivo con el servicio en android?

Quiero descargar un archivo de Internet con servicio. Encontré el código fuente y el código funcionó bien. Pero tengo un problema cuando vuelvo de la app la descarga se detiene o cuando la memoria RAM, también se detiene. Así que quiero encontrar el código de descarga como Google Play, que nunca se detiene cuando la memoria RAM, o el historial de la aplicación. Este es mi código fuente:

public class Temp extends IntentService { public static final int UPDATE_PROGRESS = 8344; private int lastupdate=0; private NotificationManager nm; private Builder mBuilder; public Temp() { super("Temp"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("SERVICE-ONCOMMAND", "onStartCommand"); return START_STICKY; } @Override protected void onHandleIntent(Intent intent) { Log.e("ok","ok"); nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle( "Picture Download dnsadg sadgasjdgashgd asgd asjdg asjgd sajgd s") .setContentText("Download in progress") .setSmallIcon(R.drawable.icon_app).setContentInfo("0%"); mBuilder.setOngoing(true); File root = new File(Environment.getExternalStorageDirectory() + "/aaaa"); String urlToDownload = "http://dl2.mid.az/endir.php?file=uploads/Exclusive/miri_yusif_-_yoxam_men_mp3.mid.az.mp3"; // ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver"); try { URL url = new URL(urlToDownload); 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(new File(root.getPath(), "ok.mp3")); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; progressChange((int)(total * 100) / fileLength); // publishing the progress.... // Bundle resultData = new Bundle(); // resultData.putInt("progress" ,(int) (total * 100 / fileLength)); // receiver.send(UPDATE_PROGRESS, resultData); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } // Bundle resultData = new Bundle(); // resultData.putInt("progress" ,100); // receiver.send(UPDATE_PROGRESS, resultData); } @Override public void onDestroy() { Log.e("DESTROY", "DESTROY"); super.onDestroy(); } void progressChange(int progress){ if (lastupdate != progress) { lastupdate = progress; // not.contentView.setProgressBar(R.id.status_progress, // 100,Integer.valueOf(progress[0]), false); // inform the progress bar of updates in progress // nm.notify(42, not); if (progress < 100) { mBuilder.setProgress(100, Integer.valueOf(progress), false).setContentInfo(progress+"%"); nm.notify(12, mBuilder.build()); Intent i = new Intent("com.russian.apps.TabActivity").putExtra("some_msg",progress+"%"); this.sendBroadcast(i); } else { mBuilder.setContentText("Download complete") // Removes the progress bar .setProgress(0, 0, false).setOngoing(false).setContentInfo("");; nm.notify(12, mBuilder.build()); } } } } 

Usted podría intentar llamar a startForeground. Echa un vistazo a este post para obtener más información.

  • Lectura de múltiples características de un dispositivo BLE de forma sincrónica (método recomendado para Android)
  • ¿Cómo puedo activar automáticamente el inicio automático de mis aplicaciones en el menú de seguridad Xiaomi Mi4i?
  • AlarmManager que repite la alarma que falta al azar cuando el teléfono no está en uso
  • Android en la facturación de la aplicación: Recepción onReceive nunca recibiendo llamadas incluso después de una compra exitosa
  • No se le permite enlazar con el servicio
  • Buenas prácticas para la comunicación asíncrona entre servicios
  • Android bindservice
  • Android: stopService () no llama a onDestroy ()!
  • Cómo obtener el comportamiento del usuario en el teléfono Android (Historial de aplicaciones, Historial de exploraciones, etc.)
  • Android Service preguntas sobre bind / unbind?
  • ASmack como servicio
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.