user1204863
user1204863

Reputation: 1

Keep My App alive - Android

I'm trying to make an App on Android 2.2 that has to run whether the screen is on or off.

I tried realizing it via a Service, but when my phone turns the screen off the service stopps working and I don't understand why.

In my Application I use

startService(new Intent(this, MyService.class));

when the User presses a button

and

Notification notification = new Notification();
startForeground(1, notification);

in the onCreate-Method of the Service class

(I tried it within the onStart() Method, too)

(I also could not find out what the id-field of startForeground() expects so I used the 1)

The service then should start an infinite vibration pattern of the phone so I know whether it is running or not. But when I turn off the screen, the phone stops vibration immediately

Please help me. I don't know how I can fix that (and google was not a big help)

Sincerely zed

Upvotes: 0

Views: 3092

Answers (3)

lofcian
lofcian

Reputation: 35

try this

KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); 
    final KeyguardManager.KeyguardLock kl = km .newKeyguardLock("MyKeyguardLock"); 
    kl.disableKeyguard(); 

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
    WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                                     | PowerManager.ACQUIRE_CAUSES_WAKEUP
                                     | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
    wakeLock.acquire();

and in manifest file

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

so when your notification or alarm manager service running, screen will light on and the keyguard will unlock.I wish it works for who has this problem too.

Upvotes: 0

barry
barry

Reputation: 4147

Try returning 'START_STICKY' from 'onStartCommand() '. This will keep the service running, restarting it if necessary, without keeping the screen on.

Have a look at http://developer.android.com/reference/android/app/Service.html#START_STICKY

Upvotes: 0

Mariusz Jamro
Mariusz Jamro

Reputation: 31653

Android devices go to a sleep mode when idle (e.g. when the screen is off), in order to conserve the battery.

To keep your service running you need to aquire a WakeLock. There are plenty of tutorials how to use it, like this one.

Note that having a service running all the time will drain your battery. Also make absolutely sure to release the wakelock when not needed, otherwise you're phone will always be awake.

Upvotes: 1

Related Questions