我正在傾聽連接和解除星系的電源。電源連接和斷開的聽衆
我創造了2個BroadCastReceivers,一個用於連接,另一個用於斷開連接。
當我嘗試實施時,即使斷開電源線,我也只能獲得連接的數據。
意圖被髮送,但看起來是錯誤的。
這裏是活動的代碼:
// Handle Power On
PowerConnectedBCReceiver myPowerConnectedBCReceiver = new PowerConnectedBCReceiver();
IntentFilter intentPowerOnFilter = new IntentFilter();
intentPowerOnFilter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
registerReceiver(myPowerConnectedBCReceiver, intentPowerOnFilter);
BroadcastReceiver PowerConnectedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
showToast("connected");
}
};
// Handle Power Off
PowerConnectedBCReceiver myPowerDisonnectedBCReceiver = new PowerConnectedBCReceiver();
IntentFilter intentPowerDisconnectedOnFilter = new IntentFilter();
intentPowerDisconnectedOnFilter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(myPowerDisonnectedBCReceiver, intentPowerDisconnectedOnFilter);
BroadcastReceiver PowerDisconnectedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
showToast("disconnected");
}
};
註冊兩個BC做工作
registerReceiver(PowerDisconnectedReceiver, new IntentFilter("com.neglected.POWER_DISCONNECTED"));
registerReceiver(PowerConnectedReceiver, new IntentFilter("com.neglected.POWER_CONNECTED"));
廣播連接代碼:
public class PowerConnectedBCReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Phone was connected to power" , Toast.LENGTH_LONG).show();
Intent tIntent = new Intent("com.neglected.POWER_CONNECTED");
context.sendBroadcast(tIntent);
}
}
廣播斷開Ç頌:
public class PowerDisconnectedBCReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Phone was disconnected from power" , Toast.LENGTH_LONG).show();
Intent tIntent = new Intent("com.neglected.POWER_DISCONNECTED");
context.sendBroadcast(tIntent);
}
}
是代碼錯了嗎? 我可以聽兩個動作嗎? seperately? 我看不到額外與CONNNECTED Action一起發送,是嗎?
謝謝,現在,我要他們做的就是Toast調試。謝謝。這個想法是我在我的Activity中有一個複選框,當更改狀態時,它應該在我的服務中註冊/註銷廣播監聽器。 *在我將它推到我的服務之前,我希望看到它在活動中有效。 – Saariko
感謝鏈接michal。我讀過它,而我的「不良」行爲就是在連接和斷開電話時收到CONNECTED事件。我會繼續尋找。再次感謝 – Saariko