Android(安卓)技巧 - 开机完成后做某事 (比如启动Service)
16lz
2021-12-04
It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...
It's quite simple. First give your app the permissionRECEIVE_BOOT_COMPLETED.
Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.
Your Manifest.xml should now look like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jjoe64"> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application> <receiver android:name=".BootCompletedIntentReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <service android:name=".BackgroundService"/> </application></manifest>
As the last step you have to implement the Receiver. This receiver just starts your background service.
package com.jjoe64;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.preference.PreferenceManager;import com.jjoe64.BackgroundService;public class BootCompletedIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent pushIntent = new Intent(context, BackgroundService.class); context.startService(pushIntent); } }}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer