【Android】Android 彩信发送的两种方式+源代码

Android  彩信发送的两种方式

第一种:直接调用彩信发送接口

  实现代码如下,

Intent intent = new Intent(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));// uri为你的附件的uri
intent.putExtra("subject", "it's subject"); //彩信的主题
intent.putExtra("address", "10086"); //彩信发送目的号码
intent.putExtra("sms_body", "it's content"); //彩信中文字内容
intent.putExtra(Intent.EXTRA_TEXT, "it's EXTRA_TEXT");
intent.setType("image/*");// 彩信附件类型
intent.setClassName("com.android.mms","com.android.mms.ui.ComposeMessageActivity");
startActivity(intent);

  看到彩信发送的代码,跟短信发送的代码有很大的不同,彩信发送不同于短信发送,调用系统的彩信发送会出现发送界面。

  有朋友就要问了,这样不适合我的需求,我需要实现自定义彩信发送,并且不调用系统彩信。第二种方法将满足我们的需求

 

第二种:自定义彩信发送

  自定义彩信发送,无需进入彩信发送界面,需要调用系统源码 PDU 实现。

  首先给出发送代码

  

//彩信发送函数
public static void sendMMS(final Context context, String number,
            String subject, String text, String imagePath, String audioPath) {
        final MMSInfo mmsInfo = new MMSInfo(context, number, subject, text,
                imagePath, audioPath);
        final List<String> list = APNManager.getSimMNC(context);
        new Thread() {
            @Override
            public void run() {
                try {
                    byte[] res = MMSSender.sendMMS(context, list,
                            mmsInfo.getMMSBytes());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            };
        }.start();
    }
APNManager.getSimMNC 用来设置 彩信Url和代理端口

MMSSender.sendMMS 实现彩信的发送

APNManager类源代码

View Code
package com.rayray.util;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

public class APNManager {

    // 电信彩信中心url,代理,端口
    public static String mmscUrl_ct = "http://mmsc.vnet.mobi";
    public static String mmsProxy_ct = "10.0.0.200";
    // 移动彩信中心url,代理,端口
    public static String mmscUrl_cm = "http://mmsc.monternet.com";
    public static String mmsProxy_cm = "10.0.0.172";
    // 联通彩信中心url,代理,端口
    public static String mmscUrl_uni = "http://mmsc.vnet.mobi";
    public static String mmsProxy_uni = "10.0.0.172";

    private static String TAG = "APNManager";
    private static final Uri APN_TABLE_URI = Uri
            .parse("content://telephony/carriers");// 所有的APN配配置信息位置
    private static final Uri PREFERRED_APN_URI = Uri
            .parse("content://telephony/carriers/preferapn");// 当前的APN
    private static String[] projection = { "_id", "apn", "type", "current",
            "proxy", "port" };
    private static String APN_NET_ID = null;
    private static String APN_WAP_ID = null;

    public static List<String> getSimMNC(Context context) {
        TelephonyManager telManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = telManager.getSubscriberId();
        if (imsi != null) {
            ArrayList<String> list = new ArrayList<String>();
            if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
                // 因为移动网络编号46000下的IMSI已经用完,所以虚拟了一个46002编号,134/159号段使用了此编号
                // 中国移动
                list.add(mmscUrl_cm);
                list.add(mmsProxy_cm);
            } else if (imsi.startsWith("46001")) {
                // 中国联通
                list.add(mmscUrl_uni);
                list.add(mmsProxy_uni);
            } else if (imsi.startsWith("46003")) {
                // 中国电信
                list.add(mmscUrl_ct);
                list.add(mmsProxy_ct);
            }
            shouldChangeApn(context);
            return list;
        }
        return null;
    }

    private static boolean shouldChangeApn(final Context context) {

        final String wapId = getWapApnId(context);
        String apnId = getCurApnId(context);
        // 若当前apn不是wap,则切换至wap
        if (!wapId.equals(apnId)) {
            APN_NET_ID = apnId;
            setApn(context, wapId);
            // 切换apn需要一定时间,先让等待2秒
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    public static boolean shouldChangeApnBack(final Context context) {
        // 彩信发送完毕后检查是否需要把接入点切换回来
        if (null != APN_NET_ID) {
            setApn(context, APN_NET_ID);
            return true;
        }
        return false;
    }

    // 切换成NETAPN
    public static boolean ChangeNetApn(final Context context) {
        final String wapId = getWapApnId(context);
        String apnId = getCurApnId(context);
        // 若当前apn是wap,则切换至net
        if (wapId.equals(apnId)) {
            APN_NET_ID = getNetApnId(context);
            setApn(context, APN_NET_ID);
            // 切换apn需要一定时间,先让等待几秒,与机子性能有关
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("xml", "setApn");
            return true;
        }
        return true;
    }

    // 切换成WAPAPN
    public static boolean ChangeWapApn(final Context context) {
        final String netId = getWapApnId(context);
        String apnId = getCurApnId(context);
        // 若当前apn是net,则切换至wap
        if (netId.equals(apnId)) {
            APN_WAP_ID = getNetApnId(context);
            setApn(context, APN_WAP_ID);
            // 切换apn需要一定时间,先让等待几秒,与机子性能有关
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("xml", "setApn");
            return true;
        }
        return true;
    }

    // 获取当前APN
    public static String getCurApnId(Context context) {
        ContentResolver resoler = context.getContentResolver();
        // String[] projection = new String[] { "_id" };
        Cursor cur = resoler.query(PREFERRED_APN_URI, projection, null, null,
                null);
        String apnId = null;
        if (cur != null && cur.moveToFirst()) {
            apnId = cur.getString(cur.getColumnIndex("_id"));
        }
        Log.i("xml", "getCurApnId:" + apnId);
        return apnId;
    }

    public static APN getCurApnInfo(final Context context) {
        ContentResolver resoler = context.getContentResolver();
        // String[] projection = new String[] { "_id" };
        Cursor cur = resoler.query(PREFERRED_APN_URI, projection, null, null,
                null);
        APN apn = new APN();
        if (cur != null && cur.moveToFirst()) {
            apn.id = cur.getString(cur.getColumnIndex("_id"));
            apn.apn = cur.getString(cur.getColumnIndex("apn"));
            apn.type = cur.getString(cur.getColumnIndex("type"));

        }
        return apn;
    }

    public static void setApn(Context context, String id) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("apn_id", id);
        resolver.update(PREFERRED_APN_URI, values, null, null);
        Log.d("xml", "setApn");
    }

    // 获取WAP APN
    public static String getWapApnId(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        // 查询cmwapAPN
        Cursor cur = contentResolver.query(APN_TABLE_URI, projection,
                "apn = \'cmwap\' and current = 1", null, null);
        // wap APN 端口不为空
        if (cur != null && cur.moveToFirst()) {
            do {
                String id = cur.getString(cur.getColumnIndex("_id"));
                String proxy = cur.getString(cur.getColumnIndex("proxy"));
                if (!TextUtils.isEmpty(proxy)) {
                    Log.i("xml", "getWapApnId" + id);
                    return id;
                }
            } while (cur.moveToNext());
        }
        return null;
    }

    public static String getNetApnId(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cur = contentResolver.query(APN_TABLE_URI, projection,
                "apn = \'cmnet\' and current = 1", null, null);
        if (cur != null && cur.moveToFirst()) {
            return cur.getString(cur.getColumnIndex("_id"));
        }
        return null;
    }

    // 获取所有APN
    public static ArrayList<APN> getAPNList(final Context context) {

        ContentResolver contentResolver = context.getContentResolver();
        Cursor cr = contentResolver.query(APN_TABLE_URI, projection, null,
                null, null);

        ArrayList<APN> apnList = new ArrayList<APN>();

        if (cr != null && cr.moveToFirst()) {
            do {
                Log.d(TAG,
                        cr.getString(cr.getColumnIndex("_id")) + ";"
                                + cr.getString(cr.getColumnIndex("apn")) + ";"
                                + cr.getString(cr.getColumnIndex("type")) + ";"
                                + cr.getString(cr.getColumnIndex("current"))
                                + ";"
                                + cr.getString(cr.getColumnIndex("proxy")));
                APN apn = new APN();
                apn.id = cr.getString(cr.getColumnIndex("_id"));
                apn.apn = cr.getString(cr.getColumnIndex("apn"));
                apn.type = cr.getString(cr.getColumnIndex("type"));
                apnList.add(apn);
            } while (cr.moveToNext());

            cr.close();
        }
        return apnList;
    }

    // 获取可用的APN
    public static ArrayList<APN> getAvailableAPNList(final Context context) {
        // current不为空表示可以使用的APN
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cr = contentResolver.query(APN_TABLE_URI, projection,
                "current is not null", null, null);
        ArrayList<APN> apnList = new ArrayList<APN>();
        if (cr != null && cr.moveToFirst()) {
            do {
                Log.d(TAG,
                        cr.getString(cr.getColumnIndex("_id")) + ";"
                                + cr.getString(cr.getColumnIndex("apn")) + ";"
                                + cr.getString(cr.getColumnIndex("type")) + ";"
                                + cr.getString(cr.getColumnIndex("current"))
                                + ";"
                                + cr.getString(cr.getColumnIndex("proxy")));
                APN apn = new APN();
                apn.id = cr.getString(cr.getColumnIndex("_id"));
                apn.apn = cr.getString(cr.getColumnIndex("apn"));
                apn.type = cr.getString(cr.getColumnIndex("type"));
                apnList.add(apn);
            } while (cr.moveToNext());

            cr.close();
        }
        return apnList;

    }

    // 自定义APN包装类
    static class APN {

        String id;

        String apn;

        String type;

        @Override
        public String toString() {
            return "id=" + id + ",apn=" + apn + ";type=" + type;
        }
    }

}

MMSSender类源代码

View Code
//发送类
package com.rayray.util;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.List;

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.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
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.util.Log;

/**
 * @author
 * @version 创建时间:2012-2-1 上午09:32:54
 */
public class MMSSender {
    private static final String TAG = "MMSSender";
    // public static String mmscUrl = "http://mmsc.monternet.com";
    // public static String mmscProxy = "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, List<String> list, byte[] pdu)
            throws IOException {
        System.out.println("进入sendMMS方法");
        // HDR_VALUE_ACCEPT_LANGUAGE = getHttpAcceptLanguage();
        HDR_VALUE_ACCEPT_LANGUAGE = HTTP.UTF_8;

        String mmsUrl = (String) list.get(0);
        String mmsProxy = (String) list.get(1);
        if (mmsUrl == 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(ConnRoutePNames.DEFAULT_PROXY, httpHost);
            HttpConnectionParams.setConnectionTimeout(httpParams, 10000);

            client = new DefaultHttpClient(httpParams);

            HttpPost post = new HttpPost(mmsUrl);
            // 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.;
            }
            APNManager.shouldChangeApnBack(context);
        }
        return new byte[0];
    }

}

注意,这里需要从系统源码中引入 com.google.android.mms包,并将相关引用包调通,才可以使用。

//

 

 

需要获取源代码的朋友,可以通过下面两种方式获取

 

(1)下载地址 http://download.csdn.net/detail/fnext/5228721

 

(2)请在评论中填写邮件地址,会通过邮箱发送源码。

 

看到大家的反馈,源码调试有些问题,我抽时间会再更新代码,请谅解,同时感谢大家的帮助和支持

 

原创声明 转载请注明

本文出自 Ray-Ray的博客

文章地址 http://www.cnblogs.com/rayray/archive/2013/03/11/2954214.html

感谢大家的推荐和收藏

你的支持! 我们的动力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值