广播接收器中的WakeLock采集问题

时间:2013-03-03 08:33:57

标签: android

我正在开发一个应用程序,我需要一个广播接收器来生成通知 接收来自GCM推送的消息。

我正在使用的代码拒绝编译,说明

   "Cannot make a static reference to the non-static method acquire() from
  the type PowerManager.Wakelock"

IDE(eclipse)现在建议我应该

 remove argument to match "acquire()"

但是,当我这样做时,显示的下一个错误是:

 The method acquire(long) in the type PowerManager.WakeLock is not applicable        
  for the arguements(Context)....

广播接收器的代码是:

   private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);

    WakeLock.acquire(getApplicationContext());



    // Showing received message
    lblMessage.append(newMessage + "\n");
    Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

    // Releasing wake lock
    WakeLock.release();
}

我在哪里错过了?

1 个答案:

答案 0 :(得分:3)

  

如何在broadcastReceiver中获取唤醒锁。?

private PowerManager.WakeLock wakeLock;  //Declaration of Instance variable.

@Override
public void onReceive(Context context, Intent intent) {
    //......Code.....
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP 
                       | PowerManager.ON_AFTER_RELEASE,"Wake Lock");
    wakeLock.acquire(15*1000);
    //......Code....
}

在AndroidManifest.xml中添加权限

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