android - 如何在android中使用服务下载文件?

标签 android service download intentservice

我想通过服务从 Internet 下载文件。我找到了源代码并且代码运行良好。但是当我从应用程序返回时,下载停止或者当我清除 RAM 时,它也停止了,我遇到了一个问题。所以我想找到下载代码,例如 Google Play,它在清除 RAM 或应用程序历史记录时永远不会停止。这是我的源代码:

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

        }

    }

}
}

最佳答案

您可以尝试调用 startForeground。查看this post获取更多信息。

关于android - 如何在android中使用服务下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864614/

相关文章:

android - 如何根据android中的 Material 设计制作Cardview?

android - 条形码扫描仪 - Cordova 插件

networking - 无法通过指定端点的 Kubernetes 服务访问服务

ios - 使用 Dropbox iOS SDK 下载照片

ios - iPhone下载指示器不显示

android - 单击 EditText 时 View 不会一直向上滚动

android - 使用 Gimbal sdk 编程我的 android 应用程序未检测到 gimbal beacon

Linux -> 自动删除超过 2 天的文件

c# - 控制台应用程序到服务

python - BeautifulSoup是否支持自定义html标签?