MMS发送流程(代码版)android_第1页
MMS发送流程(代码版)android_第2页
MMS发送流程(代码版)android_第3页
MMS发送流程(代码版)android_第4页
MMS发送流程(代码版)android_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、MMS发送流程(代码版)Android2.2packages/apps/Mms1.      点击发送按钮Src/com/android/mms/ui/ComposeMessageActivity.javapublic void onClick(View v)         if (v = mSendButton) && isPreparedForSending()        

2、0;    confirmSendMessageIfNeeded(); /确认是否需要发送短信-         2.src/com/android/mms/ui/ComposeMessageActivity.javaprivate void confirmSendMessageIfNeeded()         if (!isRecipientsEditorVisible()   /编辑联系人不可见时,

3、也就是给已存在会话的联系人发送短信时            sendMessage(true);            return;                 boolean isMms = mWorkingMessage

4、.requiresMms();   /是否需要以彩信形式发送                if (mRecipientsEditor.hasInvalidRecipient(isMms) /是否含有不合法的收件人            if (mRecipientsEditor.hasValidRecipient(i

5、sMms) /有合法的和不合法的,弹出尝试发送对话框                String title = getResourcesString(R.string.has_invalid_recipient,                   

6、0;    mRecipientsEditor.formatInvalidNumbers(isMms);                new AlertDialog.Builder(this)                   .set

7、Icon(android.R.drawable.ic_dialog_alert)                    .setTitle(title)                    .setMessage(R.

8、string.invalid_recipient_message)                   .setPositiveButton(R.string.try_to_send,                   

9、0;        newSendIgnoreInvalidRecipientListener()                   .setNegativeButton(R.string.no, new CancelSendingListener()        

10、            .show();            else /如果全是不合法的联系人,提示不能发送信息                new AlertDialog.Builder(this)  

11、                 .setIcon(android.R.drawable.ic_dialog_alert)                    .setTitle(R.string.cannot_send_message) 

12、;                   .setMessage(R.string.cannot_send_message_reason)                   .setPositiveButton(R.string.yes,

13、new CancelSendingListener()                    .show();                    else /判断收件人没有问题,接着发送信息 -  

14、0;         sendMessage(true);         3. src/com/android/mms/ui/ComposeMessageActivity.javaprivate void sendMessage(boolean bCheckEcmMode)     Log.v(TAG, "sendMessage");    &#

15、160;   if (bCheckEcmMode)             / TODO: expose this in telephony layer for SDK build            String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);&

16、#160;    /判断电话是否处于紧急拨号模式,得到的inEcm一般为空            Log.v(TAG, "inEcm = " + inEcm);            if (Boolean.parseBoolean(inEcm)        

17、;         try                     startActivityForResult(                  

18、          new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS,null),                            REQUEST_CODE

19、_ECM_EXIT_DIALOG);                    return;                catch (ActivityNotFoundException e)      

20、60;              / continue to send message                    Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e); 

21、                                            if (!mSendingMessage)      

22、0;      / send can change the recipients. Make sure we remove the listeners firstand then add            / them back once the recipient list has settled.           

23、removeRecipientsListeners();  /取消对收件人的监听            mWorkingMessage.send();   /发送信息-            mSentMessage = true;          

24、;  mSendingMessage = true;            addRecipientsListeners(); /重新添加收件人监听                / But bail out if we are supposed to exit after the message is sent.  

25、      if (mExitOnSent) /如果mExitOnSent为true,信息发送完成后退出Activity            finish();             4. src/com/android/mms/data/WorkingMessage.java/*   

26、0; * Send this message over the network.  Will call back with onMessageSent() once     * it has been dispatched to the telephonystack.  This WorkingMessage object is     * no longer useful after this method hasbeen called.     */&

27、#160;   public void send()         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)             LogTag.debug("send");            

28、60;    / Get ready to write to disk.        prepareForSave(true /* notify */);/主要做一下同步收件人和WorkingMessage,彩信时在准备其他一些东西         / We need the recipient list for both SMS and MMS.     

29、0;  final Conversation conv = mConversation;        String msgTxt = mText.toString();        Log.v(TAG, "msgText = " + msgTxt);        if (requiresMms()| addressContainsEmailToMms(

30、conv, msgTxt)             / Make local copies of the bits we need for sending a message,            / because we will be doing it off of the main thread, which will    &#

31、160;       / immediately continue on to resetting some of this state.            final Uri mmsUri = mMessageUri;   /如果第一次发送,此时mmsUri为null,如果是重发,则是草稿箱的地址 mMessageUri =content:/mms/drafts/1   

32、         final PduPersister persister = PduPersister.getPduPersister(mContext);             final SlideshowModel slideshow = mSlideshow;          

33、0; final SendReq sendReq = makeSendReq(conv,mSubject);             / Do the dirty work of sending the message off of the main UI thread.            new Thread(new Runnable()   

34、;              public void run()                     / Make sure the text in slide 0 is no longer holding onto a reference to  

35、60;                 / the text in the message text box.                    slideshow.prepareForSend();    

36、;                sendMmsWorker(conv, mmsUri, persister, slideshow, sendReq);                         

37、0;  ).start();        else             / Same rules apply as above.            final String msgText = mText.toString();/取出短消息    &

38、#160;       Log.v(TAG, "msgText = " + msgText);            new Thread(new Runnable()                 public void run()   

39、;                  preSendSmsWorker(conv, msgText);/发送信息-                           

40、).start();                 / update the Recipient cache with the new to address, if it's different        RecipientIdCache.updateNumbers(conv.getThreadId(),conv.getRecipients(); 

41、60;       / Mark the message as discarded because it is "off the market"after being sent.        mDiscarded = true;     5. src/com/android/mms/data/WorkingMessage.javaprivate void sendMmsWorker(Conversatio

42、n conv, Uri mmsUri, PduPersisterpersister, SlideshowModel slideshow, SendReq sendReq)     Log.v(TAG, "sendMmsWorker");        / If user tries to send the message, it's a signal the inputtedtext is what they wanted.   

43、0;    UserHappinessSignals.userAcceptedImeText(mContext);         / First make sure we don't have too many outstanding unsent message.        Cursor cursor = null;       

44、try             cursor = SqliteWrapper.query(mContext, mContentResolver,                    Mms.Outbox.CONTENT_URI,MMS_OUTBOX_PROJECTION, null, null,

45、null);            if (cursor != null) /如果MMS_OUTBOX里有未发送的彩信,并且总的大小已经超过了彩信的最大限制,则取消此次发送,并存入草稿箱              Log.v(TAG, "query Mms.Outbox.CONTENT_URI is not empty"); &

46、#160;              long maxMessageSize = MmsConfig.getMaxSizeScaleForPendingMmsAllowed()*                    MmsConfig.getMaxMessageSize();&

47、#160;               Log.v(TAG, "MmsConfig.getMaxSizeScaleForPendingMmsAllowed() =" + MmsConfig.getMaxSizeScaleForPendingMmsAllowed();              

48、60; Log.v(TAG, "MmsConfig.getMaxMessageSize()() = " + MmsConfig.getMaxMessageSize();                               long totalPendingSize = 0

49、;                while (cursor.moveToNext()                     totalPendingSize +=cursor.getLong(MMS_MESSAGE_SIZE_INDEX); &#

50、160;                  Log.v(TAG, "totalPendingSize = " + totalPendingSize);                      

51、60;         if (totalPendingSize >= maxMessageSize)                     unDiscard();    / itwasn't successfully sent. Allow it to be saved as a

52、 draft.                    mStatusListener.onMaxPendingMessagesReached();                    return; 

53、0;                          else              Log.v(TAG, "query Mms.Outbox.CONTENT_URI is empty"); &

54、#160;                  finally             if (cursor != null)                 cursor.clos

55、e();                            mStatusListener.onPreMessageSent();         / Make sure we are still using the correct thread ID for ou

56、r        / recipient set.        long threadId = conv.ensureThreadId();         if (Log.isLoggable(LogTag.APP, Log.VERBOSE)            

57、 LogTag.debug("sendMmsWorker: update draft MMS message " + mmsUri);                 if (mmsUri = null) /如果是首次发送,先把彩信保存入草稿箱            / Create a new MMS message

58、 if one hasn't been made yet.        Log.v(TAG, "mmsUri = null and startcreateDraftMmsMessage");            mmsUri = createDraftMmsMessage(persister,sendReq, slideshow);    

59、60;   else             / Otherwise, sync the MMS message in progress to disk.        Log.v(TAG, "mmsUri = " + mmsUri);        Log.v(TAG, "updateDraftM

60、msMessage");            updateDraftMmsMessage(mmsUri,persister, slideshow, sendReq);                 / Be paranoid and clean any draft SMS up.    

61、;    deleteDraftSmsMessage(threadId);         / Resize all the resizeable attachments (e.g. pictures) to fit        / in the remaining space in the slideshow.        int error

62、 = 0;        try             slideshow.finalResize(mmsUri);        catch (ExceedMessageSizeException e1)             err

63、or = MESSAGE_SIZE_EXCEEDED;        catch (MmsException e1)             error = UNKNOWN_ERROR;                if (error != 0)   

64、60;         markMmsMessageWithError(mmsUri);            mStatusListener.onAttachmentError(error);            return;     

65、0;           MessageSender sender = new MmsMessageSender(mContext, mmsUri,               slideshow.getCurrentMessageSize();        try   

66、60;         if (!sender.sendMessage(threadId)                 / The message was sent through SMS protocol, we should           

67、60;    / delete the copy which was previously saved in MMS drafts.                SqliteWrapper.delete(mContext, mContentResolver, mmsUri, null, null);          

68、;               / Make sure this thread isn't over the limits in message count            Recycler.getMmsRecycler().deleteOldMessagesByThreadId(mContext, threadId);  

69、      catch (Exception e)             Log.e(TAG, "Failed to send message: " + mmsUri + ",threadId=" + threadId, e);               

70、  mStatusListener.onMessageSent(); 6.src/com/android/mms/transaction/MmsMessageSender.javapublic boolean sendMessage(long token) throws MmsException         / Load the MMS from the message uri        PduPersister p = Pdu

71、Persister.getPduPersister(mContext);        GenericPdu pdu = p.load(mMessageUri);         if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_SEND_REQ)            throw n

72、ew MmsException("Invalid message: " +pdu.getMessageType();                 SendReq sendReq = (SendReq)pdu;         / Update headers.       

73、updatePreferencesHeaders(sendReq);         / MessageClass.        sendReq.setMessageClass(DEFAULT_MESSAGE_CLASS.getBytes();         / Update the 'date' field of the message befo

74、re sending it.        sendReq.setDate(System.currentTimeMillis()/ 1000L);               sendReq.setMessageSize(mMessageSize);         p.updateHeaders(mMess

75、ageUri, sendReq);         / Move the message into MMS Outbox        p.move(mMessageUri, Mms.Outbox.CONTENT_URI);         / Start MMS transaction service     

76、60;  SendingProgressTokenManager.put(ContentUris.parseId(mMessageUri), token);        mContext.startService(new Intent(mContext, TransactionService.class);         return true;     7.src/com/android/m

77、ms/transaction/TransactionService.javaOverride    public int onStartCommand(Intent intent, int flags, int startId)     Log.v(TAG, "onStartCommand");        if (intent = null)         &#

78、160;   return Service.START_NOT_STICKY;                mConnMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);        boolean noNetwork =!isNetworkAvailable();&#

79、160;        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)             Log.v(TAG, "onStart: #" + startId + ": " + intent.getExtras() + " intent=" + intent);   &

80、#160;        Log.v(TAG, "   networkAvailable=" + !noNetwork);                Log.v(TAG, "getAction is " + intent.getAction();      

81、0; if (ACTION_ONALARM.equals(intent.getAction()| (intent.getExtras() = null)         Log.v(TAG, "ACTION_ONALARM.equals(intent.getAction() |(intent.getExtras() = null)");            / Scan database to

82、find all pending operations.            Cursor cursor = PduPersister.getPduPersister(this).getPendingMessages(                    System.currentTimeMi

83、llis();            if (cursor != null)                 try                   

84、60; int count = cursor.getCount();                     if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)                

85、60;        Log.v(TAG, "onStart: cursor.count=" + count);                                  

86、       if (count = 0)                         if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)          

87、60;                  Log.v(TAG, "onStart: no pending messages. Stoppingservice.");                    

88、60;                           RetryScheduler.setRetryAlarm(this);                  &#

89、160;    stopSelfIfIdle(startId);                        return Service.START_NOT_STICKY;             

90、0;                           int columnIndexOfMsgId =cursor.getColumnIndexOrThrow(PendingMessages.MSG_ID);           

91、60;        int columnIndexOfMsgType =cursor.getColumnIndexOrThrow(                            PendingMessages.MSG_TYPE); 

92、0;                   if (noNetwork)                         / Make sure we register for connect

93、ion state changes.                        if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)                &

94、#160;            Log.v(TAG, "onStart: registerForConnectionStateChanges");                           

95、0;                    MmsSystemEventReceiver.registerForConnectionStateChanges(                     

96、          getApplicationContext();                                     

97、0;   while (cursor.moveToNext()                         int msgType =cursor.getInt(columnIndexOfMsgType);           

98、0;            int transactionType =getTransactionType(msgType);                        Log.v(TAG, "msgType = " + msgType

99、);                        Log.v(TAG, "transactionType = " + transactionType);                &#

100、160;       if (noNetwork)                            onNetworkUnavailable(startId, transactionType);      

101、0;                     return Service.START_NOT_STICKY;                         

102、                                              switch (transactionType) 

103、;                           case -1:                      &#

104、160;         break;                            case Transaction.RETRIEVE_TRANSACTION:      

105、0;                         / If it's a transiently failed transaction,                 

106、0;              / we should retry it in spite of current                              

107、;  / downloading mode.                                int failureType =cursor.getInt(         &

108、#160;                             cursor.getColumnIndexOrThrow(                &

109、#160;                              PendingMessages.ERROR_TYPE);               &#

110、160;                if (!isTransientFailure(failureType)                            &

111、#160;       break;                                           

112、;                     / fall-through                            d

113、efault:                                Uri uri =ContentUris.withAppendedId(           

114、0;                            Mms.CONTENT_URI,                    

115、;                   cursor.getLong(columnIndexOfMsgId);                          

116、;     TransactionBundle args = new TransactionBundle(                                      

117、; transactionType, uri.toString();                                / FIXME: We use the same startId for all MMs.     

118、0;                          launchTransaction(startId, args, false);                  

119、;              break;                                    

120、60;                       finally                     cursor.close();     &

121、#160;                      else                 if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)     &

122、#160;               Log.v(TAG, "onStart: no pending messages. Stoppingservice.");                        

123、        RetryScheduler.setRetryAlarm(this);                stopSelfIfIdle(startId);                  

124、0; else             if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)                 Log.v(TAG, "onStart: launch transaction.");     

125、;                   / For launching NotificationTransaction and test purpose.            TransactionBundle args = newTransactionBundle(intent.getExtras(); 

126、           launchTransaction(startId, args,noNetwork);                return Service.START_NOT_STICKY;     8. src/com/android/mms/transaction/TransactionService

127、.javaprivate void launchTransaction(int serviceId,TransactionBundle txnBundle, boolean noNetwork)     Log.v(TAG, "launchTransaction");        if (noNetwork)             Log.w(TAG, "

128、;launchTransaction: no network error!");            onNetworkUnavailable(serviceId,txnBundle.getTransactionType();            return;         

129、60;      Message msg = mServiceHandler.obtainMessage(EVENT_TRANSACTION_REQUEST);        msg.arg1 = serviceId;        msg.obj = txnBundle;         if (Log.isLoggable(

130、LogTag.TRANSACTION, Log.VERBOSE)             Log.v(TAG, "launchTransaction: sending message " + msg);                mServiceHandler.sendMessage(msg);  

131、60;  9. src/com/android/mms/transaction/TransactionService.javaprivate final class ServiceHandler extends Handler         public ServiceHandler(Looper looper)             super(looper);   &#

132、160;             /*         * Handle incoming transactionrequests.         * The incoming requests are initiatedby the MMSC Server or by the    &

133、#160;    * MMS Client itself.         */        Override        public void handleMessage(Messagemsg)             if (Lo

134、g.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)                 Log.v(TAG, "Handling incoming message: " + msg);                  &#

135、160;      Transaction transaction = null;             switch (msg.what)                 case EVENT_QUIT:      

136、              getLooper().quit();                    return;                 case EVENT_CONTINUE_MMS_CONNECTIVITY:                    synchronized (mProcessing)            

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论