对于在Android中发送短信感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解android发送短信,并且为您提供关于AndroidNDK之发送短信、android–通过Intent发送短信
对于在Android中发送短信感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解android 发送短信,并且为您提供关于Android NDK之发送短信、android – 通过Intent发送短信,并知道短信是否已被发送、android – 通过意图发送短信、android 几种发送短信的方法的宝贵知识。
本文目录一览:- 在Android中发送短信(android 发送短信)
- Android NDK之发送短信
- android – 通过Intent发送短信,并知道短信是否已被发送
- android – 通过意图发送短信
- android 几种发送短信的方法
在Android中发送短信(android 发送短信)
package SMSApp.com; import android.app.Activity; import android.app.PendingIntent; import android.content.broadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SMS extends Activity { /** Called when the activity is first created. */ Button btnSendSMS; EditText txtPhoneNo; EditText txtMessage; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnSendSMS = (Button) findViewById(R.id.btnSendSMS); txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); txtMessage = (EditText) findViewById(R.id.txtMessage); btnSendSMS.setonClickListener(new View.OnClickListener() { public void onClick(View v) { String phoneNo = txtPhoneNo.getText().toString(); String message = txtMessage.getText().toString(); if (phoneNo.length()>0 && message.length()>0) sendSMS(phoneNo,message); else Toast.makeText(getBaseContext(),"Please enter both phone number and message.",Toast.LENGTH_SHORT).show(); } /*private void sendSMS(String phoneNo,String message) { // Todo Auto-generated method stub PendingIntent pi = PendingIntent.getActivity(SMS.this,new Intent(SMS.this,SMS.class),0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNo,null,message,pi,null); }*/ private void sendSMS(String phoneNumber,String message) { String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getbroadcast(SMS.this,new Intent(SENT),0); PendingIntent deliveredPI = PendingIntent.getbroadcast(SMS.this,new Intent(DELIVERED),0); //---when the SMS has been sent--- registerReceiver(new broadcastReceiver(){ @Override public void onReceive(Context arg0,Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(),"SMS sent",Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(),"Generic failure",Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(),"No service",Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(),"Null PDU",Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RAdio_OFF: Toast.makeText(getBaseContext(),"Radio off",Toast.LENGTH_SHORT).show(); break; } } },new IntentFilter(SENT)); //---when the SMS has been delivered--- registerReceiver(new broadcastReceiver(){ @Override public void onReceive(Context arg0,"SMS delivered",Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: Toast.makeText(getBaseContext(),"SMS not delivered",new IntentFilter(DELIVERED)); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber,sentPI,deliveredPI); } }); } }
解决方法
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
在您的文件中设置权限并尝试使用此代码:
package SMSApp.com; import android.app.Activity; import android.app.PendingIntent; import android.content.broadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SMS extends Activity { /** Called when the activity is first created. */ Button btnSendSMS; EditText txtPhoneNo; EditText txtMessage; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnSendSMS = (Button) findViewById(R.id.btnSendSMS); txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); txtMessage = (EditText) findViewById(R.id.txtMessage); btnSendSMS.setonClickListener(new View.OnClickListener() { public void onClick(View v) { String phoneNo = txtPhoneNo.getText().toString(); String message = txtMessage.getText().toString(); if (phoneNo.length()>0 && message.length()>0) sendSMS(phoneNo,Toast.LENGTH_SHORT).show(); } }); } private void sendSMS(String phoneNumber,String message) { String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getbroadcast(SMS.this,0); PendingIntent deliveredPI = PendingIntent.getbroadcast(SMS.this,0); //--- When the SMS has been sent --- registerReceiver(new broadcastReceiver(){ @Override public void onReceive(Context arg0,Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(SMS.this,Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(SMS.this,Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(SMS.this,Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(SMS.this,Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RAdio_OFF: Toast.makeText(getBaseContext(),Toast.LENGTH_SHORT).show(); break; } } },new IntentFilter(SENT)); //--- When the SMS has been delivered. --- registerReceiver(new broadcastReceiver(){ @Override public void onReceive(Context arg0,Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: Toast.makeText(SMS.this,new IntentFilter(DELIVERED)); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber,deliveredPI); } }
Android NDK之发送短信
java代码:
MainActivity Activity SystemloadLibrary@Override
onCreateBundle savedInstanceStateonCreatesavedInstanceStatesetContentViewRlayoutactivity_mainsendTextMessagesendMessageObject handlerString whoNumberString messagesendTextMessageObject handlerString whoNumberString message
NDK JNI代码:
Java_com_mrper_messager_MainActivity_sendMessage
(*envobjhandlerwhoNumbermessage){
cls_activity = env->FindClass() = env->GetMethodID(cls_activity)cls_intent = env->FindClass()mid_struct = env->GetMethodID(cls_intent)fid_msg = env->GetStaticFieldID(cls_intent)field_msg = env->GetStaticObjectField(cls_intentfid_msg)cls_uri = env->FindClass()mid_parse = env->GetStaticMethodID(cls_uri)mobj_parse = env->CallStaticObjectMethod(cls_urimid_parsewhoNumber)obj_intent = env->NewObject(cls_intentmid_structfield_msgmobj_parse)mid_putExtra = env->GetMethodID(cls_intent)msg_tag = env->NewStringUTF()env->CallObjectMethod(obj_intentmid_putExtramsg_tagmessage)env->CallVoidMethod(handlerobj_intent)}
Java_com_mrper_messager_MainActivity_sendTextMessage
(*envhandlerobjectwhoNumbermessage){
cls_sms = env->FindClass()mid_instance = env->GetStaticMethodID(cls_sms)obj_sms = env->CallStaticObjectMethod(cls_smsmid_instance)mid_sms = env->GetMethodID(cls_sms)cls_pendingIntent = env->FindClass()mid_pendingIntent = env->GetStaticMethodID(cls_pendingIntent)cls_intent = env->FindClass()mid_intentStruct = env->GetMethodID(cls_intent)action_send = env->NewStringUTF()obj_sIntent = env->NewObject(cls_intentmid_intentStructaction_send)action_delivery = env->NewStringUTF()obj_rIntent = env->NewObject(cls_intentmid_intentStructaction_delivery)obj_sPendingIntent = env->CallStaticObjectMethod(cls_pendingIntentmid_pendingIntenthandlerobj_sIntent)obj_rPendingIntent = env->CallStaticObjectMethod(cls_pendingIntentmid_pendingIntenthandlerobj_rIntent)env->CallVoidMethod(obj_smsmid_smswhoNumbermessageobj_sPendingIntentobj_rPendingIntent)}
android – 通过Intent发送短信,并知道短信是否已被发送
Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("smsto:" + phoneNumber)); intent.putExtra("address",phoneNumber); intent.putExtra("sms_body",messageBody); intent.putExtra("exit_on_sent",true); startActivityForResult(intent,CODE);
然后,我想知道SMS是否已发送,我使用此代码:
public void onActivityResult(int requestCode,int resultCode,Intent intent) { switch (requestCode) { case CODE: if (resultCode == Activity.RESULT_OK) { //Then do... } elseif(resultCode == Activity.RESULT_CANCELED) { // Do... } break; } }
事情是结果始终为0(Activity.RESULT_CANCELED),即使已发送短信也是如此.如何知道短信是否已发送?我想使用手机的短信默认应用程序,而不是创建发送短信的界面.
解决方法
Observer的构造函数包含一个超时参数(以毫秒为单位),如果在一段合理的时间后没有发送消息,则允许Observer正确注销.如果需要,可以将其设置为NO_TIMEOUT.但是,如上所述,该类用于“一次性”使用,并且它将取消注册自身并在回调时使成员无效.如果没有回调,stop()方法可用于清理.在任何一种情况下,实例都不再可用,并且对它的任何引用都应设置为null.
示例活动:
public class MainActivity extends Activity implements SmsSendobserver.SmsSendListener { ... private void sendMessage(String phoneNumber,String messageBody) { // This example has a timeout set to 15 seconds new SmsSendobserver(this,phoneNumber,15000).start(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("smsto:" + phoneNumber)); intent.putExtra("address",phoneNumber); intent.putExtra("sms_body",messageBody); intent.putExtra("exit_on_sent",true); startActivity(intent); } public void onSmsSendEvent(boolean sent) { Toast.makeText(this,sent ? "Message was sent" : "Timed out",Toast.LENGTH_SHORT).show(); } }
SmsSendobserver类:
public class SmsSendobserver extends ContentObserver { public static final int NO_TIMEOUT = -1; private static final Handler handler = new Handler(); private static final Uri uri = Uri.parse("content://sms/"); private static final String COLUMN_ADDRESS = "address"; private static final String COLUMN_TYPE = "type"; private static final String[] PROJECTION = { COLUMN_ADDRESS,COLUMN_TYPE }; private static final int MESSAGE_TYPE_SENT = 2; private Context context = null; private ContentResolver resolver = null; private String phoneNumber = null; private long timeout = NO_TIMEOUT; private boolean wasSent = false; private boolean timedOut = false; public SmsSendobserver(Context context,String phoneNumber,long timeout) { super(handler); if (context instanceof SmsSendListener) { this.context = context; this.resolver = context.getContentResolver(); this.phoneNumber = phoneNumber; this.timeout = timeout; } else { throw new IllegalArgumentException( "Context must implement SmsSendListener interface"); } } private Runnable runOut = new Runnable() { @Override public void run() { if (!wasSent) { timedOut = true; callBack(); } } }; public void start() { if (resolver != null) { resolver.registerContentObserver(uri,true,this); if (timeout > NO_TIMEOUT) { handler.postDelayed(runOut,timeout); } } else { throw new IllegalStateException( "Current SmsSendobserver instance is invalid"); } } public void stop() { if (resolver != null) { resolver.unregisterContentObserver(this); resolver = null; context = null; } } private void callBack() { ((SmsSendListener) context).onSmsSendEvent(wasSent); stop(); } @Override public void onChange(boolean selfChange) { if (wasSent || timedOut) return; Cursor cursor = null; try { cursor = resolver.query(uri,PROJECTION,null,null); if (cursor != null && cursor.movetoFirst()) { final String address = cursor.getString(cursor.getColumnIndex(COLUMN_ADDRESS)); final int type = cursor.getInt(cursor.getColumnIndex(COLUMN_TYPE)); if (PhoneNumberUtils.compare(address,phoneNumber) && type == MESSAGE_TYPE_SENT) { wasSent = true; callBack(); } } } finally { if (cursor != null) { cursor.close(); } } } public interface SmsSendListener { // Passes true if the message was sent // Passes false if timed out public void onSmsSendEvent(boolean sent); } }
android – 通过意图发送短信
我想通过意图发送短信,但是当我使用此代码时,它会将我重定向到错误的联系人:
Intent intentt = new Intent(Intent.ACTION_VIEW);
intentt.setData(Uri.parse("sms:"));
intentt.setType("vnd.android-dir/mms-sms");
intentt.putExtra(Intent.EXTRA_TEXT, "");
intentt.putExtra("address", phone number);
context.startActivity(intentt);
为什么?
此外,我知道一种方法来跟踪短信发送,但我不知道如何编码:
Starting activity: Intent {
act=android.intent.action.SENDTO dat=smsto:%2B**XXXXXXXXXXXX** flg=0x14000000
cmp=com.android.mms/.ui.ComposeMessageActivity }
其中XXXXXXXXXXXX是电话号码.
解决方法:
我从一个博客开发了这个功能.您可以通过两种方式发送短信.
>打开本机短信作曲家
>编写您的消息并从您的Android应用程序发送
这是第一种方法的代码.
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/btnSendSMS"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Send SMS"
android:layout_centerInParent="true"
android:onClick="sendSMS">
</Button>
</RelativeLayout>
活动
public class SendSMSActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void sendSMS(View v)
{
String number = "12346556"; // The number on which you want to send SMS
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));
}
/* or
public void sendSMS(View v)
{
Uri uri = Uri.parse("smsto:12346556");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "Here you can set the SMS text to be sent");
startActivity(it);
} */
}
注意:-
在此方法中,您不需要AndroidManifest.xml文件中的SEND_SMS权限.
对于第二种方法,请参阅此BLOG.您将从此处找到一个很好的解释.
希望对你有帮助…
android 几种发送短信的方法
android中发送短信很简单,
首先要在Mainfest.xml中加入所需要的权限:
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_SMS"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
为了后面测试方便,干脆把SMS的所有权限加上。
方法1:
public class testSms extends Activity { ... private void send1(String phone, String message){ PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, testSms.class), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phone, null, message, pi, null); } }
方法2:
如果想知道短信发送后的状态,需要两个Receiver来实现
private void send2(String number, String message){ String SENT = "sms_sent"; String DELIVERED = "sms_delivered"; PendingIntent sentPI = PendingIntent.getActivity(this, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getActivity(this, 0, new Intent(DELIVERED), 0); registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { switch(getResultCode()) { case Activity.RESULT_OK: Log.i("====>", "Activity.RESULT_OK"); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Log.i("====>", "RESULT_ERROR_GENERIC_FAILURE"); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Log.i("====>", "RESULT_ERROR_NO_SERVICE"); break; case SmsManager.RESULT_ERROR_NULL_PDU: Log.i("====>", "RESULT_ERROR_NULL_PDU"); break; case SmsManager.RESULT_ERROR_RADIO_OFF: Log.i("====>", "RESULT_ERROR_RADIO_OFF"); break; } } }, new IntentFilter(SENT)); registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent){ switch(getResultCode()) { case Activity.RESULT_OK: Log.i("====>", "RESULT_OK"); break; case Activity.RESULT_CANCELED: Log.i("=====>", "RESULT_CANCELED"); break; } } }, new IntentFilter(DELIVERED)); SmsManager smsm = SmsManager.getDefault(); smsm.sendTextMessage(number, null, message, sentPI, deliveredPI); }
在模拟器上是看不到Receiver中的log信息的,据网上说在手机上是可以实现的,只可惜手中无机,也只能纸上谈兵了。
方法3:
上面都是发送文本文件,如果想发送一些非文本,比如加密数据,可以用以下方法:
private void send2(String number, String message){ SmsManager smsm = SmsManager.getDefault(); short port = 1000; PendingIntent pi = PendingIntent.getBroadcast(test.this, 0, new Intent(), 0); smsm.sendDataMessage(number, null, port, message.getBytes(), pi, null); }
方法4:
调用系统的短信界面,这个方法需要用户自己输入接收方的电话号码
private void send(String message){ Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", message); sendIntent.setType("vnd.android-dir/mms-sms"); }
这个方法自动设置接收方的号码
private void send1(String number, String message){ Uri uri = Uri.parse("smsto:" + number); Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri); sendIntent.putExtra("sms_body", message); startActivity(sendIntent); }
短信的接受,需要实现BroadcastReceiver类,监听系统消息
首先在Mainfest.xml中加入申明,SmsReceiver为实现类
<receiver android:name=".SmsReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
如果是方法3,使用sendDataMessage时需要加入
<receiver android:name=".SmsReceiver"> <intent-filter> <action android:name="android.intent.action.DATA_SMS_RECEIVED" /> <data android:scheme="sms" /> <data android:host="localhost" /> <data android:port="1000" /> </intent-filter> </receiver>
将其中的dat数据注释掉,模拟器上也可以接收到短信; port跟sendDataMessage中的端口值不一致时,也没有问题,太神奇了
public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String phone; String message; if(bundle != null){ Object[] pdus = (Object[])bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for(int i = 0; i < msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); phone = msgs[i].getOriginatingAddress(); message = msgs[i].getMessageBody(); } } } }
如果是sendDataMessage发送:
public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String phone; String message; if(bundle != null){ Object[] pdus = (Object[])bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for(int i = 0; i < msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); phone = msgs[i].getOriginatingAddress(); byte data[] = SmsMessage.createFromPdu((byte[])pdus[i]).getUserData(); message = new String(data); } } } }
不一样的地方是message的获取时使用getUserData()方法。
原文转自:http://blog.csdn.net/rangq1/article/details/5793953
我们今天的关于在Android中发送短信和android 发送短信的分享就到这里,谢谢您的阅读,如果想了解更多关于Android NDK之发送短信、android – 通过Intent发送短信,并知道短信是否已被发送、android – 通过意图发送短信、android 几种发送短信的方法的相关信息,可以在本站进行搜索。
本文标签: