【问题标题】:Achieve Partial wakelock inside asyncTask Class在 asyncTask 类中实现部分唤醒锁
【发布时间】: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)&lt;parent class&gt;.this.getSystemService(Context.POWER_SERVICE)
  • @Simon 这无关紧要,因为这完全是关于访问 AsyncTask 中的 Context 实例
  • 为什么不在onPreExecute方法中实现wakelock,在onPostExecute中释放。如果您在活动中将 AsyncTask 子类声明为静态类,则确实需要在类的构造函数中传递 Context 参数。但是如果你的类是非静态的,你就可以隐式访问活动类并且可以调用getSystemService
  • 您应该在构造函数中获取唤醒锁,因为设备可能会在到达 onPreExecute 之前进入睡眠状态。

标签: android android-asynctask android-wake-lock


【解决方案1】:

添加一个构造函数并从活动中传递上下文对象

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

然后使用

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

【讨论】:

    【解决方案2】:
    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    

    不会起作用,因为getSystemService() 不是AsyncTask 的方法。您需要将您的应用程序Context 对象传递给您的AsyncTask,然后执行以下操作,因为getSystemService()Context 的函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      相关资源
      最近更新 更多