Android 彩信发送的两种方式

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

实现代码如下,

Intent intent = new Intent(Intent.ACTION_SEND);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));// uri为你的附件的uriintent.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

感谢大家的推荐和收藏

你的支持! 我们的动力!


更多相关文章

  1. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Fedora镜像
  2. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  3. Android(安卓)getResources的作用和需要注意点
  4. 使用android模拟器需要的设置(环境变量设置
  5. android 按键注入,模拟back,home,menu按键
  6. 横竖屏切换时不销毁当前activity 和 锁定屏幕
  7. Android上MediaScanner是如何工作的
  8. 横竖屏切换时不销毁当前activity 和 锁定屏幕
  9. android 前后台切换 回调

随机推荐

  1. Android优缺点
  2. Android的UI构造试图工具hierarchyviewer
  3. 【源码】Android 面包屑导航效果源码、An
  4. Android AsyncTas开发
  5. 美国Android占28%份额 摩托Droid最受欢迎
  6. Android 模拟器横屏竖屏切换设置
  7. Android ContentProvider 多进程multipro
  8. android EditText inputType
  9. .Net 转战 Android 4.4 日常笔记(6)--Andro
  10. Android(安卓)Bluetooth