如何在Oreo中运行长周期的后台服务?

10

Android Oreo对后台运行服务实施了许多限制。在Oreo中,服务的行为已不同于以前。

但是,如果我必须长时间在后台运行服务该怎么办。

我正在开发一个应用程序,在用户摇动手机时启动手电筒。为了实现这一点,我需要将传感器监听器代码放在服务内部。

如何防止Android系统杀死该服务。

附言:我不想通过通知启动前台服务。


2
如果您不断运行并持续监听传感器变化,则用户应该知道此情况(通过前台服务)。 - ianhanniballake
2
@GabeSechan - 假设他们正在使用通知渠道,您可以完全关闭该渠道(无论显示是否影响前台行为),或将其降低到最低优先级(以便它不会显示在状态栏上)。 - ianhanniballake
4
@ianhanniballake 我希望它们只是被删除了。Google这个改变是一个错误——它让很多很酷的功能变得比它们需要的更加困难,混杂在我的通知中,并且对我作为用户没有任何价值,同时减少我的开发者选项。在我的设备上,使用电池的服务从来不是问题,这个改变没有改善我的电池寿命,但却让我的生活变得困难。 - Gabe Sechan
3
请注意,从2018年底开始,针对API 26(以及相关的后台限制)是强制性的。目前你所看到的(应用程序是否针对API 26)并不能说明在年底时情况会如何。请理解本文意思,不做改变,并使翻译更加易懂。 - ianhanniballake
2
@GurleenSethi:Google 限制了许多隐式广播,但没有限制显式广播。其中一些隐式广播,包括 ACTION_NEW_OUTGOING_CALL已被记录为白名单 - CommonsWare
显示剩余8条评论
4个回答

11
如何防止Android系统杀死服务?
总结评论:使用前台服务,在专用频道上发布通知,将频道设置为`IMPORTANCE_DEFAULT`。建议用户可以静音该频道(例如,在通知栏中长按“通知”)。使用专用频道意味着您仍然可以在其他频道上引发通知。您的通知还应该是有用的:
- 如果用户想要暂停服务,请提供“停止”操作以停止您的服务 - 点击通知本身会导致您的活动,以配置您应用程序的行为
如果我不想使用带有通知的前台服务。
那么最可能无法编写应用程序。
我不能排除在Android 8.x中存在一些漏洞,可以利用无限期服务的时间。实际上,我认为这种情况相当普遍。但是,这明显违反了Google的意图,这意味着:
- 如果这是您计划分发应用程序的方式,则利用该技术而没有被Google认为是合理的理由可能会导致您的应用程序被禁止在Play商店中。 - 该漏洞可能会在将来的Android版本中得到修复,与Google展开竞争往往是失败的命题
已经有足够多的“空气手势”应用程序(即基于摇晃做出反应),理想情况下,Google应该为此添加一些专用的低功耗API。例如,他们可以向`JobScheduler`添加功能,允许您注册摇晃事件,并在该情况下调用您的`JobService`,就像他们允许您注册对`ContentProvider`更改的监听一样。我不知道他们是否会提供这样的API,但如果您愿意,可以提出功能请求。

我如何创建一个前台服务,使用专用通道上的通知,并将通道设置为IMPORTANCE_DEFAULT? - Aniruddh Parihar
@CommonsWare 怎样从广播接收器中启动一个服务? - Rahulrr2602
@Rahulrr2602:调用startForegroundService(),并确保服务本身在启动后不久调用startForeground() - CommonsWare
我尝试在onStartCommand()中调用startForeground(),但是它报错了。有什么想法吗? - Rahulrr2602
@Rahulrr2602:请提出一个单独的 Stack Overflow 问题,其中提供一个 [mcve] 并详细解释“出现错误”的含义。 - CommonsWare
显示剩余2条评论

6

让一个服务在Oreo或更高版本上变得不可停止而不显示通知是可能的(是的,我们可以)。

现在我来解释一下如何使服务仅可由用户停止,而不是由系统停止(或者更好地说,唯一的停止方式是卸载您的应用程序)。

请注意,即使我认为使服务不可停止不是一种好的技术,出于不同的原因(如电池消耗、清晰的用户体验等),我持反对态度。

首先,您需要在清单文件中声明该服务。

独立名称“:serviceNonStoppable”将使该服务在单独的进程中运行,而不是在主应用程序进程中运行。这对于需要单独运行的后台进程很有帮助。 为了使我们自己的服务进程对其他进程或应用程序不可见,您需要设置exported=false参数。 描述“@string/service_description”将告诉用户您的服务执行的操作以及为什么用户不应停止它们(您可以在strings.xml中创建此描述)。

  <service
      android:process=":serviceNonStoppable"
      android:name="your.package.name.serviceOn" 
      android:exported="false"
      android:description="@string/service_description" />

其次我们要创建一个支持类,其中包含可在不同地方使用的静态方法。
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Utils {

   // This is a support class witch have static methods to use everywhere

   final static int NOTIFICATION_INT_CHANNEL_ID = 110211; // my daughter birthday but you can change that with your number
   final static String NOTIFICATION_STRING_CHANNEL_ID = "put.a.random.id.here"; //if you write "the.pen.is.on.the.table" is the same

   final static int TEST_THIS = 111; // or you can put here something else
   final static String BROADCAST_MSG_ID = "BROADCAST_MSG_ID"; // or you can put here something else
   final static String APP_MESSAGE = "your.package.name.action.APP_MESSAGE"; // or you can put here pippo.pluto.and.papperino

   static void returnUpMyService(final Context context) {
      try {
         //to avoid crashes when this method is called by service (from itself) make sure the service is not alredy running (maybe is in cache)
         if (killServiceIfRun(context)) {
            startServiceOn(context);
         }

      } finally {
         System.out.println(" I'm trying to start service ");
      }
   }


   private static boolean killServiceIfRun(final Context context) {

      boolean isRunning = isMyServiceRunning(context);
      if (!isRunning) { return true; }

      try {
         ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

         // maybe killing process is not terminated by system in this fase
         //I force to kill them by my one
         if (manager != null) {
            manager.killBackgroundProcesses(getServicename(context));
            return true;
         }
         return true;
      } catch (Exception e) {
         System.out.println("killServiceIfRun error: " + e.toString());
      }

      return false;

   }


   private static boolean isServiceInCache(final Context context) {

      ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      if (manager != null && manager.getRunningAppProcesses() != null) {

         if (manager.getRunningAppProcesses().size() > 0) {
            for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {

               if (process.processName != null) {
                  if (process.processName.equalsIgnoreCase(getServicename(context))) {
                     // Here we know that the service is running but sleep brrrrrrrr
                     if (process.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
                        return true;
                     }
                  }
               }
            }
         }
      }

      return false;
   }


   static void StartMyService(Context context) {

      // If the sevice is running doesn't need to restart
      if (isMyServiceRunning(context) && !isServiceInCache(context)) {
         return;
      }

      // If service is running but is in chache is the same like killed, so we need to kill them
      if (isServiceInCache(context)) {
         // this method at first kill and after that start the service
         returnUpMyService(context);

      } else {
         //Otherwise we start own service
         startServiceOn(context);
      }

   }


   private static void startServiceOn(final Context context) {
      // After we had been sure about that service doesn't exist
      // we make a schedule to restart them
      new ScheduledThreadPoolExecutor(1).schedule(() -> {

         //Create an instance of serviceOn
         serviceOn service = new serviceOn();

         //prepare the launch intent
         Intent launchIntent = new Intent(context, service.getClass());

         // Now we start in background our service
         context.startForegroundService(launchIntent);

         // I put 50 ms to allow the system to take more time to execute GC on my killed service before
      }, 50, TimeUnit.MILLISECONDS);
   }

   private static boolean isMyServiceRunning(final Context context) {

      ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      if (manager != null && manager.getRunningAppProcesses() != null) {

         if (manager.getRunningAppProcesses().size() > 0) {
            for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
               if (process != null && process.processName != null && process.processName.equalsIgnoreCase(getServicename(context))) {
                  return true;
               }
            }
         }
      }

      return false;

   }


   static void SendMsgToService(Context context, int id, Map<String, Object> params) {

      try {
         Intent mServiceIntent = new Intent(APP_MESSAGE);

         if (params != null) {

            for (Map.Entry<String, Object> entry : params.entrySet()) {
               //System.out.println(entry.getKey() + "/" + entry.getValue());

               if (entry.getValue() instanceof String) {
                  mServiceIntent.putExtra(entry.getKey(), (String) entry.getValue());
               } else if (entry.getValue() instanceof Integer) {
                  mServiceIntent.putExtra(entry.getKey(), (Integer) entry.getValue());
               } else if (entry.getValue() instanceof Float) {
                  mServiceIntent.putExtra(entry.getKey(), (Float) entry.getValue());
               } else if (entry.getValue() instanceof Double) {
                  mServiceIntent.putExtra(entry.getKey(), (Double) entry.getValue());
               } else if (entry.getValue() instanceof byte[]) {
                  mServiceIntent.putExtra(entry.getKey(), (byte[]) entry.getValue());

               }
            }
         }

         mServiceIntent.putExtra(BROADCAST_MSG_ID, id);
         context.sendBroadcast(mServiceIntent);

      } catch (RuntimeException e) {
         System.out.println(e.toString());
      }

   }


   private static String getServicename(final Context context) {
      //                                 the name declared in manifest you remember?
      return context.getPackageName() + ":serviceNonStoppable";
   }


}

这是一个继承IntentService的服务类。

import android.app.IntentService;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class serviceOn extends IntentService {

   // Needed to keep up notifying without show the icon
   private ScheduledExecutorService notifyer = null;


   // don't remove this. cause error becouse we declare this service in manifest
   public serviceOn() {
      super("put.a.constant.name.here");
   }


   // We need this class to capture messages from main activity
   private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

      @Override
      public void onReceive(final Context context, Intent intent) {

         if (intent != null) {
            if (intent.getAction() != null) {

               if (intent.getAction().equals(Utils.APP_MESSAGE)) {

                  int msgID = intent.getIntExtra(Utils.BROADCAST_MSG_ID, -1);

                  switch (msgID) {

                     case Utils.TEST_THIS:

                        String message = intent.getStringExtra("message");
                        if (!TextUtils.isEmpty(message)) {
                           System.out.println(message);
                        }
                        //Do your task here
                        //Do your task here
                        //Do your task here
                        //Do your task here
                        break;

                  }

               }
            }
         }
      }

   };


   @Override
   protected void onHandleIntent(@Nullable Intent intent) { }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      return START_STICKY;
   }


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


      try {
         // First of all we need to register our receiver
         List<String> actions = Arrays.asList(
         Utils.APP_MESSAGE, // this is the string which identify our mesages
         Intent.ACTION_SCREEN_ON, // this event is raised on sreen ON by system
         Intent.ACTION_SCREEN_OFF, // this event is raised on screen OFF by system
         Intent.ACTION_TIME_TICK);// this event is raised every minute by system (helpful for periodic tasks)

         for (String curIntFilter : actions) {
            IntentFilter filter = new IntentFilter(curIntFilter);
            registerReceiver(broadcastReceiver, filter);
         }
      } catch (RuntimeException e) {
         e.printStackTrace();
      }


      final Notification notificationDefault = new NotificationCompat.Builder(getApplicationContext(), Utils.NOTIFICATION_STRING_CHANNEL_ID)
                                               .setOngoing(true) //Ongoing notifications do not have an 'X' close button, and are not affected  by the "Clear all" button
                                               .setCategory(Notification.CATEGORY_SERVICE) // indicate this service is running in background
                                               .setSmallIcon(R.drawable.ic_radio) // put here a drawable from your drawables library
                                               .setContentTitle("My Service")  // Put here a title for the notification view on the top

                                               // A smaller explanation witch system show to user this service is running
                                               // in background (if existing other services from other apps in background)
                                               .setContentText("My Service is unstoppable and need to run in background ")
                                               .build();


      // This is an efficient workaround to lie the system if we don't wont to show notification icon on top of the phone but a little aggressive 
      notifyer = Executors.newSingleThreadScheduledExecutor();
      notifyer.scheduleAtFixedRate(() -> {

         try {
            // Here start the notification witch system need to permit this service to run and take this on.
            // And we repeat that task every 15 seconds 
            startForeground(Utils.NOTIFICATION_INT_CHANNEL_ID, notificationDefault);

            //immediately after the system know about our service and permit this to run
            //at this point we remove that notification (note that is never shown before)
            stopForeground(true);

            //better not invoke Exception classes on error, make all a little heavy
         } finally {
            // Log here to tell you your code is called
            System.out.println(" Service is running");
         }

         // So, the first call is after 1000 millisec, and successively is called every 15 seconds for infinite
      }, 1000, 15000, TimeUnit.MILLISECONDS);

   }


   @Override
   public void onDestroy() {

      // unregister the receiver
      unregisterReceiver(broadcastReceiver);

      // stop the notifyer
      if (notifyer != null) {
         notifyer.shutdownNow();
         notifyer = null;
         System.out.println(" notifyer.shutdownNow() ");
      }


      final Context context = getBaseContext();

      try {

         new Thread() {

            @Override
            public void run() {

               // The magic but dirty part
               // When the system detect inactivity by our service decides to put them in cache or kill it
               // Yes system you can kill me but I came up stronger than before
               Utils.returnUpMyService(context);
            }
         }.start();

      } finally {
         System.out.println("You stop me LOL ");
      }

   }


}

这里是用法。
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;

import java.util.HashMap;

class MyActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      // Sstart the first time
      Utils.StartMyService(this);

      // Test after 3 seconds
      new Handler().postDelayed(() -> {
         Utils.SendMsgToService(X_App.getContext(), Utils.TEST_THIS, new HashMap<String, Object>() {{
            put("message", "Hello from main activity");
         }});
      }, 3000);



   }
}

感谢您的回答,非常感激。附注:我不再从事Android开发,转向Flutter :) - Gurleen Sethi
@G3nt_M3caj,好答案,也是很好的方法。非常感谢你。 - FLASHCODER
看起来有点像狐狸式的,但是运行得非常完美 ;) 谢谢。 - G3nt_M3caj
谢谢 @G3nt_M3caj!这是一个无可挑剔的解决方案! - vidulaJ
@vidulaJ 我有两个应用程序需要在GP上拥有不间断的服务。祝玩得愉快 :) - G3nt_M3caj
显示剩余2条评论

3
我发现我们可以在Android Oreo及以上版本中运行前台服务而不显示通知,以下是解决方案:首先创建带有通知信道的通知,还要为通知设置通道ID,然后使用该通知启动前台服务。现在是时候使用ID取消通知通道,并在1或2秒后删除通知,这意味着通知将被移除并且服务将始终运行。就这样。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接