2013-04-25 97 views
-1

我想開發一個android服務,知道是否有任何通知,然後採取行動。我不知道如何管理通知。
我想知道通知如何工作,以及如何傾聽他們。如何通過服務處理通知?

+0

什麼y你的意思是「聽通知」?你的意思是你想要某種服務以某種方式讀取通知並對其採取行動? – ravemir 2013-04-25 18:23:37

+0

另外,你知道你想採取哪些通知嗎?也許有一種解決方法可以更好地滿足您的需求,您可能不得不使用繁瑣的可訪問性服務並要求用戶使用它,這一直是可疑的。 – ravemir 2013-04-25 18:26:18

+0

Alread閱讀這個或你的意思是什麼樣的通知? https://developer.android.com/guide/topics/ui/notifiers/notifications.html – luxer 2013-04-25 18:27:34

回答

0

this answer中所述,您應該使用BroadcastReceiver捕獲適當的意圖並執行您的預期操作。

你提到的一個例子是,接收短信應觸發LED指示燈。如前所述here,你應該註冊你的 'SMSReceiver' 廣播接收器,像這樣:

// SMS Receiver 
<receiver android:name="com.myexample.receivers.SMSReceiver" > 
    <intent-filter> 
     <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter> 
</receiver> 

...而有所界定,像這樣的代碼:

public class SMSReceiver extends BroadcastReceiver { 
private final String DEBUG_TAG = getClass().getSimpleName().toString(); 
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; 
private Context mContext; 
private Intent mIntent; 

// Retrieve SMS 
public void onReceive(Context context, Intent intent) { 
    mContext = context; 
    mIntent = intent; 

    String action = intent.getAction(); 

    if(action.equals(ACTION_SMS_RECEIVED)){ 

     String address, str = ""; 
     int contactId = -1; 

     SmsMessage[] msgs = getMessagesFromIntent(mIntent); 

     // Iterate over the received messages with a loop, 
     // performing the desired actions during the process 
    } 

} 

public static SmsMessage[] getMessagesFromIntent(Intent intent) { 
    Object[] messages = (Object[]) intent.getSerializableExtra("pdus"); 
    byte[][] pduObjs = new byte[messages.length][]; 

    for (int i = 0; i < messages.length; i++) { 
     pduObjs[i] = (byte[]) messages[i]; 
    } 
    byte[][] pdus = new byte[pduObjs.length][]; 
    int pduCount = pdus.length; 
    SmsMessage[] msgs = new SmsMessage[pduCount]; 
    for (int i = 0; i < pduCount; i++) { 
     pdus[i] = pduObjs[i]; 
     msgs[i] = SmsMessage.createFromPdu(pdus[i]); 
    } 
    return msgs; 
} 

}

...作爲LED的問題,大多數報道似乎粗略,但this answer有一個躲閃避難所變通辦法:

android.provider.Settings.System.putInt(context.getContentResolver(), 
    "notification_light_pulse", on ? 1 : 0);