Notificaton+IntentService下载

Notificaton+IntentService下载下载音乐

    • 思路
      • 1.后台下载用IntentService
      • 2.获得文件总长度
      • 3.每隔多长时间发送通知
    • 详细代码
      • Service.java
      • Activity.java

Notificaton+IntentService下载_第1张图片

Notificaton+IntentService下载_第2张图片

思路

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);
    }

你可能感兴趣的:(Android,一,android)