服务onCreate和onStartCommand无法运行

时间:2019-08-16 11:13:47

标签: java android flutter android-service

我正在构建一个用于音频播放的android服务(这是一个使用本机代码进行播放的Flutter应用),但是启动该服务时,它似乎没有运行onCreate()和`onStartCommand()'。 / p>

我已经通过在这些函数中放置一些打印或日志语句对其进行了测试,但是它们从未运行过。我还确保将服务添加到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。这可能是个问题吗?

1 个答案:

答案 0 :(得分:1)

在前景服务中使用START_STICKY的目的是什么,并且保证只要显示正在进行的通知,它就可以运行?