天天看點

[置頂] android 實作發送彩信方法 (MMS),非調用系統彩信界面

5進制-android技術開發部落格

最近有個需求,不去調用系統界面發送彩信功能。做過發送短信功能的同學可能第一反應是這樣:

不使用 StartActivity,像發短信那樣,調用一個類似于發短信的方法

SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage(phoneCode, null, text, null, null);

可以實作嗎? 答案是否定的,因為android上根本就沒有提供發送彩信的接口,如果你想發送彩信,對不起,請調用系統彩信app界面,如下:

[java] view plain copy print ?

  1. Intent sendIntent = new Intent(Intent.ACTION_SEND, Uri.parse("mms://"));
  2. sendIntent.setType("image/jpeg");
  3. String url = "file://sdcard//tmpPhoto.jpg";
  4. sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
  5. startActivity(Intent.createChooser(sendIntent, "MMS:"));
Intent sendIntent = new Intent(Intent.ACTION_SEND,  Uri.parse("mms://"));
	    sendIntent.setType("image/jpeg");
	    String url = "file://sdcard//tmpPhoto.jpg";
	    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
	    startActivity(Intent.createChooser(sendIntent, "MMS:"));
           

第一步:先構造出你要發送的彩信内容,即建構一個pdu,需要用到以下幾個類,這些類都是從android源碼的MMS應用中mms.pdu包中copy出來的。你需要将pdu包中的所有類

都拷貝到你的工程中,然後自己酌情調通。      
[java] 
    view plain
    copy
    print
    ?
   
  
          
  1. final SendReq sendRequest = new SendReq ();
  2. final PduBody pduBody = new PduBody();
  3. final PduPart part = new PduPart();//存放附件,每個附件是一個part,如果添加多個附件,就想body中add多個part。
  4. pduBody.addPart(partPdu);
  5. sendRequest.setBody(pduBody);
  6. final PduComposer composer = new PduComposer(ctx, sendRequest);
  7. final byte[] bytesToSend = composer.make(); //将彩信的内容以及主題等資訊轉化成byte數組,準備通過http協定發送到 "http://mmsc.monternet.com";
final SendReq sendRequest = new SendReq ();
   final PduBody pduBody = new PduBody();
final PduPart part = new PduPart();//存放附件,每個附件是一個part,如果添加多個附件,就想body中add多個part。
   pduBody.addPart(partPdu);
   sendRequest.setBody(pduBody);
   final PduComposer composer = new PduComposer(ctx, sendRequest);
final byte[] bytesToSend = composer.make(); //将彩信的内容以及主題等資訊轉化成byte數組,準備通過http協定發送到 "http://mmsc.monternet.com";
           
第二步:發送彩信到彩信中心。      
建構pdu的代碼:      
[java] 
     view plain
     copy
     print
     ?
    
   
           
  1. String subject = "測試彩信";
  2. String recipient = "接收彩信的号碼";//138xxxxxxx
  3. final SendReq sendRequest = new SendReq();
  4. final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
  5. if (sub != null && sub.length > 0) {
  6. sendRequest.setSubject(sub[0]);
  7. }
  8. final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipient);
  9. if (phoneNumbers != null && phoneNumbers.length > 0) {
  10. sendRequest.addTo(phoneNumbers[0]);
  11. }
  12. final PduBody pduBody = new PduBody();
  13. final PduPart part = new PduPart();
  14. part.setName("sample".getBytes());
  15. part.setContentType("image/png".getBytes());
  16. String furl = "file://mnt/sdcard//1.jpg";
  17. final PduPart partPdu = new PduPart();
  18. partPdu.setCharset(CharacterSets.UTF_8);//UTF_16
  19. partPdu.setName(part.getName());
  20. partPdu.setContentType(part.getContentType());
  21. partPdu.setDataUri(Uri.parse(furl));
  22. pduBody.addPart(partPdu);
  23. sendRequest.setBody(pduBody);
  24. final PduComposer composer = new PduComposer(ctx, sendRequest);
  25. final byte[] bytesToSend = composer.make();
  26. Thread t = new Thread(new Runnable() {
  27. @Override
  28. public void run() {
  29. try {
  30. HttpConnectInterface.sendMMS(ctx, bytesToSend);
  31. //
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. });
  37. t.start();
  38. 發送pdu到彩信中心的代碼:
  39. public static String mmscUrl = "http://mmsc.monternet.com";
  40. // public static String mmscUrl = "http://www.baidu.com/";
  41. public static String mmsProxy = "10.0.0.172";
  42. public static String mmsProt = "80";
  43. private static String HDR_VALUE_ACCEPT_LANGUAGE = "";
  44. // Definition for necessary HTTP headers.
  45. private static final String HDR_KEY_ACCEPT = "Accept";
  46. private static final String HDR_KEY_ACCEPT_LANGUAGE = "Accept-Language";
  47. private static final String HDR_VALUE_ACCEPT =
  48. "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic";
  49. public static byte[] sendMMS(Context context, byte[] pdu)throws IOException{
  50. HDR_VALUE_ACCEPT_LANGUAGE = getHttpAcceptLanguage();
  51. if (mmscUrl == null) {
  52. throw new IllegalArgumentException("URL must not be null.");
  53. }
  54. HttpClient client = null;
  55. try {
  56. // Make sure to use a proxy which supports CONNECT.
  57. client = HttpConnector.buileClient(context);
  58. HttpPost post = new HttpPost(mmscUrl);
  59. //mms PUD START
  60. ByteArrayEntity entity = new ByteArrayEntity(pdu);
  61. entity.setContentType("application/vnd.wap.mms-message");
  62. post.setEntity(entity);
  63. post.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
  64. post.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);
  65. //mms PUD END
  66. HttpParams params = client.getParams();
  67. HttpProtocolParams.setContentCharset(params, "UTF-8");
  68. HttpResponse response = client.execute(post);
  69. LogUtility.showLog(tag, "111");
  70. StatusLine status = response.getStatusLine();
  71. LogUtility.showLog(tag, "status "+status.getStatusCode());
  72. if (status.getStatusCode() != 200) { // HTTP 200 is not success.
  73. LogUtility.showLog(tag, "!200");
  74. throw new IOException("HTTP error: " + status.getReasonPhrase());
  75. }
  76. HttpEntity resentity = response.getEntity();
  77. byte[] body = null;
  78. if (resentity != null) {
  79. try {
  80. if (resentity.getContentLength() > 0) {
  81. body = new byte[(int) resentity.getContentLength()];
  82. DataInputStream dis = new DataInputStream(resentity.getContent());
  83. try {
  84. dis.readFully(body);
  85. } finally {
  86. try {
  87. dis.close();
  88. } catch (IOException e) {
  89. Log.e(tag, "Error closing input stream: " + e.getMessage());
  90. }
  91. }
  92. }
  93. } finally {
  94. if (entity != null) {
  95. entity.consumeContent();
  96. }
  97. }
  98. }
  99. LogUtility.showLog(tag, "result:"+new String(body));
  100. return body;
  101. } catch (IllegalStateException e) {
  102. LogUtility.showLog(tag, "",e);
  103. // handleHttpConnectionException(e, mmscUrl);
  104. } catch (IllegalArgumentException e) {
  105. LogUtility.showLog(tag, "",e);
  106. // handleHttpConnectionException(e, mmscUrl);
  107. } catch (SocketException e) {
  108. LogUtility.showLog(tag, "",e);
  109. // handleHttpConnectionException(e, mmscUrl);
  110. } catch (Exception e) {
  111. LogUtility.showLog(tag, "",e);
  112. //handleHttpConnectionException(e, mmscUrl);
  113. } finally {
  114. if (client != null) {
  115. // client.;
  116. }
  117. }
  118. return new byte[0];
  119. }
String subject = "測試彩信";
		    String recipient = "接收彩信的号碼";//138xxxxxxx
		    final SendReq sendRequest = new SendReq();
		    final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
		    if (sub != null && sub.length > 0) {
		    	sendRequest.setSubject(sub[0]);
		    }
		    final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipient);
		    if (phoneNumbers != null && phoneNumbers.length > 0) {
		    	sendRequest.addTo(phoneNumbers[0]);
		    }
		    final PduBody pduBody = new PduBody();
		    final PduPart part = new PduPart();
		    part.setName("sample".getBytes());
		    part.setContentType("image/png".getBytes());
		    String furl = "file://mnt/sdcard//1.jpg";

		    		final PduPart partPdu = new PduPart();
		    		partPdu.setCharset(CharacterSets.UTF_8);//UTF_16
		    		partPdu.setName(part.getName());
		    		partPdu.setContentType(part.getContentType());
		    		partPdu.setDataUri(Uri.parse(furl));
		    		pduBody.addPart(partPdu);   

		    sendRequest.setBody(pduBody);
		    final PduComposer composer = new PduComposer(ctx, sendRequest);
		    final byte[] bytesToSend = composer.make();

		    Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						HttpConnectInterface.sendMMS(ctx,  bytesToSend);
//
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		    t.start();
發送pdu到彩信中心的代碼:
        public static String mmscUrl = "http://mmsc.monternet.com";
//	public static String mmscUrl = "http://www.baidu.com/";
	public static String mmsProxy = "10.0.0.172";
	public static String mmsProt = "80";

       private static String HDR_VALUE_ACCEPT_LANGUAGE = "";
    // Definition for necessary HTTP headers.
       private static final String HDR_KEY_ACCEPT = "Accept";
       private static final String HDR_KEY_ACCEPT_LANGUAGE = "Accept-Language";

    private static final String HDR_VALUE_ACCEPT =
        "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic";
public static byte[] sendMMS(Context context, byte[] pdu)throws IOException{
		HDR_VALUE_ACCEPT_LANGUAGE = getHttpAcceptLanguage();

		if (mmscUrl == null) {
            throw new IllegalArgumentException("URL must not be null.");
        }

        HttpClient client = null;
        try {
	        // Make sure to use a proxy which supports CONNECT.
	        client = HttpConnector.buileClient(context);
	        HttpPost post = new HttpPost(mmscUrl);
	        //mms PUD START
	        ByteArrayEntity entity = new ByteArrayEntity(pdu);
			entity.setContentType("application/vnd.wap.mms-message");
	        post.setEntity(entity);
	        post.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
	        post.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);
	        //mms PUD END
	        HttpParams params = client.getParams();
	        HttpProtocolParams.setContentCharset(params, "UTF-8");
	        HttpResponse response = client.execute(post);

			LogUtility.showLog(tag, "111");
	        StatusLine status = response.getStatusLine();
	        LogUtility.showLog(tag, "status "+status.getStatusCode());
	        if (status.getStatusCode() != 200) { // HTTP 200 is not success.
            	LogUtility.showLog(tag, "!200");
                throw new IOException("HTTP error: " + status.getReasonPhrase());
            }
	        HttpEntity resentity = response.getEntity();
            byte[] body = null;
            if (resentity != null) {
                try {
                    if (resentity.getContentLength() > 0) {
                        body = new byte[(int) resentity.getContentLength()];
                        DataInputStream dis = new DataInputStream(resentity.getContent());
                        try {
                            dis.readFully(body);
                        } finally {
                            try {
                                dis.close();
                            } catch (IOException e) {
                                Log.e(tag, "Error closing input stream: " + e.getMessage());
                            }
                        }
                    }
                } finally {
                    if (entity != null) {
                        entity.consumeContent();
                    }
                }
            }
            LogUtility.showLog(tag, "result:"+new String(body));
            return body;
		}  catch (IllegalStateException e) {
			LogUtility.showLog(tag, "",e);
//            handleHttpConnectionException(e, mmscUrl);
        } catch (IllegalArgumentException e) {
        	LogUtility.showLog(tag, "",e);
//            handleHttpConnectionException(e, mmscUrl);
        } catch (SocketException e) {
        	LogUtility.showLog(tag, "",e);
//            handleHttpConnectionException(e, mmscUrl);
        } catch (Exception e) {
        	LogUtility.showLog(tag, "",e);
        	//handleHttpConnectionException(e, mmscUrl);
        } finally {
            if (client != null) {
//                client.;
            }
        }
		return new byte[0];
	}
           

至此,彩信的發送算是完成了。

總結:android的彩信相關操作都是沒有api的,包括彩信的讀取、發送、存儲。這些過程都是需要手動去完成的。想要弄懂這些過程,需要仔細閱讀android源碼中的mms這個app。還有就是去研究mmssms.db資料庫,因為彩信的讀取和存儲其實都是對mmssms.db這個資料庫的操作過程。而且因為這個是共享的資料庫,是以隻能用ContentProvider這個元件去操作db。

總之,想要研究彩信這塊(包括普通短信),你就必須的研究mmssms.db的操作方法,多多了解每個表對應的哪個uri,每個uri能提供什麼樣的操作,那些字段代表短信的那些屬性等。

最後推薦個好用的sqlite檢視工具:SQLite Database Browser。

5進制-android技術開發部落格