Context.startForegroundService然后没有调用Service.startForeground:替代解决方案

时间:2019-04-29 15:17:39

标签: android android-service android-service-binding foreground-service

注意:此问题假设您知道将服务绑定到上下文。

产品上的每个人都知道此问题,甚至某些拥有Android Oreo或Pie设备的用户也知道此问题。异常如下所示:

Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1792)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:164)
   at android.app.ActivityThread.main(ActivityThread.java:6523)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)

当您致电Context.startForegroundService(Intent)时,还必须在5秒内致电Service.startForeground(int, Notification) (即使您的手机甚至无法启动服务,对于某些人来说,这也是您的错原因),否则您的应用将冻结或引发Android框架异常。经过进一步思考,我已经开发出一种解决方案。

由于Context.startForegroundService(Intent)不能确保将在5秒钟内创建该服务,并且该服务是异步操作,因此我认为这种做法会发生:

// Starts service.
public static void startService(Context context)
{
    // If the context is null, bail.
    if (context == null)
        return;

    // This is the same as checking Build.VERSION.SDK_INT >= Build.VERSION_CODES_O
    if (Utilities.ATLEAST_OREO)
    {
        Log.w(TAG, "startForegroundService");

        // Create the service connection.
        ServiceConnection connection = new ServiceConnection()
        {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service)
            {
                // The binder of the service that 
                // returns the instance that is created.
                MyService.LocalBinder binder = (MyService.LocalBinder) service;

                // The getter method to acquire the service.
                MyService myService = binder.getService();

                // getServiceIntent(context) returns the relative service intent.
                context.startForegroundService(getServiceIntent(context));

                // This is the key: Without waiting Android Framework 
                // to call this method inside Service.onCreate(), 
                // immediately call here to post the notification.
                // MyService.createNotification(context) is static
                // for other purposes.
                myService.startForeground(19982, MyService.createNotification(context));

                // Release the connection to prevent leaks.
                context.unbindService(this);
            }

            @Override
            public void onServiceDisconnected(ComponentName name)
            {

            }
        };

        // Try to bind the service.
        try
        {
            context.bindService(getServiceIntent(context), connection, Context.BIND_AUTO_CREATE);
        }
        catch (RuntimeException ignored)
        {
            // This is probably a broadcast receiver context 
            // even though we are calling getApplicationContext().
            // Just call startForegroundService instead 
            // since we cannot bind a service to a
            // broadcast receiver context. 
            // The service also have to call startForeground in this case.
            context.startForegroundService(getServiceIntent(context));
        }
    }
    else
    {
        // Normal stuff below API 26.
        Log.w(TAG, "startService");
        context.startService(getServiceIntent(context));
    }
}

从启动服务的活动中调用此函数。有趣的是:它可以工作并且不会引发异常。我已经在仿真器(我的设备也是Oreo)上进行了测试,我想确认这是防止此异常的最佳方法从发生。

我的问题是:这是实际创建前台服务的好方法吗?有什么想法吗?谢谢您的评论。

0 个答案:

没有答案