下载服务并更新其他活动

时间:2015-03-28 04:45:00

标签: android android-intent android-service

我有三项活动:MainActivity, DownloadServiceTest, ViewDetailDownload。现在,我想使用Service(IntentService)下载文件。

肉体:

MainActivity有按钮。当我点击 button_1 时,启动服务(DownloadServiceTestextends IntentSerive)执行下载,我想点击button_2时会启动ViewDetailDownload并更新进度。

但是,当我开始ViewDetailDownload时,我无法从DownloadServiceTest

接收数据(下载百分比,速度)

我的代码在这里。

类MainActivity:

public class MainActivity extends Activity implements OnClickListener {
    private final String LINK_MP3 = "http://data.chiasenhac.com/downloads/1471/5/1470643-c6ef1a26/320/Vo%20Hinh%20Trong%20Tim%20Em%20-%20Mr%20Siro%20%5BMP3%20320kbps%5D.mp3";
    Activity activity;
    Button btnDownload_1, btnDownload_2, btnDownload_3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_control);
        activity = MainActivity.this;
        btnDownload_1 = (Button) findViewById(R.id.btn_startdownload_1);
        btnDownload_2 = (Button) findViewById(R.id.btn_startdownload_2);
        btnDownload_3 = (Button) findViewById(R.id.btn_startdownload_3);
        btnDownload_1.setOnClickListener(this);
        btnDownload_2.setOnClickListener(this);
        btnDownload_3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_startdownload_1) {
            Intent intent = new Intent(activity, DownloadServiceTest.class);
            intent.putExtra(DownloadServiceTest.REQUEST_STRING, LINK_MP3);
            startService(intent);
        }
        if (v.getId() == R.id.btn_startdownload_2) {
             Intent intent = new Intent(MainActivity.this,
             ViewDetailDownload.class);
             startActivity(intent);
        }
    }


}

class DownloadServiceTest:

public class DownloadServiceTest extends IntentService {

    public static final String REQUEST_STRING = "REQUEST_LINK";
    public static final String PROGRESS_UPDATE_ACTION = DownloadServiceTest.class
            .getName() + ".progress_update";
    private LocalBroadcastManager mLocalBroadcastManager;
    private String mUrl_mp3;

    public DownloadServiceTest(String name) {
        super(name);
    }

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

    @Override
    public void onCreate() {
        mLocalBroadcastManager = LocalBroadcastManager
                .getInstance(DownloadServiceTest.this);
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        mUrl_mp3 = intent.getStringExtra(REQUEST_STRING);
        DownloadTask task = new DownloadTask();
        if (mUrl_mp3 != null) {
            task.execute(mUrl_mp3);
        }
    }

    private void onProgressUpdateReceiver(int progress, int speed) {
        Intent intent = new Intent();
        intent.setAction(PROGRESS_UPDATE_ACTION);
        intent.putExtra("progress", progress);
        intent.putExtra("speed", speed);
        Log.i("", "abc onProgressUpdateReceiver progress "+progress);
        Log.i("", "abc onProgressUpdateReceiver speed "+speed);
        mLocalBroadcastManager.sendBroadcast(intent);
    }

    private class DownloadTask extends AsyncTask<String, Void, Void> {

        String filename;
        int mProgress;
        int mSpeed;
        private int checkExist;
        File SDCardRoot;
        private FileOutputStream fileOut;
        private InputStream fileIn;
        File file;

        @Override
        protected void onPreExecute() {
            filename = mUrl_mp3.substring(mUrl_mp3.lastIndexOf("/") + 1);
            try {
                filename = URLDecoder.decode(filename, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) {
            int contentLengh = 0;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                if (HttpURLConnection.HTTP_OK == urlConnection
                        .getResponseCode()) {
                    contentLengh = urlConnection.getContentLength();
                    Log.i("", "abc " + contentLengh);
                    fileIn = urlConnection.getInputStream();
                    SDCardRoot = Environment.getExternalStorageDirectory();
                    file = new File(Environment.getExternalStorageDirectory()
                            + "/Blog Radio");
                    boolean success = true;
                    if (!file.exists()) {
                        success = file.mkdir();
                    }
                    String getTypeFile = filename.substring(filename
                            .indexOf("."));
                    if (success) {
                        file = new File(SDCardRoot.getAbsolutePath()
                                + "/Blog Radio/" + filename);
                        if (file.exists()) {
                            checkExist++;
                            String PATH = Environment
                                    .getExternalStorageDirectory()
                                    + "/Blog Radio/"
                                    + filename.replace(filename
                                            .substring(filename.indexOf(".")),
                                            "")
                                    + "_"
                                    + checkExist
                                    + getTypeFile;
                            file = new File(PATH);
                        }
                    } else {
                        file = new File(SDCardRoot.getAbsolutePath()
                                + "/Blog Radio/" + filename);
                        if (file.exists()) {
                            checkExist++;
                            String PATH = Environment
                                    .getExternalStorageDirectory()
                                    + "/Blog Radio/"
                                    + filename.replace(filename
                                            .substring(filename.indexOf(".")),
                                            "")
                                    + "_"
                                    + checkExist
                                    + getTypeFile;
                            file = new File(PATH);
                        }
                    }
                    fileOut = new FileOutputStream(file);
                    int downloadSize = 0;
                    byte[] buffer = new byte[8192];
                    long tempTotal = 0;
                    long startTime = System.currentTimeMillis();
                    int bufferLengh = 0;
                    while ((bufferLengh = fileIn.read(buffer)) != -1) {
                        long interval = System.currentTimeMillis() - startTime;
                        if (isCancelled()) {
                            fileIn.close();
                        }
                        if (contentLengh > 0) {
                            downloadSize += bufferLengh;
                            tempTotal += bufferLengh;
                            mProgress = (int) ((downloadSize * 100L) / contentLengh);
                            if (interval >= 1000) {
                                Log.i("now = ", String.valueOf(System
                                        .currentTimeMillis()));
                                Log.i("last = ", String.valueOf(startTime));
                                Log.i("currentDump = ",
                                        String.valueOf(tempTotal));
                                mSpeed = (int) (tempTotal * 1000 / interval / 1024);
                                startTime = System.currentTimeMillis();
                                tempTotal = 0;
                            }
                            fileOut.write(buffer, 0, bufferLengh);
                            onProgressUpdateReceiver(mProgress, mSpeed);
                        }
                    }
                    fileOut.flush();
                    fileOut.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;

        }

    }
}

类ViewDetailDownload:

    public class ViewDetailDownload extends Activity {

    TextView tv_Title, tv_Info;
    ProgressBar progressBar;
    ImageView img;
    MyRequestReceiver receiver;
    IntentFilter intentToReceiveFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_service_layout);
        img = (ImageView) findViewById(R.id.img);
        tv_Title = (TextView) findViewById(R.id.title);
        tv_Info = (TextView) findViewById(R.id.info);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        intentToReceiveFilter = new IntentFilter();
        intentToReceiveFilter
        .addAction(DownloadServiceTest.PROGRESS_UPDATE_ACTION);
        receiver = new MyRequestReceiver();
    }

    @Override
    protected void onResume() {
        registerReceiver();
        super.onResume();
    }

    private void registerReceiver() {
        this.registerReceiver(receiver, intentToReceiveFilter);
    }

    @Override
    protected void onPause() {
        unregisterReceiver();
        super.onPause();
    }


    protected void onProgressUpdate(int progress, int speed) {
        progressBar.setProgress(progress);
        tv_Info.setText(speed);
    }

    protected void onProgressUpdateOneShot(int progresses, int speeds) {
        int progress = progresses;
        int speed = speeds;
        onProgressUpdate(progress, speed);
    }

    private void unregisterReceiver() {
        this.unregisterReceiver(receiver);

    }

    public class MyRequestReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    DownloadServiceTest.PROGRESS_UPDATE_ACTION)) {
                int progresses = intent.getIntExtra("progress", -1);
                int speeds = intent.getIntExtra("speed", -1);
                Log.i("", "abc progresses onReceive" + progresses);
                Log.i("", "abc speeds onReceive" + speeds);
                onProgressUpdateOneShot(progresses, speeds);
            }
        }
    }

}

我需要帮助! 如果你知道......请举例。 谢谢大家

1 个答案:

答案 0 :(得分:1)

在onCreate()方法的DownloadServiceTest.java中添加。

Intent iin= getIntent();
   Bundle b = iin.getExtras();
   if(b!=null)
   {
       String mname =(String) b.getString("LINK_MP3");

   }

现在,您可以在DownloadServiceTest

中的任何位置使用此字符串mname