前景服务无法持续运行

时间:2018-08-13 13:29:54

标签: 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;
    }

}

1 个答案:

答案 0 :(得分:3)

  

您的代码中没有一个... Many problems ...您可能会收到“ 0错误”,因为它在语法上是正确的,但androidicaly是错误的,您的{{1 }}很差,basicsandroid documentation的阅读效果很差。 Android永远不会运行非常糟糕的事情...

问题:1

您通常知道服务吗,应该使用implementation overrideonCreateonStartCommandonBind方法...。

  

我在那没有看到onDestroy .... !!

问题:2

您知道如何通知...吗?您的onDestroy实现再次变得毫无意义。

  

保持空空,只需返回START_STICKY

问题:3

您希望如何在后台执行限制下运行它?首先仅在onStartCommand中发出通知,然后在需要时使用oncreate来通知Android。

  

我在那儿看不到它。...您尝试在startforeground中执行此操作,但它再次表现不佳...

嗯...看看下面的工作代码:

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"); } } 中的“ Performing”消息...

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

  

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

如何启动它...... ??????

无论是来自logcat还是来自mainactivity或来自任何receiver的任何地方:

class

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

根本就不.....即使您开始服务需要多少次....如果它已经在运行中...那么它将不会再次启动....如果没有在运行则...将开始... !!

相关问题