服务的onCreate和onStartCommand方法不执行

3
我正在构建一个用于音频播放的Android服务(它是一个使用本地代码进行播放的Flutter应用程序),但是在启动服务时,似乎没有运行onCreate()和`onStartCommand()`。
我已经通过在这些函数中添加一些打印或日志语句来测试它们,但它们从未运行。我还确保将服务添加到了AndroidManifest.xml中。
以下是我启动服务的方式:
public class MainActivity extends FlutterActivity implements MethodCallHandler {
  public void onMethodCall(MethodCall call, Result result) {
    switch (call.method) {
      [...]
      case "startService":
        Intent serviceIntent = new Intent(getFlutterView().getContext(), AudioService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          this.startForegroundService(serviceIntent);
        } else {
          this.startService(serviceIntent);
        }
        break;
        [...]
    }
}

FlutterActivity是一个扩展了Activity的类。

这里是服务类:

public class AudioService extends Service {
  public MediaPlayer audioPlayer;

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

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

    Log.i("Audio", "onCreate()");
  }

  @Nullable
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    Log.i("Audio", "Starting service...");

    // create notification
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            0,
            notificationIntent,
            0
    );

    Notification audioNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground service is running")
            .setContentText("This notification does nothing")
            .setSmallIcon(R.drawable.app_icon)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, audioNotification);

    audioPlayer = new MediaPlayer();

    Log.i("Audio", "Service started successfuly");
    return START_STICKY;
  }

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

    // destroy the player
    stopAudio();
  }
  [...]
}

而在 AndroidManifest 中的服务声明:

<service 
      android:name=".AudioService"
      android:process="net.tailosive.app.AudioService"
      android:enabled="true"
      android:exported="true"/>

我不明白我在这里做错了什么。 值得一提的是,安装包名称为net.tailosive.app,但Java文件、目录和清单中包含的包名称为com.example.tailosive。这可能是一个问题吗? 最初的回答:这个问题可能是因为你的应用程序包名不一致导致的。请确保在所有文件中使用相同的包名,包括Java文件、目录和清单文件。

你可以尝试将startForeground放在onCreate的最前面,甚至是在super.onCreate之前。至少这就是在使用前台服务时曾经拯救过我的方法。 - undefined
1个回答

0
  • 我强烈推荐阅读这个问题:Context.startForegroundService() did not then call Service.startForeground()

  • 从我的经验来看(在相同的场景下工作),通过使用startForegroundService命令启动前台服务,您将在不同设备和不同SDK版本上遇到许多意外的错误。只需使用旧的startService方法,一切都会没问题。

另外,在前台服务中使用START_STICKY有什么目的呢?因为它保证只要持续通知显示,服务就会一直运行。


这些东西确实有帮助,但问题似乎是我没有在AndroidManifest.xml中添加FOREGROUND_SERVICE权限。感谢您的建议! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接