首页 > 解决方案 > 带有 Unity3D 前台服务的 Android 插件

问题描述

我正在尝试为 Unity3D 编写一个 android 插件。该插件应该启动一个前台服务,该服务在使用通知通道杀死应用程序后无法停止。我写了一些代码,但它不起作用。我有两个问题:

  1. 如何将我的 Unity Activity 上下文放入我的 onStartCommand 此处(而不是 Bridge 类) Intent notificationIntent = new Intent(this, Bridge.class);
  2. 我实际上可以在派生应用程序类的类中启动通知吗?

服务等级

public class PedometerService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String input = intent.getStringExtra("inputExtra");
    Intent notificationIntent = new Intent(this, Bridge.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent,0);
    Notification notification = new NotificationCompat.Builder(this, "PedometerLib")
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_adb)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1,notification);
    return START_NOT_STICKY;
}

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

应用类

public class Bridge extends Application {

public static final String TAG="channelExample";
@Override
public void onCreate() {
    super.onCreate();
    createNotifficationChannel();

}


private void createNotifficationChannel(){
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
        NotificationChannel serviceChannel = new NotificationChannel(
                "PedometerLib",
                "Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager!=null){
            Log.d("START", "NOT NULL");
            manager.createNotificationChannel(serviceChannel);
        }

    }
}

public void ExecuteService(final Context ctx,final String message){
    Intent serviceIntent = new Intent(ctx, PedometerService.class);
    serviceIntent.putExtra("inputExtra","Service works...");
    ContextCompat.startForegroundService(this,serviceIntent);
    ctx.startForegroundService(serviceIntent);

}

标签: javaandroidunity3d

解决方案


推荐阅读