-1

我正在尝试开发一个知道是否有任何通知然后采取行动的android服务。我不知道如何管理通知。
我想知道通知是如何工作的,以及如何收听它们。

4

1 回答 1

0

本答案中所述,您应该使用 BroadcastReceiver 来捕获适当的意图并执行您的预期操作。

您提到作为示例,接收 SMS 消息应触发 LED 灯。如此处所述,您应该像这样注册您的“SMSReceiver”BroadcastReceiver:

// 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 问题,大多数报告似乎很粗略,但这个答案有一个狡猾的解决方法:

android.provider.Settings.System.putInt(context.getContentResolver(),
    "notification_light_pulse", on ? 1 : 0);
于 2013-04-25T18:57:04.147 回答