Android 发送彩信

一、调用系统UI发送

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:"));

二、后台无界面发送彩信

1、代码结构图


2、彩信信息类MMSInfo.java:用于彩信信息的设定

package com.cs.mms;
import android.content.Context;
import android.net.Uri;

import com.google.android.mms.pdu.CharacterSets;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.pdu.PduBody;
import com.google.android.mms.pdu.PduComposer;
import com.google.android.mms.pdu.PduPart;
import com.google.android.mms.pdu.SendReq;

/**
* @author 
* @version 创建时间:2012-1-31 下午01:59:30
*/
public class MMSInfo {
        private Context con;
        private PduBody pduBody;
        private String recieverNum;
        private int partCount = 1;

        private static final String SUBJECT_STR = "来自XX好友的彩信"; // 彩信主题

        public MMSInfo(Context con, String recieverNum) {
                // TODO Auto-generated constructor stub
                this.con = con;
                this.recieverNum = recieverNum;
                pduBody = new PduBody();
        }

        /**
         * 添加图片附件,每添加一个附件调用本方法一次即可
         * 
         * @author 
         * @param uriStr
         *            , 如:file://mnt/sdcard//1.jpg
         */
        public void addPart(String uriStr) {
                PduPart part = new PduPart();
                part.setCharset(CharacterSets.UTF_8);
                part.setName(("附件" + partCount++).getBytes());
//                part.setContentType(("image/jpg" + getTypeFromUri(uriStr)).getBytes());// "image/png"
                part.setContentType("image/jpg".getBytes());
                part.setDataUri(Uri.parse(uriStr));
                pduBody.addPart(part);
        }

        /**
         * 通过URI路径得到图片格式,如:"file://mnt/sdcard//1.jpg" -----> "jpg"
         * 
         * @author 
         * @param uriStr
         * @return
         */
        private String getTypeFromUri(String uriStr) {
                return uriStr.substring(uriStr.lastIndexOf("."), uriStr.length());
        }

        /**
         * 将彩信的内容以及主题等信息转化成byte数组,准备通过http协议发送到"http://mmsc.monternet.com"
         * 
         * @author
         * @return
         */
        public byte[] getMMSBytes() {
                PduComposer composer = new PduComposer(con, initSendReq());
                return composer.make();
        }

        /**
         * 初始化SendReq
         * 
         * @author 
         * @return
         */
        private SendReq initSendReq() {
                SendReq req = new SendReq();
                EncodedStringValue[] sub = EncodedStringValue.extract(SUBJECT_STR);
                if (sub != null && sub.length > 0) {
                        req.setSubject(sub[0]);// 设置主题
                }
                EncodedStringValue[] rec = EncodedStringValue.extract(recieverNum);
                if (rec != null && rec.length > 0) {
                        req.addTo(rec[0]);// 设置接收者
                }
                req.setBody(pduBody);
                return req;
        }

}

3、彩信发送类MMSSender.java:用于彩信发送信息的设定,及发送彩信

//发送类
package com.cs.mms;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.util.Log;

public class MMSSender {
        private static final String TAG = "MMSSender";
        public static String mmscUrl = "http://mmsc.monternet.com";
        public static String mmsProxy = "10.0.0.172";
        public static int mmsProt = 80;

        private static String HDR_VALUE_ACCEPT_LANGUAGE = "";
        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 {
                System.out.println("进入sendMMS方法");
                // HDR_VALUE_ACCEPT_LANGUAGE = getHttpAcceptLanguage();
                HDR_VALUE_ACCEPT_LANGUAGE = HTTP.UTF_8;
                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);

                        HttpHost httpHost = new HttpHost(mmsProxy, mmsProt);
                        HttpParams httpParams = new BasicHttpParams();
                        httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
                        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);

                        client = new DefaultHttpClient(httpParams);

                        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);
                        post.addHeader("user-agent", "Mozilla/5.0(Linux;U;Android 2.1-update1;zh-cn;ZTE-C_N600/ZTE-C_N600V1.0.0B02;240*320;CTC/2.0)AppleWebkit/530.17(KHTML,like Gecko) Version/4.0 Mobile Safari/530.17");
                        // mms PUD END
                        HttpParams params = client.getParams();
                        HttpProtocolParams.setContentCharset(params, "UTF-8");

                        System.out.println("准备执行发送");

//                      PlainSocketFactory localPlainSocketFactory = PlainSocketFactory.getSocketFactory();
                        
                        
                        HttpResponse response = client.execute(post);

                        System.out.println("执行发送结束, 等回执。。");

                        StatusLine status = response.getStatusLine();
                        Log.d(TAG, "status " + status.getStatusCode());
                        if (status.getStatusCode() != 200) { // HTTP 200 表服务器成功返回网页
                                Log.d(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();
                                        }
                                }
                        }
                        Log.d(TAG, "result:" + new String(body));

                        System.out.println("成功!!" + new String(body));

                        return body;
                } catch (IllegalStateException e) {
                        Log.e(TAG, "", e);
                        // handleHttpConnectionException(e, mmscUrl);
                } catch (IllegalArgumentException e) {
                        Log.e(TAG, "", e);
                        // handleHttpConnectionException(e, mmscUrl);
                } catch (SocketException e) {
                        Log.e(TAG, "", e);
                        // handleHttpConnectionException(e, mmscUrl);
                } catch (Exception e) {
                        Log.e(TAG, "", e);
                        // handleHttpConnectionException(e, mmscUrl);
                } finally {
                        if (client != null) {
                                // client.;
                        }
                }
                return new byte[0];
        }
        
        
        private int CountMoneyCMWAPNEWWAY()
        {

                String strHead = "";
                try{
//                        if(!GameLet._self.isNetworkCMWAPAvailable())
//                        {
//                                GameLet._self.ActiveNetWorkByMode("wap");
//                                Thread.sleep(5000);
//                        }

                    String urlstr = "http://mmsc.monternet.com";    
                        
                    int splashIndex = urlstr.indexOf("/", 7);

                    String hosturl = urlstr.substring(7, splashIndex);
                    String hostfile = urlstr.substring(splashIndex);
                    
                  

                    HttpHost proxy = new HttpHost( "10.0.0.172", 80, "http");
                    HttpHost target = new HttpHost(hosturl, 80, "http");         
               
                    HttpParams httpParams = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
                    HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
                    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
                    HttpClientParams.setRedirecting(httpParams, true);
               
//                    String userAgent =  AndroidPlatform.getUAFromProperties();
//                    ProductProperties.get(ProductPropertiws.USER_AGENT_KEY,null);
//               
//                    HttpProtocolParams.setUserAgent(httpParams, userAgent);
                    DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);

                    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                     
                    HttpGet req = new HttpGet(hostfile);
                 
                    HttpResponse rsp = httpclient.execute(target, req);
                  
                    HttpEntity entity = rsp.getEntity();
                    
                    InputStream inputstream = entity.getContent();
                    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
                    byte abyte1[] = new byte[1024];
                    for(int k = 0; -1 != (k = inputstream.read(abyte1));)
                       bytearrayoutputstream.write(abyte1, 0, k);
                    
                    strHead = new String(bytearrayoutputstream.toByteArray(), "UTF-8");
                    
                    httpclient.getConnectionManager().shutdown();   
                    
                    }
                    catch (Exception e)        {
                            return 2;
                    }
                     
                  if(strHead.indexOf("status=1301") > -1 || strHead.indexOf("status=1300") > -1)
                  {
                        return 1;
                  }
                  else
                  {
                        return 0;
                  }   
        }
}
4、程序主入口MMSTest1Activity.java:调用发送函数

package com.cs.mms;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;

import com.wain.cs.mms.R;
public class MMSTest1Activity extends Activity {
    /** Called when the activity is first created. */
    public static String mmscUrl = "http://mmsc.monternet.com";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //关闭WIFI
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {  

        	wifiManager.setWifiEnabled(false);  
        	
        	} 
        //获取当前网络
        ConnectivityManager conManager= (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); 
        NetworkInfo info = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
        String currentAPN = info.getExtraInfo(); 
        conManager.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "mms");
        currentAPN = info.getExtraInfo(); 
        //只有CMWAP才能发送彩信
        if("cmwap".equals(currentAPN))
        {
        	sendMMS();
        }
    }
    void sendMMS()
    {
    	final MMSInfo mms = new MMSInfo(MMSTest1Activity.this, "159xxxxxxxx");//发送的手机号
        String path = "file://mnt/sdcard//1.jpg";//需发送的图片
        System.out.println("--->" + path);
        mms.addPart(path);// file://mnt/sdcard//1.jpg
        final MMSSender sender = new MMSSender();
        new Thread() {
                public void run() {
                        try {
                                byte[] res = sender.sendMMS(MMSTest1Activity.this,
                                                mms.getMMSBytes());
                                System.out.println("-==-=-=>>> " + res.toString());
                        } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                };
        }.start();
    }
}
5、注意:一定要在发彩信前将手机切换成CMWAP方式!!!

6、源码地址:http://download.csdn.net/detail/thundercat/4067925


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值