我想在android中关闭我的应用程序时创建一个不停止的线程

时间:2015-01-25 16:18:57

标签: android service download android-download-manager

我想在android中创建一个下载管理器,这样如果我的应用程序被最小化或关闭或被用户杀死,则再次下载以继续。 这个代码,我使用它,当后退按钮按下,在后台运行,但当用户杀死应用程序时,下载停止! 有人有提议解决这个问题吗?

我在MainActivity上使用此代码:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

  private TextView textView;
  Thread thread;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.status);
  }

  public void onClick(View view) {

      Thread thread = new Thread(new Runnable() {
            public void run()
            {
                try {
                    Intent intent = new Intent(MainActivity.this, DownloadService.class);
                    intent.putExtra("filename", "index.mp3");
                    intent.putExtra("urlpath",
                            "http://s1.mihandownload.com/2015/saeedahmadi/Technology-mihandownload-com.rar");
                    startService(intent);
                    textView.setText("Service started");
                } catch(Exception v) {
                    System.out.println(v);
                }
            }});  
      thread.start();
  }
} 

和我的DownloadService上的代码

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import android.widget.ProgressBar;

public class DownloadService extends IntentService {

    ProgressBar progressBar;
    NotificationManager mNotifyManager;
    Builder mBuilder;
    int id = 1;

    HttpURLConnection connection;
    String DESTINATION_PATH;
    Activity myActivity;
    float val=0.0f;

  public DownloadService() {
    super("DownloadService");
  }


  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
  protected void onHandleIntent(Intent intent) {

      mNotifyManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      mBuilder = new NotificationCompat.Builder(this);
      mBuilder.setContentTitle("Picture Download")
            .setContentText("Download in progress")
            .setSmallIcon(R.drawable.ic_launcher);
      mBuilder.setOngoing(true);
      mBuilder.setProgress(100, 0, false);
      mNotifyManager.notify(id, mBuilder.build());

      String URL = intent.getStringExtra("urlpath");
      String DESTINATION_PATH = intent.getStringExtra("filename");

      AsyncDownload asyncCallWS = new AsyncDownload();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            asyncCallWS.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, URL,DESTINATION_PATH);
        else
            asyncCallWS.execute(URL,DESTINATION_PATH);      

  }

    private class AsyncDownload extends AsyncTask<String, Void, Void> {
        String fileName="";
        @Override
        protected Void doInBackground(String... params) {
            fileName = params[1];
            downloadFile(params[0], getFilename(params[1]));
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i("AsyncDownload", "onPostExecute");
            Log.i("AsyncDownload", fileName);

        }

    }

    private void downloadFile(String myUrl, String DESTINATION_PATH) {
        try{
            URL url = new URL(myUrl);
            connection = (HttpURLConnection) url.openConnection();
            int downloaded = 0;
            File file=new File(DESTINATION_PATH);
            if(file.exists()){
                if(file.length()!=0){
                     downloaded = (int) file.length();
                }
            }
            connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
            connection.setDoInput(true);
            connection.setDoOutput(true);

            BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
            FileOutputStream fos;
            if(downloaded==0){
                fos = new FileOutputStream(DESTINATION_PATH);
            }else{
                fos = new FileOutputStream(DESTINATION_PATH,true);
            }
            setProgres(((file.length()*1.0f)/connection.getContentLength())*100);
            BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
            byte[] data = new byte[1024];
            int x = 0;
            while ((x = in.read(data, 0, 1024)) >= 0) {
                bout.write(data, 0, x);
                downloaded += x;
                Log.e("file Name", DESTINATION_PATH);
                setProgres(((file.length()*1.0f)/connection.getContentLength())*100);
            }
            bout.close();
            fos.close();
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }



    private String getFilename(String fileName) {
      String filepath = Environment.getExternalStorageDirectory()+"/test/"+fileName;
      return filepath;
    }

    private void setProgres(final float value) {
        Log.e("",String.valueOf(value));
        mBuilder.setProgress(100, (int)value, false);
        mNotifyManager.notify(id, mBuilder.build());

    }

} 

1 个答案:

答案 0 :(得分:0)

您必须创建前台服务。这意味着用户知道服务,并且当内存不足时,它不是系统杀死的候选者。要启动forground服务,您必须致电startForeground(ONGOING_NOTIFICATION_ID, notification);

您可以在Android开发者网站here以及here

上阅读更多内容