短信的接收流程应用层
1、源文件
这部分代码在packages/apps/Mms下,涉及的主要类: [plain] view plain copy- com.android.mms.transaction.PrivilegedSmsReceiver
- com.android.mms.transaction.SmsReceiver
- com.android.mms.transaction.SmsReceiverService
- com.android.mms.transaction.MessagingNotification
2、图解
短信接收的时序图:
注意:SeviceHandler是SmsReceiverService的内部类,SmsReceiver是PrivlegedSmsReceiver的父类; 3、详细分析
3.1 PrivilegedSmsReceiver到SmsReceiverService
1)PrivilegedSmsReceiver这个接收器从中间才能获取数据 PrivilegedSmsReceiver是一个广播接收器并且继承自SmsReceiver,在AndroidManifest.xml 中有如下声明: [plain] view plain copy- protected void dispatchPdus(byte[][] pdus) {
- Intent intent = new Intent(Intents.SMS_RECEIVED_ACTION);
- intent.putExtra("pdus", pdus);
- intent.putExtra("encoding", getEncoding());
- intent.putExtra("sub_id", mPhone.getSubscription()); //Subscription information to be passed in an intent
- dispatch(intent, "android.permission.RECEIVE_SMS");
- }
- void dispatch(Intent intent, String permission) {
- mWakeLock.acquire(WAKE_LOCK_TIMEOUT);
- mContext.sendOrderedBroadcast(intent, permission, mResultReceiver,
- this, Activity.RESULT_OK, null, null);
- }
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SMS_RECEIVED_ACTION =
- "android.provider.Telephony.SMS_RECEIVED";
- protected void onReceiveWithPrivilege(Context context, Intent intent, boolean privileged) {
- if (!privileged && (intent.getAction().equals(Intents.SMS_RECEIVED_ACTION)
- || intent.getAction().equals(Intents.SMS_CB_RECEIVED_ACTION))) {
- return;
- }
- intent.setClass(context, SmsReceiverService.class);
- intent.putExtra("result", getResultCode());
- beginStartingService(context, intent);
- }
- private final class ServiceHandler extends Handler {
- public ServiceHandler(Looper looper) {
- super(looper);
- }
- /**
- * Handle incoming transaction requests.
- * The incoming requests are initiated by the MMSC Server or by the MMS Client itself.
- */
- @Override
- public void handleMessage(Message msg) {
- int serviceId = msg.arg1;
- Intent intent = (Intent)msg.obj;
- if (intent != null) {
- String action = intent.getAction();
- int error = intent.getIntExtra("errorCode", 0);
- if (MESSAGE_SENT_ACTION.equals(intent.getAction())) {
- handleSmsSent(intent, error);
- } else if (SMS_RECEIVED_ACTION.equals(action)) {
- handleSmsReceived(intent, error);
- } else if (SMS_CB_RECEIVED_ACTION.equals(action)) {
- handleCbSmsReceived(intent, error);
- } else if (ACTION_BOOT_COMPLETED.equals(action)) {
- handleBootCompleted();
- } else if (TelephonyIntents.ACTION_SERVICE_STATE_CHANGED.equals(action)) {
- handleServiceStateChanged(intent);
- } else if (ACTION_SEND_MESSAGE.endsWith(action)) {
- handleSendMessage(intent);
- }
- }
- // NOTE: We MUST not call stopSelf() directly, since we need to
- // make sure the wake lock acquired by AlertReceiver is released.
- SmsReceiver.finishStartingService(SmsReceiverService.this, serviceId);
- }
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- mResultCode = intent != null ? intent.getIntExtra("result", 0) : 0;
- Message msg = mServiceHandler.obtainMessage();
- msg.arg1 = startId;
- msg.obj = intent;
- mServiceHandler.sendMessage(msg);
- return Service.START_NOT_STICKY;
- }

说 明在insertMessage方法时会判断当前是替换还是插入,对于替换短信,笔者不是很清楚在什么情况下会走这条路。 blockingUpdateNewMessageIndicator方法会用notification提醒用户,并且在方法内会判断当前用户是否需要显 示发送报告。
3.2 刷新会话列表
走到上面的代码,短信已经入库,但界面的刷新是如何实现的了? 1)会话列表的初始化 ConversationList继承自ListActivity,用于显示短信的会话列表,在该类的onStart方法里有调用了一个重要的方法startAsyncQuery()方法: [plain] view plain copy- private void startAsyncQuery() {
- try {
- setTitle(getString(R.string.refreshing));
- setProgressBarIndeterminateVisibility(true);
- Conversation.startQueryForAll(mQueryHandler, THREAD_LIST_QUERY_TOKEN);
- } catch (SQLiteException e) {
- SqliteWrapper.checkSQLiteException(this, e);
- }
- }
- public static void startQueryForAll(AsyncQueryHandler handler, int token) {
- handler.cancelOperation(token);
- handler.startQuery(token, null, sAllThreadsUri,
- ALL_THREADS_PROJECTION, null, null, Conversations.DEFAULT_SORT_ORDER);
- }
- private final class ThreadListQueryHandler extends AsyncQueryHandler {
- public ThreadListQueryHandler(ContentResolver contentResolver) {
- super(contentResolver);
- }
- @Override
- protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
- switch (token) {
- case THREAD_LIST_QUERY_TOKEN:
- mListAdapter.changeCursor(cursor);
- setTitle(mTitle);
- setProgressBarIndeterminateVisibility(false);
- if (mNeedToMarkAsSeen) {
- mNeedToMarkAsSeen = false;
- Conversation.markAllConversationsAsSeen(getApplicationContext());
- // Database will be update at this time in some conditions.
- // Wait 1s and ensure update complete.
- mQueryHandler.postDelayed(new Runnable() {
- public void run() {
- // Delete any obsolete threads. Obsolete threads are threads that aren't
- // referenced by at least one message in the pdu or sms tables.
- Conversation.asyncDeleteObsoleteThreads(mQueryHandler,
- DELETE_OBSOLETE_THREADS_TOKEN);
- }
- }, 1000);
- }
- break;
- default:
- Log.e(TAG, "onQueryComplete called with unknown token " + token);
- }
- }
- }
- private void initListAdapter() {
- mListAdapter = new ConversationListAdapter(this, null);
- mListAdapter.setOnContentChangedListener(mContentChangedListener);
- setListAdapter(mListAdapter);
- getListView().setRecyclerListener(mListAdapter);
- }
- private final ConversationListAdapter.OnContentChangedListener mContentChangedListener =
- new ConversationListAdapter.OnContentChangedListener() {
- public void onContentChanged(ConversationListAdapter adapter) {
- startAsyncQuery();
- }
- };
2)会话列表的更新
看到上面监听器所做的工作大家应该明白啦,会话列表的更新靠的就是这个监听器,当内容发生改变就会重新查询,界面进行刷新,到此为止 短信的界面刷新完成。 特 别注意:该情况是用户在短信会话列表这个界面,如果不在这个界面大概还有其他两种情况: 1、在某个会话中;2、没有进入mms程序。对于前一种情况会在下面继续分析,对于后一种情况我想也不用多说在这种情况下会走activity的声明周期 函数,在onstart方法里进行查询显示前面已经提到。那还有一种特殊的情况就是在从某个会话中返回到会话列表时的处理。下面请看ConversationList的声明:
[plain] view plain copy
-
- android:label="@string/app_label"
- android:configChanges="orientation|keyboardHidden"
- android:launchMode="singleTop">
- @Override
- protected void onNewIntent(Intent intent) {
- // Handle intents that occur after the activity has already been created.
- startAsyncQuery();
- }
3.23刷新会话内容
刷新ui除了刷新会话列表之外,还有一种情况就是当用户在某个会话时,这时该会话接收到新的消息,这时需要刷新会话的内容,这是怎么实现的? 用于会话显示的activity:ComposeMessageActivity;用于显示会话的短信内容组件: MessageListView;填充listview的adapter是:MessageListAdapter 1)初始化 ComposeMessageActivity的onCreate方法调用initialize方法,initialize方法再调用initMessageList()完成初始化 [plain] view plain copy- private void initMessageList() {
- if (mMsgListAdapter != null) {
- return;
- }
- String highlightString = getIntent().getStringExtra("highlight");
- Pattern highlight = highlightString == null
- ? null
- : Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE);
- // Initialize the list adapter with a null cursor.
- mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight);
- mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
- mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler);
- mMsgListView.setAdapter(mMsgListAdapter);
- mMsgListView.setItemsCanFocus(false);
- mMsgListView.setVisibility(View.VISIBLE);
- mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener);
- mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- public void onItemClick(AdapterView> parent, View view, int position, long id) {
- if (view != null) {
- ((MessageListItem) view).onMessageListItemClick();
- }
- }
- });
- }
- private final MessageListAdapter.OnDataSetChangedListener
- mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() {
- public void onDataSetChanged(MessageListAdapter adapter) {
- mPossiblePendingNotification = true;
- }
- public void onContentChanged(MessageListAdapter adapter) {
- startMsgListQuery();
- }
- };
- private void startMsgListQuery() {
- Uri conversationUri = mConversation.getUri();
- if (conversationUri == null) {
- return;
- }
- if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
- log("for " + conversationUri);
- }
- // Cancel any pending queries
- mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN);
- try {
- // Kick off the new query
- mBackgroundQueryHandler.startQuery(
- MESSAGE_LIST_QUERY_TOKEN, null, conversationUri,
- PROJECTION, null, null, null);
- } catch (SQLiteException e) {
- SqliteWrapper.checkSQLiteException(this, e);
- }
- }
- @Override
- protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
- switch(token) {
- case MESSAGE_LIST_QUERY_TOKEN:
- // Set last sub used in this conversation thread.
- if (cursor.getCount() > 0) {
- cursor.moveToLast();
- mLastSubInConv = cursor.getInt(COLUMN_SUB_ID); //TODO: ADD SUBSCRIPION HERE
- cursor.moveToPosition(-1);
- } else {
- mLastSubInConv = SUBSCRIPTION_ID_INVALID;
- }
- int newSelectionPos = -1;
- long targetMsgId = getIntent().getLongExtra("select_id", -1);
- if (targetMsgId != -1) {
- cursor.moveToPosition(-1);
- while (cursor.moveToNext()) {
- long msgId = cursor.getLong(COLUMN_ID);
- if (msgId == targetMsgId) {
- newSelectionPos = cursor.getPosition();
- break;
- }
- }
- }
- mMsgListAdapter.changeCursor(cursor);
- if (newSelectionPos != -1) {
- mMsgListView.setSelection(newSelectionPos);
- }
- if (cursor.getCount() == 0 && !isRecipientsEditorVisible() && !mSentMessage) {
- initRecipientsEditor();
- }
- mTextEditor.requestFocus();
- mConversation.blockMarkAsRead(false);
- mConversation.setMessageCount(cursor.getCount());
- return;
- }
- }
4、总结
短信的接收大致过程就是这样,对于上面提到的替换短信,该情况暂时不清楚,有些细节描述的很粗糙,希望大家多提意见,一起研究研究本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
