Notificaton+IntentService下载

在这里插入图片描述

在这里插入图片描述

思路

1.后台下载用IntentService

2.获得文件总长度

3.每隔多长时间发送通知

详细代码

Service.java

public class DownLoadMusicService extends IntentService {

    public InputStream inputStream;
    public int total;
    public NotificationManager manager;
    public int notificaton_id = 100;
    public NotificationCompat.Builder builder;
    public Handler handler = new Handler();
    public int currentProgress = 0;
    HttpURLConnection connection;

    public DownLoadMusicService() {
        super("LoadMusic");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

        initNotification();
        startForeground(notificaton_id, builder.build());
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent( @Nullable Intent intent) {
        String path = intent.getStringExtra("url");

        try {
            URL  url = new URL(path);

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Encoding", "identity");//不加此行得不到总长度
            total = connection.getContentLength();//拿不到
            if(connection.getResponseCode() == 200){

                handler.post(nThread);
                inputStream = connection.getInputStream();

                int len = 0;
                byte[] bytes = new byte[60];

                File file0 = Environment.getExternalStorageDirectory();
                File newFile = new File(file0,"dabeizhou.mp3");
                FileOutputStream fileOutputStream = new FileOutputStream(newFile);

                while ((len = inputStream.read(bytes)) != -1){
                    currentProgress+=len;
                    fileOutputStream.write(bytes,0,len);
                }
                Log.d("amy",currentProgress+"--");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(inputStream != null)
                    inputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

            if(connection != null)
                connection.disconnect();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void initNotification(){
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel("channel_1","name",NotificationManager.IMPORTANCE_LOW);
        manager.createNotificationChannel(channel);
        builder = new NotificationCompat.Builder(this,"channel_1")
                .setSmallIcon(R.mipmap.bq1)
                .setContentText("下载文件")
                .setContentText("下载中。。");
    }

    /**
     * 线程用来发送通知
     */
    Thread nThread = new Thread(){
        @Override
        public void run() {
            super.run();
            builder.setProgress(total,currentProgress,false);
            manager.notify(notificaton_id,builder.build());
            handler.postDelayed(nThread,1000);
        }
    };

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

Activity.java

public void downloadMusic(View view) {
        //下载
        Intent intent = new Intent(this,DownLoadMusicService.class);
        intent.putExtra("url","http://m10.music.126.net/20200704095418/39a88357cd32cb186ccaed3699cd2083/ymusic/8481/cbba/7868/c96fe64c4a34c2137ce30e5f941b145c.mp3");
        startService(intent);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值