gpt4 book ai didi

java - 服务 onCreate 和 onStartCommand 不运行

转载 作者:IT王子 更新时间:2023-10-29 06:55:49 26 4
gpt4 key购买 nike

我正在构建一个用于音频播放的 android 服务(它是一个使用 native 代码进行播放的 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 的目的是什么,因为它是一个前台服务,并且保证只要持续的通知显示就一直在运行?

关于java - 服务 onCreate 和 onStartCommand 不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57523637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com