uni-app 系统通知栏显示进度条Android插件

发布于 1周前 作者 caililin 来自 Uni-App

uni-app 系统通知栏显示进度条Android插件

app新版更新时,在系统通知栏显示下载进度条,代码还有地方要改进。

使用:

var url = "";  
var options = {method:"GET"};  
dtask = plus.downloader.createDownload( url, options );  
plus.notification.setNotification("新版下载", "开始下载"); //插件调用  
dtask.addEventListener( "statechanged", function(task,status){  
    switch(task.state) {  
        case 1: // 开始  
            break;  
        case 2: //已连接到服务器  
             break;  
        case 3: // 已接收到数据  
            var current = parseInt(100*task.downloadedSize/task.totalSize);  
            plus.notification.setProgress(current); //插件调用  
             break;  
        case 4: // 下载完成           
            plus.notification.compProgressNotification("下载完成"); //插件调用  
            plus.runtime.install(plus.io.convertLocalFileSystemURL(task.filename), //安装APP  
                           {force:true},function(){  

            },function(){  
                mui.toast('安装失败');  
            });  
            break;  
    }  
} );

添加权限:

"notification":{  
    "description": "通知栏"  
}

plugin.js:

document.addEventListener("plusready",  function()  
{  
    var B = window.plus.bridge;  
    var notification =   
    {  
        "setProgress":function(incr){  
            return B.exec("notification", "setProgress", [incr]);  
        },  
        "setNotification":function(contentTitle, ticker){  
            return B.exec("notification", "setProgressNotification", [contentTitle, ticker]);  
        },  
        "compProgressNotification":function(contentTitle){  
            return B.exec("notification", "compProgressNotification", [contentTitle]);  
        }  
    };  
    window.plus.notification = notification;  
}, true);

Notify.java:

import io.dcloud.DHInterface.AbsMgr;  
import io.dcloud.DHInterface.IFeature;  
import io.dcloud.DHInterface.IWebview;  
import io.dcloud.util.JSUtil;  
import io.dcloud.adapter.util.AndroidResources;  
import android.R.integer;  
import android.R.string;  
import android.app.Activity;  
import android.app.Notification;  
import android.app.NotificationManager;  
import android.content.Context;  
import android.os.Bundle;  
import android.util.Log;  

public class Notify implements IFeature{  

    NotificationManager manager;  
    Notification.Builder builder;  
    Activity activity;  

    @Override  
    public String execute(final IWebview pWebview, final String action, final String[] pArgs) {  
        activity = pWebview.getActivity();  
        manager = (NotificationManager)activity.getSystemService(Activity.NOTIFICATION_SERVICE);  
        builder = new Notification.Builder(activity);  
        builder.setWhen(System.currentTimeMillis())  
            .setPriority(Notification.PRIORITY_DEFAULT)  
            .setContentTitle("新版下载")  
            .setTicker("开始下载")  
            .setSmallIcon(R.drawable.icon)  
            .setVibrate(null);  

        activity.runOnUiThread(new Runnable() {  
            @Override  
            public void run() {  
                if("setNotification".equals(action))  
                {  
                    String title = pArgs[0];  
                    String ticker = pArgs[1];  
                    builder.setContentTitle(title).setTicker(ticker);  
                    manager.notify(1000, builder.build());  
                }  
                else if("setProgress".equals(action))  
                {  

                    int incr = Integer.parseInt(pArgs[0]);  
                    builder.setProgress(100, incr, false);  
                    manager.notify(1000, builder.build());  
                }  
                else if("compProgressNotification".equals(action))  
                {  
                    String title = pArgs[0];  
                    builder.setContentTitle(title).setProgress(0, 0, false);  
                    manager.notify(1000, builder.build());  
                }  
            }  
        });  
        return null;  
    }  

    @Override  
    public void init(AbsMgr arg0, String arg1) {  

    }  
    @Override  
    public void dispose(String arg0) {  
    }  
}

1 回复

针对在uni-app中实现系统通知栏显示进度条的Android插件需求,可以通过自定义原生插件的方式来实现。以下是一个简要的代码示例,展示了如何在Android端实现通知栏进度条功能,并集成到uni-app项目中。

1. 创建Android原生插件

首先,在Android Studio中创建一个新的Android库项目,用于开发原生插件。

插件代码示例(NotificationProgressPlugin.java)

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;

public class NotificationProgressPlugin extends Service {
    private static final int NOTIFICATION_ID = 1;
    private NotificationManager notificationManager;
    private NotificationCompat.Builder builder;

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        String CHANNEL_ID = "progress_channel";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Progress Channel", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Download Progress")
                .setContentText("0%");

        startForeground(NOTIFICATION_ID, builder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int progress = intent.getIntExtra("progress", 0);
        RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification_progress);
        views.setProgressBar(R.id.progress_bar, 100, progress, false);
        views.setTextViewText(R.id.progress_text, progress + "%");

        builder.setCustomContentView(views);
        notificationManager.notify(NOTIFICATION_ID, builder.build());

        return START_STICKY;
    }

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

2. 在uni-app中调用插件

在uni-app项目中,使用plus.android.importClass方法导入上述服务,并通过Intent启动服务,传递进度参数。

uni-app代码示例

const main = plus.android.runtimeMainActivity();
const Intent = plus.android.importClass('android.content.Intent');
const NotificationProgressPlugin = plus.android.importClass('com.example.NotificationProgressPlugin'); // 替换为实际包名

function updateProgress(progress) {
    const intent = new Intent(main, NotificationProgressPlugin.class);
    intent.putExtra('progress', progress);
    main.startService(intent);
}

// 示例调用
updateProgress(50);

注意

  • 上述代码仅为示例,实际开发中需根据需求完善错误处理、生命周期管理等。
  • R.layout.notification_progressR.drawable.ic_notification需自行定义,包含进度条和文本视图。
  • 确保AndroidManifest.xml中声明了服务,并申请必要的权限。
  • uni-app调用原生插件时,需确保插件已正确集成到项目中。
回到顶部