【发布时间】:2012-09-17 17:54:55
【问题描述】:
我有一个运行很长进程的应用程序。我正在使用 AsyncTask 类来实现它。但是当手机休眠时,异步任务会自动停止。 为了阻止这种行为,我想在 doInBackgound 启动时实现部分唤醒锁,并在它结束时释放它。
但是当我在 doInBackground 方法中粘贴以下代码时,getSystemService 会给出错误,即它未定义类型 myclass。
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
你能给我一个解决方法吗..
我想做的是..
class doit extends AsyncTask<String, String , Void>
{
@Override
protected Void doInBackground(String... params)
{
//Achieve Partial Wakelock
//Do long Work
//Release Lock
}
}
【问题讨论】:
-
我现在无法测试它,所以这更像是一个猜测(因此是评论而不是答案):试试
(PowerManager)<parent class>.this.getSystemService(Context.POWER_SERVICE) -
@Simon 这无关紧要,因为这完全是关于访问 AsyncTask 中的 Context 实例
-
为什么不在
onPreExecute方法中实现wakelock,在onPostExecute中释放。如果您在活动中将 AsyncTask 子类声明为静态类,则确实需要在类的构造函数中传递 Context 参数。但是如果你的类是非静态的,你就可以隐式访问活动类并且可以调用getSystemService -
您应该在构造函数中获取唤醒锁,因为设备可能会在到达 onPreExecute 之前进入睡眠状态。
标签: android android-asynctask android-wake-lock