gpt4 book ai didi

android - 每隔 X 秒播放一个音频文件 Y 次,即使在更换应用程序时也是如此

转载 作者:行者123 更新时间:2023-11-30 00:05:44 25 4
gpt4 key购买 nike

我的应用应该接收确定音频播放方式的时间(以秒为单位)。

例子:每2分钟播放一次音频文件x(时长约2秒),共播放16次。

如果 android 不喜欢在您转移到另一个应用程序后如此频繁地关闭外国应用程序和服务,那就太好了。

我的结构是这样的:

MainActivity 通过 intent 启动一个新的 MainActivityService

gintent = new Intent(MainActivity.this,MainActivityService.class);
gintent.putExtra(...);
gintent.putExtra(...);
...
startService(gintent);

然后该服务运行 putExtra 指定的时间。

关键是,android 有各种各样的机制来杀死服务和应用程序。所以我一直在尝试通过在 MainActivity 中使用 onSaveInstanceState 来保持它

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(...);
savedInstanceState.putInt(...);
...
}

onRestoreInstanceStateisMyServiceRunning(MainActivityService.class) 等等,但我忘记了所有的 onResume 等等。并且最终服务还是被kill掉了。

我不想来回调试这个。我想知道黄金标准如何做到这一点。

最佳答案

Android 将非前台服务视为可以终止的时机。您需要将您的服务标记为前台服务。这将降低操作系统终止该进程的可能性。

A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory.... To request that your service run in the foreground, call startForeground().

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build();

startForeground(ONGOING_NOTIFICATION_ID, notification);

参见:Running a service in the foreground

关于android - 每隔 X 秒播放一个音频文件 Y 次,即使在更换应用程序时也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061005/

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