суббота, 14 июля 2012 г.

Android autostart application

При старте устройства можно сделать что-то полезное :)

права

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Регистрация получателя


<receiver android:name="com.example.MyBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>


Получатель


package com.example;

public class MyBroadcastreceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, MyService.class);
        context.startService(startServiceIntent);
    }
}


Как проверить?


open console/terminal and navigating to /platform-tools
type "adb shell" or on linux/mac "./adb shell"
in the shell type "am broadcast -a android.intent.action.BOOT_COMPLETED" or whatever action you want to fire

Проблемы
Если стартовать activity, то иногда activity выкидывает nullPointerException при доступе к context или getExternalCacheDir.
Решение: Thread.sleep(1000); перед context.startService(startServiceIntent); в BroadcastReceiver.




Пример

https://github.com/commonsguy/cw-advandroid/tree/master/SystemEvents/OnBoot

Ссылки

http://stackoverflow.com/questions/7317939/android-autostart-application?rq=1

http://stackoverflow.com/questions/5051687/broadcastreceiver-not-receiving-boot-completed

Комментариев нет:

Отправить комментарий