简体   繁体   English

在启动和 PreferenceChange 时启动 Android 服务

[英]Starting Android Service on boot and PreferenceChange

As my code looks today, I'm periodically sending a alarm(?) using AlarmManager that is received by AlarmReceiver extends BroadcastReceiver which in turn starts a Service.正如我今天的代码所示,我使用AlarmManager接收的AlarmReceiver extends BroadcastReceiver进而启动服务。 The Service do some updating and ends with a stopSelf() .服务进行一些更新并以stopSelf()结束。 IMO this is the best way of periodically perfom a task without constantly having a Service running. IMO 这是定期执行任务而无需不断运行服务的最佳方式。 Correct?正确的?

The issue with this code is however that the whole chain of events is initiated onSharedPreferenceChanged() .然而,这段代码的问题是整个事件链都是由onSharedPreferenceChanged()启动的。 I (initially) thought this was a good idea since the whole updating thing is enabled by the user in SharedPreferences .我(最初)认为这是一个好主意,因为整个更新都是由用户在SharedPreferences中启用的。 I've now come to the conclusion that this is in fact not very good and that I need to initiate the AlarmManager/AlarmReceiver/Service/whatever both onPreferenceChange but also on boot.我现在得出的结论是,这实际上不是很好,我需要在 onPreferenceChange 和启动时启动 AlarmManager/ onPreferenceChange /Service/whatever。

I've done some searching but everyone seems to want to start the Service on boot.我做了一些搜索,但每个人似乎都想在启动时启动服务。 As I see it, I just need to initiate the AlarmManager which will then start the Service (when needed and only periodically).正如我所看到的,我只需要启动AlarmManager ,然后它会启动服务(在需要时并且仅定期启动)。

Please help me with, first of all, sorting this out and secondly coding it!请先帮我整理一下,然后再编码! Thanks in advance!提前致谢!

Then, create and register a BroadcastReceiver where you will do the AlarmManager stuff:然后,创建并注册一个BroadcastReceiver ,您将在其中执行AlarmManager的内容:

public class YourBootReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        // do the AlarmManager here
    }
}

Then, on your manifest:然后,在您的清单上:

<application>
    ... other stuff
    <receiver android:name=".YourBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM