歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中SMS的接收處理

Android中SMS的接收處理

日期:2017/3/1 10:29:57   编辑:Linux編程

在解析WAPPUSH over SMS時,看了一下Android裡SMS接收的流程,並按照自己需要的流程記錄,其他的分支處理並未講述。PDU數據的encode/decode並未解析,有興趣的讀者可以到相應的代碼處自己解讀一下。

Android中,RIL用RILReciever接收SMS pdu,並根據不同的信息類型用相應函數來處理。因手機制式的差異,用GsmSmsDispatcher或CdmaSmsDispatcher來做各自的消息處理並分發。最後的分發是通過發送相應的Broadcast,所以,對感興趣的消息處理,可以注冊Receiver來監聽相應的Broadcast,實現自己的SMS/MMS/Wap push,以及其他類型消息的接收處理。

RIL構造函數中,Receiver的初始化[在文件RIL.java中]

[java]
  1. mReceiver = newRILReceiver();
  2. mReceiverThread =new Thread(mReceiver, "RILReceiver");
  3. mReceiverThread.start();

其中的類型

  • mReceiver: RILReceiver
  • mReceiverThread: Thread

RILReceiver實現了Runnable


關注RILReceiver線程的實現[在RILReceiver::run()中]

[java]
  1. public void run() {
  2. int retryCount= 0;
  3. try {for (;;) {
  4. LocalSockets = null;
  5. LocalSocketAddress l;
  6. try {
  7. s = newLocalSocket();
  8. l = newLocalSocketAddress(SOCKET_NAME_RIL,
  9. LocalSocketAddress.Namespace.RESERVED);
  10. s.connect(l);
  11. } catch (IOException ex){
  12. // 。。。
  13. }
  14. retryCount= 0;
  15. mSocket =s;
  16. int length= 0;
  17. try {
  18. InputStreamis = mSocket.getInputStream();
  19. for(;;) {
  20. Parcel p;
  21. length = readRilMessage(is, buffer);
  22. if(length < 0) {
  23. // End-of-stream reached
  24. break;
  25. }
  26. p =Parcel.obtain();
  27. p.unmarshall(buffer, 0, length);
  28. p.setDataPosition(0);
  29. processResponse(p);
  30. p.recycle();
  31. }
  32. } catch(java.io.IOException ex) {
  33. // …
  34. } catch(Throwable tr) {
  35. // …
  36. }
  37. // …
  38. }} catch(Throwable tr) {
  39. Log.e(LOG_TAG,"Uncaught exception", tr);
  40. }
  41. }

RILReceiver線程不停的監聽本地Socket,讀到數據之後在processResponse()[Line#37]中處理。

[java]
  1. private void processResponse (Parcel p) {
  2. int type;
  3. type = p.readInt();
  4. if(type == RESPONSE_UNSOLICITED) {
  5. processUnsolicited (p);
  6. }else if (type == RESPONSE_SOLICITED) {
  7. processSolicited (p);
  8. }
  9. releaseWakeLockIfDone();
  10. }

如果類型屬於Unsolicited消息,則在processUnsolicited()中處理。收到的短信是屬於Unsolicited信息,看它的實現。

processUnsolicited()中很長的switch… case語句中對收到短信的處理在case RIL_UNSOL_RESPONSE_NEW_SMS:

[java]
  1. SmsMessage sms;
  2. sms = SmsMessage.newFromCMT(a);
  3. if (mSMSRegistrant != null) {
  4. mSMSRegistrant.notifyRegistrant(new AsyncResult(null, sms, null));
  5. }
Copyright © Linux教程網 All Rights Reserved