2011-04-26 4 views
8

Я хочу загрузить файл из Интернета и хранить во внешней памяти. Главное, его нужно загружать в фоновом режиме, например, на рынок, при нажатии на его установку будет загружен файл apk file.if есть идеи, пожалуйста, скажите мнеandroid: файл скачать в фоновом режиме

Спасибо.

ответ

-2

Пожалуйста, find эту ссылку. В нем объясняется, как загрузить файл из Интернета. Вы должны поместить этот код в поток. Он используется для фонового процесса. Вы должны ссылаться на поток для фоновых процессов или использовать AsyncTask, который также используется для фонового процесса.

+3

Ссылка не работает. 404. –

+1

ссылка не работает. пожалуйста, дайте решение здесь –

+0

Я обновил ссылку. –

6

Если ваше приложение использует 2,3, вы можете использовать DownloadManager api, предоставленный под андроид SDK. Иначе вы можете написать свой собственный service для этой цели.

+0

Я могу рассказать мне, как реализовать DownloadManager в версиях 2.1 и 2.2, у меня есть работа с службами, но я не знал, как загрузить файл, если есть какая-либо ссылка, тогда пришлите мне –

+0

DownloadManager доступен только с 2,3 года , SO для более низких версий api использует ссылку, предоставленную Chirag. – mudit

0

, как андроид с открытым исходным кодом, вы можете просто портировать DownloadManager в Android 2.3 с более низкой андроида версии

10

это другой код downloaf файл с помощью задачи Asyc с countinues уведомления

public class DownloadTask extends AsyncTask<Integer, Integer, Void>{ 
    private NotificationHelper mNotificationHelper; 

    private static final String PEFERENCE_FILE = "preference"; 
    private static final String ISDOWNLOADED = "isdownloaded"; 
    SharedPreferences settings; 
    SharedPreferences.Editor editor; 
    Context context; 
    public DownloadTask(Context context){ 
     this.context = context; 
     mNotificationHelper = new NotificationHelper(context); 
    } 

    protected void onPreExecute(){ 
     //Create the notification in the statusbar 
     mNotificationHelper.createNotification(); 
    } 

    @Override 
    protected Void doInBackground(Integer... integers) { 
     //This is where we would do the actual download stuff 
     //for now I'm just going to loop for 10 seconds 
     // publishing progress every second 

     int count; 

     try { 


     URL url = new URL("filename url"); 
     URLConnection connexion = url.openConnection(); 
     connexion.connect(); 

     int lenghtOfFile = connexion.getContentLength(); 
     Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 

     InputStream input = new BufferedInputStream(url.openStream()); 
     //OutputStream output = new FileOutputStream("/sdcard/foldername/temp.zip"); 
     OutputStream output = new FileOutputStream("/sdcard/foldername/himages.zip"); 
     byte data[] = new byte[1024]; 

     long total = 0; 

      while ((count = input.read(data)) != -1) { 
       total += count; 
       //publishProgress(""+(int)((total*100)/lenghtOfFile)); 
       Log.d("%Percentage%",""+(int)((total*100)/lenghtOfFile)); 
       onProgressUpdate((int)((total*100)/lenghtOfFile)); 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
      File file = new File(Environment.getExternalStorageDirectory() 
        + "/foldername/"+"_images.zip"); 
      File path = new File(Environment.getExternalStorageDirectory() 
        + "/foldername"); 
       try { 
         ZipUtil.unzip(file,path); 
         settings = this.context.getSharedPreferences(PEFERENCE_FILE, 0); 
         editor = settings.edit(); 
         editor.putBoolean(ISDOWNLOADED, true); 
         editor.commit(); 

       } catch (IOException e) { 
         Log.d("ZIP UTILL",e.toString()); 
        } 

     } catch (Exception e) {} 


     return null; 
    } 
    protected void onProgressUpdate(Integer... progress) { 
     //This method runs on the UI thread, it receives progress updates 
     //from the background thread and publishes them to the status bar 
     mNotificationHelper.progressUpdate(progress[0]); 
    } 
    protected void onPostExecute(Void result) { 
     //The task is complete, tell the status bar about it 
     HyundaiApplication.serviceState=false; 
     mNotificationHelper.completed(); 
    } 
} 

этого вспомогательный сигнал уведомления

public class NotificationHelper { 
    private Context mContext; 
    private int NOTIFICATION_ID = 1; 
    private Notification mNotification; 
    private NotificationManager mNotificationManager; 
    private PendingIntent mContentIntent; 
    private CharSequence mContentTitle; 
    public NotificationHelper(Context context) 
    { 
     mContext = context; 
    } 

    /** 
    * Put the notification into the status bar 
    */ 
    public void createNotification() { 
     //get the notification manager 
     mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); 

     //create the notification 
     int icon = android.R.drawable.stat_sys_download; 
     CharSequence tickerText = mContext.getString(R.string.download_ticker); //Initial text that appears in the status bar 
     long when = System.currentTimeMillis(); 
     mNotification = new Notification(icon, tickerText, when); 

     //create the content which is shown in the notification pulldown 
     mContentTitle = mContext.getString(R.string.content_title); //Full title of the notification in the pull down 
     CharSequence contentText = "0% complete"; //Text of the notification in the pull down 

     //you have to set a PendingIntent on a notification to tell the system what you want it to do when the notification is selected 
     //I don't want to use this here so I'm just creating a blank one 
     Intent notificationIntent = new Intent(); 
     mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0); 

     //add the additional content and intent to the notification 
     mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); 

     //make this notification appear in the 'Ongoing events' section 
     mNotification.flags = Notification.FLAG_ONGOING_EVENT; 

     //show the notification 
     mNotificationManager.notify(NOTIFICATION_ID, mNotification); 
    } 

    /** 
    * Receives progress updates from the background task and updates the status bar notification appropriately 
    * @param percentageComplete 
    */ 
    public void progressUpdate(int percentageComplete) { 
     //build up the new status message 
     CharSequence contentText = percentageComplete + "% complete"; 
     //publish it to the status bar 
     mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent); 
     mNotificationManager.notify(NOTIFICATION_ID, mNotification); 
    } 

    /** 
    * called when the background task is complete, this removes the notification from the status bar. 
    * We could also use this to add a new ‘task complete’ notification 
    */ 
    public void completed() { 
     //remove the notification from the status bar 
     mNotificationManager.cancel(NOTIFICATION_ID); 
    } 
} 

Спасибо.

+3

Это очень неправильно: 'onProgressUpdate ((int) ((всего * 100)/lenghtOfFile));'. Вы вызываете метод из рабочего потока вместо потока пользовательского интерфейса. Вместо этого используйте 'publishProgress()'. – JohnD

+0

-1 плохой совет, плохая форма, см. Комментарий JohnD's выше. – mikebabcock

Смежные вопросы