首页 文章

Android服务onStartCommand方法param使用

提问于
浏览
0

现在更新的SDK版本Service类具有覆盖方法

int onStartCommand(Intent intent,int flags,int startId)

它取代了随Android 2.0(API级别5)引入的以下内容 .

void onStart(Intent intent,int startid)

我的问题是:

  • 什么是使用params如flag和startId作为参数传递?

  • 我们如何操纵这些参数?

Update 1. 2:清除:)

以下是snapcode清除 flags param的用例 . 默认情况下它收到0,如果你的服务开始回来,那么它将收到带有我们从onStartCommand(..)方法返回的标志 .

void readFlags(int flags) {
    switch (flags) {
        case START_FLAG_REDELIVERY:
        case START_FLAG_RETRY:
            // restarted by system, might be kill app form stack.
            break;

        default:
            // on regular startService call from client.
    }
}

并且 startID 非常清楚,每当你调用stopSelf时你应该用这个startID调用,所以如果服务有多个客户端的运行请求,那么它不会终止服务,它只会停止这个startID的工作 . 它是由系统生成的,无需操纵:) .

3. 但是如何管理这个startID来调用stopSelf仍然是一个问题?任何人 !!

1 回答

  • 1

    首先,文档明确表示不要自己调用这些方法,因此您可以在其他地方操作它们 .

    flags int:有关此启动请求的其他数据 . 值为0或START_FLAG_REDELIVERY或START_FLAG_RETRY的组合 .

    这些常量标志在同一页面中描述

    我不清楚输入来自哪里,但你将该整数与按位OR组合起来

    return flags | START_REDELIVER_INTENT;
    

    startId int:表示此特定启动请求的唯一整数 . 与stopSelfResult(int)一起使用 .

    因此,id用于记录并获取服务句柄以停止它

相关问题