我已经花了好几个小时在整个互联网上寻找解决方案。我看到类似的线程,但它们都没有有效的解决方案。
我有前台服务,每秒钟更新通知,这是工作。问题是,当我关闭应用程序时,前台服务也会停止几秒钟,然后重新启动。
问题是它会忘记所有的数据,所以当这个服务从0到100计数,然后关闭应用程序时,前台服务也会停止,然后在一段时间后再次启动,然后从0开始重新计数,它甚至不记得变量值。
必须有一种方法来继续前台服务,而不重新启动服务,每次我的应用程序被杀死。
显示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exampletestlibrary">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true">
<service android:name=".MyOwnService" android:stopWithTask="false" />
</application>
</manifest>
主类:(它是unity的插件,unity应用程序发送其活动并启动前台服务)
package com.example.exampletestlibrary;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
public final class HelloWorld
{
static Activity myActivity;
static PendingIntent pendingIntent;
static boolean runInBackground = true;
static int timeLeftToStop = 190;
public static void ReceiveActivityInstance (Activity tempActivity)
{
myActivity = tempActivity;
}
public static void StartForegroundService ()
{
Intent serviceIntent = new Intent(myActivity, MyOwnService.class);
serviceIntent.putExtra("inputExtra", "Tap to open Let's GO, Friends!");
ContextCompat.startForegroundService(myActivity, serviceIntent);
}
public static void StopForegroundService ()
{
runInBackground = false;
Intent serviceIntent = new Intent(myActivity, MyOwnService.class);
myActivity.stopService(serviceIntent);
}
}
服务等级:
package com.example.exampletestlibrary;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.widget.Toast;
import android.os.Message;
import android.os.Looper;
import android.os.Process;
import androidx.core.app.NotificationCompat;
public class MyOwnService extends Service {
private Looper serviceLooper;
private ServiceHandler serviceHandler;
public static final String CHANNEL_ID = "ForegroundServiceChannel";
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try
{
while (HelloWorld.runInBackground)
{
HelloWorld.timeLeftToStop--;
UpdateNotification(Integer.toString(HelloWorld.timeLeftToStop));
Thread.sleep(1000);
if (HelloWorld.timeLeftToStop <= 1)
{
HelloWorld.runInBackground = false;
}
}
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
@Override
public void onCreate()
{
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work doesn't disrupt our UI.
HelloWorld.runInBackground = true;
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_FOREGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MyOwnService.class);
startForeground(1, CreateNotification(Integer.toString(HelloWorld.timeLeftToStop)));
HelloWorld.runInBackground = true;
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = serviceHandler.obtainMessage();
msg.arg1 = startId;
serviceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy()
{
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_HIGH
);
serviceChannel.setShowBadge(false);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
private void UpdateNotification (String timeLeft)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
Notification notification = CreateNotification(timeLeft);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.notify(1, notification);
}
}
private Notification CreateNotification (String timeLeft)
{
Intent notificationIntent = new Intent(this, HelloWorld.myActivity.getClass());
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Tap to open")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher_icon_background)
.setSubText("countdown - " + timeLeft + " seconds left")
.setOnlyAlertOnce(true)
.build();
}
}
我该怎么做才能让它不在每次用户关闭我的应用程序时重新启动?我想让它运行的所有时间没有任何重新启动由于应用程序终止由用户。
编辑:在我看来,unity正在终止我的服务或通知。我在纯androidstudio项目中测试了相同的代码,并将其构建为apk,效果非常好。
unity活动是否有可能在应用程序退出时终止前台服务?有什么解决办法吗?
暂无答案!
目前还没有任何答案,快来回答吧!