首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >启动服务时立即启动java android

启动服务时立即启动java android
EN

Stack Overflow用户
提问于 2017-08-02 07:26:35
回答 1查看 1.3K关注 0票数 1

我在应用程序中使用服务来锁定状态条。

此服务是粘性的,并在启动启动时运行。

但是我的服务在2-5秒后启动并启动(在启动时)。

这一次我能减一点吗?

EN

回答 1

Stack Overflow用户

发布于 2017-08-02 07:30:46

代码语言:javascript
复制
public class BroadcastReceiverOnBootComplete extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class);
            context.startService(serviceIntent);
        }
    }
}

服务

代码语言:javascript
复制
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class AndroidServiceStartOnBoot extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
       // here you can add whatever you want this service to do
    }

}

AndroidManifest.xml

代码语言:javascript
复制
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

<receiver
        android:name=".BroadcastReceiverOnBootComplete"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_REPLACED" />
            <data android:scheme="package" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_ADDED" />
            <data android:scheme="package" />
        </intent-filter>
    </receiver>

    <service android:name=".AndroidServiceStartOnBoot"></service>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45454177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档