澄清Android前台服务

Sta*_*een 5 android

我的应用程序当前使用后台服务与物理设备进行通信(蓝牙).(我制造和销售物理设备.)应用程序每500ms向设备发送一个命令.用户启动此过程并且必须运行直到用户停止它.当应用程序处于活动状态时,该过程的结果将发送到应用程序.即使应用程序未处于活动状态,也需要运行此过程.(即他们接听电话,搜索网络.)一旦应用程序再次变为活动状态,该过程的状态将与应用程序同步.该过程可以在几分钟到几个小时的任何时间运行.(是的,如果用户希望在99小时内运行该过程,则需要插入.)大多数用户运行它持续2-15分钟.一切都很好,但是对于API 26,看起来不再允许这种架构.一种迁移选项是移动到前台服务.但是,我发现有关前台服务如何工作的文档不清楚.前台服务是否继续运行且应用程序未激活?(即它已经通过onPause.)如果是这样,这与后台服务有什么不同?有关前台服务如何工作的更好的文档.(我的网络搜索没有显示任何重要信息.)Alos,API 26文档没有说明如果新的限制仍适用,应用程序是否与后台服务绑定.他们呢?

谢谢,斯坦

小智 11

一个前台服务是你把在前台状态的服务,这意味着,系统不会,如果它需要CPU,或者如果您的应用程序被关闭杀死进程.

首先,您有3种服务:

  • 已启动的服务(在UI线程中运行)
  • IntentService(在自己的线程中运行)(请参阅服务与IntentServices)
  • 绑定服务(只要有一个活动绑定它就会运行)

如上所述,如果您关闭应用程序,绑定服务也将关闭,它由bindService()启动.

IntentServices是一个子类型,Service它简化了传入意图的"工作队列进程",即它在队列中逐个处理传入意图,如IntentService描述中所述.它有一个默认实现,由startService()启动.它主要用于异步任务.

"已启动服务"是由组件启动的服务,并在调用stopService()或关闭您的应用程序之前继续存在.

使用Foreground Service可以Service 保持持久性.您必须在服务中调用startForeground().它会一直运行,直到你停止Service,例如使用stopSelf()stopService() ;

请注意,每次调用startService()时都会触发onStartCommand(),但只触发一次.onCreate()

以下是Foreground Started Service的简单实现:

在你的Manifest.xml中:

<service android:name=".ConnectionService"
    android:enabled="true"/>
Run Code Online (Sandbox Code Playgroud)

在MyService.java中:

public class MyService extends Service {
    // Unique notification identifier
    private final static int NOTIFICATION_ID = 95;

    private NotificationManager mNotificationManager;

    public MyService() { super(); }

    @Override
    public void onCreate() {
        // Initialize notification
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        // Build your notification here
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        mBuilder.setSmallIcon(R.mipmap.ic_small_icon);
        mBuilder.setContentTitle("MyService");
        mBuilder.setContentText("The Service is currently running");

        // Launch notification
        startForeground(NOTIFICATION_ID, mBuilder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Handle startService() if you need to
        // for exmple if you are passing data in your intent
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // We don't provide binding, so return null
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Remove the notification when the service is stopped
        mNotificationManager.cancel(NOTIFICATION_ID);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后只需调用startService().