利用service下载图片&发送进度notification

  • 不能在service中直接下载,需要开启子线程
  • 在子线程中下载的信息需要传递出来,包括进度,下载完毕什么的,需要一个handler去传递

代码示意:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class ImgService extends Service {
    private NotificationCompat.Builder builder;
    private NotificationManager manager;

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case -2:
                Toast.makeText(getApplicationContext(), "-----网络状态异常", 0).show();
                break;
            case -1:
                Toast.makeText(getApplicationContext(), "-----sd卡异常", 0).show();
                break;
            case 0:

                Toast.makeText(getApplicationContext(), "-----下载成功", 0).show();
                stopSelf(); // 关闭
                break;

            case 1:
                builder.setProgress(100, msg.arg1, false).setContentText(msg.arg1 + "%");
                manager.notify(10090, builder.build());
                break;
            default:
                break;
            }
        };
    };

    public void onCreate() {
        super.onCreate();
        manager = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(getApplicationContext());

        builder.setSmallIcon(R.drawable.ic_launcher).setTicker("下载").setContentTitle("数据下载中").setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher)).setWhen(System.currentTimeMillis());
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        final String path = intent.getStringExtra("path");
        Log.i("---------", "准备");

        // 开启线程下载
        new Thread() {
            public void run() {
                down(path);
            };
        }.start();

        return super.onStartCommand(intent, flags, startId);
    }

    public void down(String path) {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();

            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();

                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/my.jpg");

                    byte[] b = new byte[1024];
                    int len = 0;

                    // 总的长度
                    int totalsize = conn.getContentLength();
                    // 已经下载的长度
                    int temp = 0;

                    while ((len = is.read(b)) != -1) {
                        fos.write(b, 0, len);
                        temp += len;
                        Message msg = handler.obtainMessage();
                        msg.arg1 = (temp * 100) / totalsize;
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }

                    handler.sendEmptyMessage(0);
                } else {
                    // sd卡不存在
                    handler.sendEmptyMessage(-1);
                }

            } else {
                handler.sendEmptyMessage(-2);
            }

            is.close();
            fos.close();
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值