2012-10-26 29 views
0

我想在一個簡單的Android應用程序上工作,當設備插入,即通過碼頭,屏幕會喚醒鎖,以便屏幕不會關閉,不管他們使用什麼應用程序,並且在拔掉喚醒鎖時釋放。系統範圍的喚醒鎖定和釋放取決於電源連接

目前我沒有任何服務運行,因爲我認爲這是不需要的。它接收電源連接和電源斷開的廣播意圖。當電源連接時,它似乎成功獲得了喚醒鎖定,但當電源斷開時,它會嘗試釋放喚醒鎖定,但會拋出空指針異常。我猜測它是因爲應用程序不一定在運行,並且沒有服務,所以變量不會保留。

下面是我用來接收廣播的代碼。

public class BroadcastReceiveDetection extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     ManageScreenLight manageScreenLight = new ManageScreenLight(context); 
     String action = intent.getAction(); 

     if (action == Intent.ACTION_POWER_CONNECTED) 
     { 
      manageScreenLight.receivedPowerConnected(); 
     } 
     else if (action == Intent.ACTION_POWER_DISCONNECTED) 
     { 
      try { 
       manageScreenLight.receivedPowerDisconnected(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

下面是獲取和釋放喚醒鎖的代碼。

Context context; 
    PowerManager.WakeLock wakeLock; 
    public ManageScreenLight(Context context) 
    { 
     this.context = context; 
    } 

    public void receivedPowerConnected() 
    { 
     Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show(); 

     PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 
     wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay"); 
     wakeLock.acquire(); 
    } 

     public void receivedPowerDisconnected() throws IOException 
{ 
    try 
    { 
     Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show(); 
     wakeLock.release(); 
    } 
    catch (Exception ex) 
    { 
     Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show(); 
    } 
} 

有沒有一種方法,這可以工作,我會有需要是運行服務時喚醒鎖是獲得性的,一旦電源斷開的釋放並停止該服務。

感謝您提供的任何幫助。

回答

0

好吧,根據BroadcastReceiver文檔,看起來onReceive()不會在您的應用程序被終止時調用,這很有意義。如果Android只是致電onReceive(),Android將不會啓動您的應用程序。如果您想繼續接收/響應這些事件,則需要使用服務。