簡體   English   中英

服務 onCreate 和 onStartCommand 不運行

[英]Service onCreate and onStartCommand don't run

我正在構建一個用於音頻播放的 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文件、目錄和manifest中包含的包名是com.example.tailosive。 這可能是一個問題嗎?

另外,在START_STICKY是前台服務時使用它的目的是什么,並且只要持續的通知顯示它就可以保證運行?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM