前台服务不会一直运行

Mad*_*ina 2 android foreground-service

在我的应用程序中,我使用必须不断运行的前台服务。有时前台服务会停止。在什么情况下操作系统会终止我的服务(即使内存足够,电池已满,手机正在充电也会发生)?

这是我的代码到目前为止的样子:

public class ServiceTest extends Service {

    public static Thread serverThread = null;
    public Context context = this;

    public ServiceTest(Context context) {
        super();
        this.context = context;
    }

    public ServiceTest() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        if (this.serverThread == null) {
            this.serverThread = new Thread(new ThreadTest());
            this.serverThread.start();
        }

        return START_STICKY;
    }

    private class ThreadTest implements Runnable {

        @Override
        public void run() {
            Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle("Notification title")
                .setContentText("Notification text")
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .setSmallIcon(R.drawable.android)
                .setOngoing(true).build();

                startForeground(101, notification);

                while(true){
                    //work to do
                }
        }


    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

san*_*ane 5

没有一个单一的...Many problems在你的代码......你可能会得到它“0错误”,因为它在语法上是正确的,但它是androidicaly错的,你basics是穷人,阅读android documentationimplementation非常差。Android 从不运行非常糟糕的东西......

问题:1

你知道一个服务传统,你应该override onCreateonStartCommandonBindonDestroy方法....?

我在那里看不到 onDestroy....!!

问题:2

你知道如何通知...?您的onStartCommand实施再次毫无意义。

保持清空只需返回 START_STICKY

问题:3

您如何期望在后台执行限制下运行它......?首先通过oncreatestartforeground在需要时发出通知来通知 android ......

我在那里看不到它......你试图这样做onstartcommand一次又一次它非常糟糕......

好吧...看看下面的工作代码:

public class RunnerService extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";

public RunnerService() { }

@Override
public void onCreate()
{
    super.onCreate();

    Log.d("RUNNER : ", "OnCreate... \n");

    Bitmap IconLg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);

    mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this, null);
    mBuilder.setContentTitle("My App")
            .setContentText("Always running...")
            .setTicker("Always running...")
            .setSmallIcon(R.drawable.ic_menu_slideshow)
            .setLargeIcon(IconLg)
            .setPriority(Notification.PRIORITY_HIGH)
            .setVibrate(new long[] {1000})
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setOngoing(true)
            .setAutoCancel(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{1000});
        notificationChannel.enableVibration(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        mNotifyManager.createNotificationChannel(notificationChannel);

        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        startForeground(1, mBuilder.build());
    }
    else
    {
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotifyManager.notify(1, mBuilder.build());
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.d("RUNNER : ", "\nPERFORMING....");

    return START_STICKY;
}

@Override
public void onDestroy()
{
    Log.d("RUNNER : ", "\nDestroyed....");
    Log.d("RUNNER : ", "\nWill be created again automaticcaly....");
    super.onDestroy();
}


@Override
public IBinder onBind(Intent intent)
{
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("NOT_YET_IMPLEMENTED");
}
}
Run Code Online (Sandbox Code Playgroud)

怎么查……???

从最近列表中删除该应用程序,您应该在日志中看到“ Performing”消息logcat...

在什么情况下它会停止......?

它永远不会停止(直到下次启动......!!)......是的,当用户强制停止应用程序时它会停止。很少有系统发现它的资源非常少......这似乎是一种非常罕见的情况,因为 android 随着时间的推移有了很大的改进......

如何开始它......????

无论它可能来自mainactivity或来自receiver或来自任何class

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            context.startForegroundService(new Intent(context, RunnerService.class));

        }
        else
        {
            context.startService(new Intent(context, RunnerService.class));

        }
Run Code Online (Sandbox Code Playgroud)

如何检查服务是否已启动....?

简单地不要.....即使你想要多少次启动服务....如果它已经在运行......那么它就不会再次启动......如果没有运行......开始吧……!!