日常开发——Service, Notification显示下载进度

最近做的一个小demo,启动Service并在Service里面创建一个线程来监听下载进度,更新notification的UI。当然,demo里面的下载并非是真正的下载文件,而是一个循环累加的数值,有兴趣的朋友可以添加真正的下载线程来调试。Demo做得比较简单,没有设置点击响应事件,所以是没有取消下载的,只能算是个小demo吧,有机会时再实现更多功能。


MainActivity.java

Activity只有一个点击响应事件,点击service按钮时,将启动MyService,因为没实现交互,所以没有bindService。

package com.example.demo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        Button serviceButton = (Button)findViewById(R.id.button2);
        serviceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


MyService.java

package com.example.demo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
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.RemoteViews;

public class MyService extends Service {
    public MyService() {
    }

    private NotificationCompat.Builder nBuilder = null;
    private Notification notification = null;
    private NotificationManager manager = null;
    private RemoteViews remoteViews = null;
    private Handler sHandler = new Handler(){
        @Override
        public void handleMessage(Message message){
            switch (message.what){
                case 100:
                    manager.cancel(1);
                    stopSelf();
                    break;
                default:
                    remoteViews.setProgressBar(R.id.progress, 100, message.what, false);
                    remoteViews.setTextViewText(R.id.progressText, Integer.toString(message.what)+"%");
                    manager.notify(1,notification);
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        nBuilder = new NotificationCompat.Builder(this);
        nBuilder.setSmallIcon(R.mipmap.ic_launcher);
        remoteViews = new RemoteViews(getApplication().getPackageName(), R.layout.layout_update_download);
        nBuilder.setContent(remoteViews);
        remoteViews.setProgressBar(R.id.progress, 100, 0, false);
        remoteViews.setTextViewText(R.id.progressText, "0%");
        notification = nBuilder.build();
        Log.e("S","C");
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private boolean buttonStatus = false;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("S", "S");
        manager.notify(1, notification);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(500);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = i;
                    sHandler.sendMessage(message);
                }
                }
            }).start();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.e("S","D");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}


Notification 布局文件 

layout_update_download.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp">
    <TextView
        android:text="Download Update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </TextView>
    <LinearLayout
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ProgressBar
                style="?android:attr/progressBarStyleHorizontal"
                android:id="@+id/progress"
                android:layout_weight="2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="20dp">
        </ProgressBar>
       <TextView
           android:text="0%"
           android:gravity="center"
           android:layout_weight="5"
           android:id="@+id/progressText"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

演示

(请忽略里面的JUMP按钮)



点击service,开启“下载”


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Android 中的 `DownloadManager` 来实现下载链接文件并显示下载进度。 首先,在 AndroidManifest.xml 文件中添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /> <uses-permission android:name="android.permission.DOWNLOAD_MANAGER" /> ``` 然后,在需要下载的地方使用以下代码: ```java DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse("下载链接")); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) .setAllowedOverRoaming(false) .setTitle("下载标题") .setDescription("下载描述") .setVisibleInDownloadsUi(true) .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "文件名"); long downloadId = downloadManager.enqueue(request); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_RUNNING == cursor.getInt(columnIndex)) { int columnTotalSizeIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES); int columnDownloadedSoFarIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR); int totalSize = cursor.getInt(columnTotalSizeIndex); int downloadedSoFar = cursor.getInt(columnDownloadedSoFarIndex); float progress = ((float) downloadedSoFar / (float) totalSize) * 100; // 更新下载进度 } } ``` 以上代码会启动下载任务,并在 `DownloadManager` 中查询下载进度。可以通过查询到的下载状态和下载进度更新 UI。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值