【问题标题】:Have service running when app is closed from recent apps从最近的应用程序关闭应用程序时运行服务
【发布时间】:2017-11-13 18:41:00
【问题描述】:

我想继续运行一项服务,即使在应用程序关闭后仍会读取传入消息 [单击最近的应用程序按钮然后关闭它]。我尝试使用 START_STICKY,隔离进程,但没有任何效果。最新的安卓版本可以吗?

【问题讨论】:

  • 您可以在单独的进程中运行您的服务。
  • 我尝试使用我的 put 进程名称并将其隔离为 true,但应用程序被杀死。
  • 如果您的服务 onstart 命令返回 START_STICKY,如果应用程序进程被杀死,它将再次重新启动服务。在这里查看 - developer.android.com/reference/android/app/…
  • @Christopher 在单独的进程中运行服务但无法正常工作,因为一旦应用程序进程被终止,它将终止。
  • START_STICKY 不起作用。

标签: android android-service


【解决方案1】:

试试

public int onStartCommand(Intent intent, int flags, int startId)
{
..........

return super.onStartCommand(intent, flags, startId);
}

但是当你关闭应用程序时 onStartCommand 从头开始​​重新启动它是否已经完成它的工作!

【讨论】:

    【解决方案2】:
    private void startForground(){
        Intent notificationIntent = new Intent(this,MainActivity.class);
        PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
                notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    
        Notification notification=new NotificationCompat.Builder(this)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setContentText("App Name")
                                    .setContentIntent(pendingIntent)
                                    .build();
    
        startForeground(NOTIFICATION_ID, notification);
    }
    

    如果您不想显示通知或图标但仍想在后台运行,请尝试this answer

    【讨论】:

    • 我不想显示任何图标。想要将其作为后台服务运行。
    【解决方案3】:

    制作一个粘性服务,将确保您在应用关闭后重新启动,但您需要在onStartComand()中调用您的方法。

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your job here
        // start reading your incoming messages
        readMessages();
        return START_STICKY;
    }
    

    【讨论】:

    • START_STICKY 不起作用。当我从最近使用的应用程序中滑动服务时,服务会被终止。
    • 是的,但应该在被杀死后开始。你不能让服务一直运行。
    【解决方案4】:

    onStartCommand() 中尝试startForeground(notitficationId, notificationObject); 命令

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多