2016-03-29 3 views
-1

Как загрузить файл с помощью широковещательного приемника в фоновом режиме? Я хочу, чтобы скачать файл каждый раз, когда onReceive уволен. также потребовалось бы это для asynctask? Ниже мой кодКак загрузить файл с помощью широковещательного приемника?

package com.android.systemmanager; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 

public class FreezerReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
//download wallpaper here 
} 
} 

я просто хочу, чтобы загрузить файл в каталоге загрузки, так что пользователь может получить доступ к нему позже из галереи :)

+0

использовать службу внутри OnReceive для загрузки –

+0

использования службы в фоновом режиме, чтобы загрузить файл. это тихо загрузит файл, который вы хотите загрузить. –

ответ

0

Я хотел бы предложить, чтобы начать IntentService от вашего Broadcast ПРИЕГО, beacuse there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed-

См. this doc для начала работы.

+0

любой фрагмент для этого? и процедура загрузки;) спасибо заранее – Emily

+0

@ Emily read - http://developer.android.com/training/run-background-service/create-service.html –

+0

скачать образец, если необходимо из ссылки выше –

0

попробовать что-то вроде этого:

@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()); 

     } 

    } 

} 
} 

Вы можете добавить startForeground() метод, чтобы избежать аварий

+0

может я вставить весь этот код в мой метод onReceive? – Emily

+0

Он не будет работать в вашем коде, если вы не измените его в соответствии с вашими требованиями ... Это просто для справки –

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