Reputation: 21
I have a Main activity, which can start a service using this command
startService(new Intent(Main.this, Myservice.class));
and Myservice class is like this
public class Myservice extends Service {
private ShakeListener mShaker;
String startell;
SharedPreferences prefs;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
//Something
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
//Do Something to detecting shake
//Show my notification
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
//Stop Shake detection
//stop notification
super.onDestroy();
}
}
and my applications works fine, but after about one hour, service stops automatically, i mean after about one hour shake detection dose not work any more. :(
I googled a bit and I found I should use StartForeground, but I didn't find how.
Now, how should I use StartForeground in my code?
Upvotes: 2
Views: 5650
Reputation: 691
Code to Acquire & Release Lock
//acquire wake lock in onCreate() Method
devicePowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = devicePowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass().getName());
if(wakeLock != null){
if(wakeLock.isHeld() == false){
wakeLock.acquire();
}
}
//release wake lock in onDestroy() Method
if (wakeLock != null) {
if(wakeLock.isHeld()){
wakeLock.release();
wakeLock = null;
}
}
Upvotes: 1
Reputation: 3915
I think you service stop working because of your device going to sleep. If you want it to work in background all the time you can use WakeLock to prevent you device from sleeping, BUT this will significantly increase battery consumption, so be carefull with it.
EDIT: You can set()
lock in onCreate
methond of your Service
and release()
it in onDestroy()
Upvotes: 0
Reputation: 10620
Yes, you can start service by calling startService
method. And go through this example, it will help you
Upvotes: 0