彩信MMS发送和接受 手机不能接受彩信

彩信发送:
概括的讲,彩信发送可分为两步执行:
(1)组装彩信PDU
publicstatic GenericPdu makePdu(Context context,String phone,
Stringsubject, String text, String imagePath, String audioPath) {
SendReq sendReq=new SendReq();
//设置主题
EncodedStringValue[] sub =EncodedStringValue.extract(subject);
if (sub !=null && sub.length >0) {
sendReq.setSubject(sub[0]);
}
//设置接收号码
EncodedStringValue[] phoneNumbers =EncodedStringValue.extract(phone);
if(phoneNumbers != null &&phoneNumbers.length > 0) {
sendReq.addTo(phoneNumbers[0]);
}
//设置发送号码
TelephonyManager mTelephonyManager =(TelephonyManager)context.getApplicationContext()
.getSystemService(Context.TELEPHONY_SERVICE);
StringlineNumber =mTelephonyManager.getLine1Number();
if (!TextUtils.isEmpty(lineNumber)) {
sendReq.setFrom(new EncodedStringValue(lineNumber));
}
//设置PduBody内容,对于图片/音频/视频,不需要保存Data在part里,因为它们的渲染器支持URI作为数据源(setDataUri())。
PduBodypduBody = new PduBody();
if(!TextUtils.isEmpty(text)) {
PduPartpartPdu3 = new PduPart();
partPdu3.setCharset(CharacterSets.UTF_8);
partPdu3.setName("mms_text.txt".getBytes());
partPdu3.setContentType("text/plain".getBytes());
partPdu3.setData(text.getBytes());
pduBody.addPart(partPdu3);
}
if(!TextUtils.isEmpty(imagePath)) {
PduPartpartPdu = new PduPart();
partPdu.setCharset(CharacterSets.UTF_8);//编码格式
partPdu.setName("aa.jpg".getBytes());
partPdu.setContentType("image/jpeg".getBytes());
//partPdu.setDataUri(Uri.parse("file:///sdcard/aa.bmp"));
partPdu.setDataUri(Uri.fromFile(new File(imagePath)));
pduBody.addPart(partPdu);
}
if(!TextUtils.isEmpty(audioPath)) {
PduPartpartPdu2 = new PduPart();
partPdu2.setCharset(CharacterSets.ISO_8859_1);
partPdu2.setName("speech_test.amr".getBytes());
partPdu2.setContentType("audio/amr".getBytes());
//partPdu2.setContentType("audio/amr-wb".getBytes());
//partPdu2.setDataUri(Uri.parse("file://mnt//sdcard//.lv//audio//1326786209801.amr"));
partPdu2.setDataUri(Uri.fromFile(new File(audioPath)));
pduBody.addPart(partPdu2);
}
sendReq.setBody(pduBody);
returnsendReq;
}
(2)发送
发送之前,需要先获取手机运营商主机地址及访问地址。
//电信彩信中心url,代理,端口
publicstatic String mmscUrl_ct = "http://mmsc.vnet.mobi";
publicstatic String mmsProxy_ct = "10.0.0.200";
//移动彩信中心url,代理,端口
publicstatic String mmscUrl_cm = "http://mmsc.monternet.com";
publicstatic String mmsProxy_cm = "010.000.000.172";

//联通彩信中心url,代理,端口
publicstatic String mmscUrl_uni = "http://mmsc.vnet.mobi";
publicstatic String mmsProxy_uni = "10.0.0.172";
//默认端口
publicstatic int mmsDefautPort=80;

//获取服务商访问地址及端口
privatestatic List<String> getSimMNC(Contextcontext) {
TelephonyManager telManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String imsi= telManager.getSubscriberId();
if (imsi !=null) {
ArrayList<String> list = newArrayList<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);
returnlist;
}
returnnull;
}

privatestatic boolean shouldChangeApn(final Context context) {

final StringwapId = getWapApnId(context);
String apnId= getApn(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();
}
returntrue;
}
returnfalse;
}

privatestatic String getApn(Context context) {
ContentResolver resoler = context.getContentResolver();
String[]projection = new String[] { "_id" };
Cursor cur =resoler.query(
Uri.parse("content://telephony/carriers/preferapn"),
projection,null, null, null);
String apnId= null;
if (cur !=null && cur.moveToFirst()) {
do {
apnId =cur.getString(cur.getColumnIndex("_id"));
} while(cur.moveToNext());
}
returnapnId;
}
然后将彩信Pdu转换为byte[]数组,
final PduComposer composer = new PduComposer(context,sendReq);
final byte[] data = composer.make();
调用httpConnection()方法发送出去。

彩信接收:
(1)彩信发送成功后,MMSC会以短信息PDU包的形式通知接收方,即彩信通知,接收方获取彩信提取地址等信息。
(2)接收方从MMSC中提取MMS,并解析PDU数据。
public static finalString MMS_RECEIVE_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";
Stringaction = intent.getAction();
if(acttion.equals(MMS_RECEIVE_ACTION)){
new ReceivePushTask(context).execute(intent);
}
// 彩信预处理过程
classReceivePushTask extends AsyncTask<Intent, Void,Void> {
publicReceivePushTask(Context context) {
super();
}
@Override
protectedVoid doInBackground(Intent... intents) {
Intentintent = intents[0];
//获取push-data
// Get rawPDU push-data from the message and parse it
byte[]pushData = intent.getByteArrayExtra("data");
PduParserparser = new PduParser(pushData);
//NotificationInd mNotificationInd;
GenericPdumPdu;
//StringmId;
StringmContentLocation;// 彩信下载地址
byte[]retrieveConfData = null;
try {
//mNotificationInd = (NotificationInd) parser.parse();
mPdu=parser.parse();
//mId = newString(mNotificationInd.getTransactionId());
//mContentLocation = newString(mNotificationInd.getContentLocation());

mContentLocation=mPdu.getPduHeaders().getContentLocation();
Log.d(TAG,"HeadermContentLocation:"+mContentLocation);
Log.d(TAG,"HeaderFrom:"+mPdu.getPduHeaders().getFrom());
//获取彩信Pdu数据
retrieveConfData = getPdu(mContentLocation);
if(retrieveConfData != null) {
GenericPdupdu = new PduParser(retrieveConfData).parse();
PduHeadersheader = pdu.getPduHeaders();
彩信MMS发送和接受 手机不能接受彩信
EncodedStringValuesubject=header.getEncodedStringValue(PduHeaders.SUBJECT);
subject.setCharacterSet(CharacterSets.ANY_CHARSET);
Log.d(TAG,"Header主题:"+subject.getString());
Log.d(TAG,"ContentLocation:"+header.getContentLocation());
Log.d(TAG,"From:"+header.getFrom());
Log.d(TAG,"MessageType:"+header.getMessageType());
PduBody body= null;
// Get bodyif the PDU is a RetrieveConf or SendReq.
if (pduinstanceof MultimediaMessagePdu) {
Log.d(TAG,"主题:"+((MultimediaMessagePdu)pdu).getSubject().getString());
body = ((MultimediaMessagePdu) pdu).getBody();
// Start saving parts if necessary.
if (body != null) {
int partsNum= body.getPartsNum();
try {
for(int i=0;i<partsNum;i++){
//获取附件数据
Log.d(TAG,"------------part:"+i+"-------------");
PduPart part =body.getPart(i);
String contentType = toIsoString(part.getContentType());
persistData(part,contentType);
}
} catch(MmsException e) {
e.printStackTrace();
}
}
}
}

} catch(InvalidHeaderValueException e) {

e.printStackTrace();
}
returnnull;
}
}
//请求Url获取彩信数据
publicbyte[] getPdu(String url) {
Log.d("TAG","url:"+url);
try {
returnHttpUtils.httpConnection(mContext, -1L, url, null,
HttpUtils.HTTP_GET_METHOD, true, "10.0.0.172", 80);
} catch(IOException e) {
e.printStackTrace();
returnnull;
}
}
public static byte[] httpConnection(String url,
byte[] pdu,int method, boolean isProxySet, String proxyHost,
intproxyPort) throws IOException {

if (url ==null) {
throw newIllegalArgumentException("URL must not be null.");
}

AndroidHttpClient client = null;// 定义客户端
try {
URI hostUrl= new URI(url);// 访问地址
// 主机
HttpHosttarget = new HttpHost(hostUrl.getHost(),
hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
client =AndroidHttpClient.newInstance("Android-Mms/2.0");
HttpRequestreq = null;
switch(method) {
caseHTTP_POST_METHOD:
ByteArrayEntity entity = new ByteArrayEntity(pdu);
// Setrequest content type.
entity.setContentType("application/vnd.wap.mms-message");

HttpPostpost = new HttpPost(url);
post.s--etEntity(entity);
req =post;
break;
caseHTTP_GET_METHOD:
req = newHttpGet(url);
break;
default:
Log.e(TAG,"Unknown HTTP method: " + method
+ ". Must beone of POST[" + HTTP_POST_METHOD
+ "] orGET[" + HTTP_GET_METHOD + "].");
returnnull;
}
HttpParamsparams = client.getParams();
//设置代理
if(isProxySet) {
ConnRouteParams.setDefaultProxy(params, newHttpHost(proxyHost,
proxyPort));
}
req.setParams(params);

// 必要的 Setnecessary HTTP headers for MMS transmission.
req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
req.addHeader(HDR_KEY_ACCEPT_LANGUAGE,HDR_VALUE_ACCEPT_LANGUAGE);

HttpResponseresponse = client.execute(target, req);
StatusLinestatus = response.getStatusLine();
if(status.getStatusCode() != 200) { // HTTP 200 is success.
throw newIOException("HTTP error: " + status.getReasonPhrase());
}
HttpEntityentity = response.getEntity();
byte[] body= null;
if (entity!= null) {
try {
if(entity.getContentLength() > 0) {
body = newbyte[(int) entity.getContentLength()];
DataInputStream dis = new DataInputStream(
entity.getContent());
try {
dis.readFully(body);
} finally{
try {
dis.close();
} catch(IOException e) {
Log.e(TAG,
"Errorclosing input stream: "
+e.getMessage());
}
}
}
} finally{
if (entity!= null) {
entity.consumeContent();
}
}
}
returnbody;
} catch(Exception e) {
Log.e(TAG,"Url: " + url + "n" + e.getMessage());
} finally{
if (client!= null) {
client.close();
}
}
returnnull;
}
//解析Pdu part
public voidpersistData(PduPart part,String contentType)
throws MmsException {
Log.d(TAG,"ContentType:"+contentType);
FileOutputStream os = null;
try {
byte[] data = part.getData();
if (ContentType.TEXT_PLAIN.equals(contentType)
|| ContentType.APP_SMIL.equals(contentType)
|| ContentType.TEXT_HTML.equals(contentType)) {

String partText= new EncodedStringValue(data).getString();

Log.d(TAG, "Text:"+partText);

} else {
os = new FileOutputStream(new File("/sdcard/temp.jpg"));
os.write(data);

}
} catch (FileNotFoundException e) {
Log.e(TAG, "Failed to open Input/Output stream.", e);
throw new MmsException(e);
} catch (IOException e) {
Log.e(TAG, "Failed to read/write data.", e);
throw new MmsException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
Log.e(TAG, "IOException while closing: " + os, e);
}
}
}
}

  

爱华网本文地址 » http://www.413yy.cn/a/25101015/271756.html

更多阅读

手机不能上网怎么回事 手机上不了网怎么回事

手机不能上网怎么回事——简介手机上网主要分为两种方式:一种是能过SIM卡上网,别一种是通过无线网上网,下面说下如果无法上网应该怎么检查供参考:手机不能上网怎么回事——方法/步骤手机不能上网怎么回事 1、首先,确定你的手机信号是否

羊年明年 真的不能生宝宝吗? 明年苹果手机不能用了

金玉章 /文据参考消息网5月12日报道,美国《华盛顿邮报》网站称,中国夫妇抢在可怕的羊年之前怀孕。事实上,从去年到目前为止,很多年轻的夫妇热衷于计划生一个马宝宝,而避开“可怕”的羊年生孩子。为什么会有这样荒谬的现象呢?流传较广的

解决手机不能发送短信 苹果手机不能发送短信

解决手机不能发送短信——简介手机不能发送短信!?哼!看窝哒(不适用于所有手机,请自行对号入座)解决手机不能发送短信——工具/原料手机解决手机不能发送短信——方法/步骤解决手机不能发送短信 1、手机有没有信号 (无信号当然不能发送短

解决安卓系统手机不能上网问题! 新风系统解决臭氧问题

菜单-设置-无线和网络—移动网络-勾选数据漫游(因为安卓是国外的系统,所以如果我们上移动或联通的网络,安卓就会认为我们在数据漫游,这个安全,请大家放心!) 同上,进入接入点名称: 接入点名称-按照机器原来的自带设置一共有2个,分别为: cmnet,cmwap

为什么手机连接不上wifi 精 手机不能自动连接wifi

为什么手机连接不上wifi 精——简介手机的功能越来越多,需要网络的支持就越来越多。那么,wifi的普及率就也顺着提高了。但是有些手机在连接wifi的时候,总是自动断开重联,还总是连接不上,应该怎么解决呢?请阅读下文!为什么手机连接不上wifi

声明:《彩信MMS发送和接受 手机不能接受彩信》为网友等你回心分享!如侵犯到您的合法权益请联系我们删除