关闭

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

标签: Androidservice下载通知
102人阅读 评论(0) 收藏 举报
分类:
  • 不能在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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6307次
    • 积分:444
    • 等级:
    • 排名:千里之外
    • 原创:39篇
    • 转载:0篇
    • 译文:1篇
    • 评论:1条
    文章分类
    最新评论