uniapp 安卓原生插件如何注册前台服务的具体步骤
在UniApp开发中,如何在安卓原生插件中注册前台服务?具体步骤是什么?需要配置哪些权限和参数?能否提供一个完整的示例代码?
2 回复
- 在插件Module的
onCreate方法中创建NotificationChannel - 构建Notification对象(需设置常驻通知)
- 调用
startForeground(notificationId, notification)启动前台服务 - 在
AndroidManifest.xml声明服务并添加FOREGROUND_SERVICE权限 - 注意Android 9+需要添加
FOREGROUND_SERVICE权限声明
在 UniApp 中注册 Android 前台服务需通过原生插件实现,步骤如下:
1. 创建 Android 原生插件项目
- 在 UniApp 项目的
nativeplugins目录下创建插件文件夹(如MyForegroundService)。 - 目录结构:
MyForegroundService/ ├── android │ ├── libs │ ├── src │ │ └── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── MyService.java │ │ └── AndroidManifest.xml │ └── plugin.gradle
2. 实现前台服务类
在 MyService.java 中继承 Service,并添加前台服务逻辑:
public class MyService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 创建通知并启动前台服务
Notification notification = buildNotification();
startForeground(NOTIFICATION_ID, notification);
return START_STICKY;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"前台服务通道",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
private Notification buildNotification() {
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("前台服务运行中")
.setContentText("服务正在后台执行任务")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.build();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
3. 配置 AndroidManifest.xml
在插件目录的 AndroidManifest.xml 中声明服务:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<service android:name=".MyService" android:enabled="true" android:exported="false" />
</application>
</manifest>
4. 创建插件调用接口
在插件 android 目录下创建模块类(如 MyForegroundModule.java):
public class MyForegroundModule extends UniModule {
@UniMethod
public void startForegroundService() {
Context context = mUniSDKInstance.getContext();
Intent intent = new Intent(context, MyService.class);
context.startService(intent);
}
@UniMethod
public void stopForegroundService() {
Context context = mUniSDKInstance.getContext();
Intent intent = new Intent(context, MyService.class);
context.stopService(intent);
}
}
5. 注册插件
在 UniApp 项目的 pages.json 中配置插件:
{
"plugins": {
"MyForegroundService": {
"version": "1.0.0",
"provider": "你的插件包名"
}
}
}
6. 在 UniApp 中调用
在 Vue 文件中使用:
const myService = uni.requireNativePlugin('MyForegroundService-MyForegroundModule');
// 启动服务
myService.startForegroundService();
// 停止服务
myService.stopForegroundService();
注意事项:
- Android 8.0+ 必须创建通知渠道,否则服务无法启动。
- 确保在
AndroidManifest.xml中声明服务,避免崩溃。 - 测试时需使用真机,并授予必要权限(如前台服务权限)。
以上步骤可帮助你在 UniApp 中注册并调用 Android 前台服务。

