0

I have an application that runs a long process. I am using AsyncTask class to achieve it. But when the phone sleeps the async task automatically stops. To stop this behaviour I want to achieve a partial wakelock when the doInBackgound starts and release it when it ends.

But when I paste the following code in doInBackground method, the getSystemService gives the error that it is undefined for the type myclass.

        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);

Can you gimme a workaround for this..

What I want to do is..

class doit extends AsyncTask<String, String , Void>
{
@Override
protected Void doInBackground(String... params) 
{
//Achieve Partial Wakelock
//Do long Work
//Release Lock
}
}
user1589754
  • 647
  • 2
  • 8
  • 20
  • 1
    http://stackoverflow.com/questions/9414588/android-context-and-context-powermanager – Simon Sep 17 '12 at 17:59
  • I have no way to test it right now, so this is more of a guess than anything (hence a comment instead of an answer): Try `(PowerManager).this.getSystemService(Context.POWER_SERVICE)` – Izkata Sep 17 '12 at 18:00
  • @Simon That is unrelated, since this is all about accessing a Context instance inside an AsyncTask – Izkata Sep 17 '12 at 18:01
  • why not to achieve wakelock in `onPreExecute` method and release it in `onPostExecute`. If you declare your AsyncTask subclass inside an activity as static class, you really need to pass Context parameter in constructor of your class. But if your class is non-static you have an implicit access to the activity class and can call `getSystemService` – grine4ka Mar 05 '14 at 12:40
  • You should grab the wake lock in the constructor as the device may go to sleep before it gets to onPreExecute. – dkneller May 13 '15 at 20:45

2 Answers2

1

Add a constructor and pass Context object from the activity

Context context;
doit(Context mContext){
    super();
    context = mContext;
}

Then use

    PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
nandeesh
  • 24,740
  • 6
  • 69
  • 79
1
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);

Will not work because getSystemService() is not a method of AsyncTask. You need to pass your applications Context object to your AsyncTask and then do the following since getSystemService() is a function of Context.

PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
Jug6ernaut
  • 8,219
  • 2
  • 26
  • 26