android技术-发短信、打电话、发邮件

短信

1.发送短信

需要权限 android.permission.SEND_SMS

使用android.telephony.SmsManager类

普遍使用的方式

 

private void sendSmsMessage(String address,String message)throws Exception
    {
        SmsManager smsMgr = SmsManager.getDefault();
        Intent sent = new Intent();
        sent.setAction("com.send");
        PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, sent, 0);
        Intent delivery = new Intent();
        delivery.setAction("com.delivery");
        PendingIntent deliveryIntent = PendingIntent.getBroadcast(this, 0, delivery , 0);
        smsMgr.sendTextMessage(address, null, message, sentIntent, deliveryIntent);
    }

 BroadcastReceiver send = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			if("com.send".equals(intent.getAction()))
				Toast.makeText(TelephonyDemo.this, "SMS send  success", 
	                	Toast.LENGTH_LONG).show();
		}
	};
	 BroadcastReceiver delivery = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				if("com.delivery".equals(intent.getAction()))
					Toast.makeText(TelephonyDemo.this, "SMS delivery success", 
	                	Toast.LENGTH_LONG).show();
			}
		};

 

另两种方式

sendDataMessage()接受一个附加参数以指定一个端口号,还会接受一个字节数组(不是一个String 消息)。

sendMultipartTextMessage()支持在整条消息大于SMS规范所允许的大小时发送文本消息。

SmsManager类提供了divideMessage()方法来帮助将较长的消息拆分为多个部分。

2.监视传入的SMS消息

需要权限:android.permission.RECEIVE_SMS

当设备收到SMS消息时,android会发出广播。该广播的action是android.provider.Telephony.SMS_RECEIVED

该action在文档上找不到,在源码的android.provider包下能找到Telephony类,其中有这么个action,同时有参数说明

 

  /**
             * Broadcast Action: A new text based SMS message has been received
             * by the device. The intent will have the following extra
             * values:</p>
             *
             * <ul>
             *   <li><em>pdus</em> - An Object[] od byte[]s containing the PDUs
             *   that make up the message.</li>
             * </ul>
             *
             * <p>The extra values can be extracted using
             * [email protected] #getMessagesFromIntent(Intent)}.</p>
             *
             * <p>If a BroadcastReceiver encounters an error while processing
             * this intent it should set the result code appropriately.</p>
             */
            @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
            public static final String SMS_RECEIVED_ACTION =
                    "android.provider.Telephony.SMS_RECEIVED";

 

具体实现

 

<receiver android:name="MySMSMonitor">
			<intent-filter>
				<action android:name="android.provider.Telephony.SMS_RECEIVED" />
			</intent-filter>
		</receiver>

public class MySMSMonitor extends BroadcastReceiver {

	private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
    public void onReceive(Context context, Intent intent)
    {
		if(intent!=null && intent.getAction()!=null && 
	        ACTION.compareToIgnoreCase(intent.getAction())==0)
	    {
	        Object[]pduArray = (Object[]) intent.getExtras().get("pdus");
	        SmsMessage[] messages = new SmsMessage[pduArray.length];
	        for (int i = 0; i<pduArray.length; i++) {
	            messages[i] = SmsMessage.createFromPdu((byte[])pduArray [i]);
	            Log.d("MySMSMonitor", "From: " + messages[i].getOriginatingAddress());
	            Log.d("MySMSMonitor", "Msg: " + messages[i].getMessageBody());
	        }
	        Log.d("MySMSMonitor","SMS Message Received.");
	    }
	}
}

 

 

访问SMS文件夹

需要权限 android.permission.READ_SMS

要读取SMS消息,必须对SMS收件箱进行查询。如下所示

 

public class SMSInboxDemo extends ListActivity {

    private ListAdapter adapter;
    private static final Uri SMS_INBOX = Uri.parse("content://sms/inbox");

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        Cursor c = getContentResolver()
                .query(SMS_INBOX, null, null, null, null);
        startManagingCursor(c);
        String[] columns = new String[] { "body" };
        int[] names = new int[] { R.id.row };
        adapter = new SimpleCursorAdapter(this, R.layout.sms_inbox, c, columns,
                names);

        setListAdapter(adapter);
    }
}

 

以下是完整的SMS文件夹列表和每个文件夹的URI

所有文件夹  content://sms/all

收件箱 content://sms/inbox

已发送 content://sms/sent

草稿 content://sms/draft

发件箱 content://sms/outbox

发送失败 content://sms/failed

排队消息 content://sms/queued

未送达 content://sms/undelivered

对话 content://sms/conversations

 

 

发送电子邮件

android没有提供API来发送电子邮件,必须使用已注册的电子邮件应用程序。可以使用ACTION_SEND来启动电子邮件应用程序

 

 Intent emailIntent=new Intent(Intent.ACTION_SEND);

        String subject = "Hi!";
        String body = "hello from android....";

        String[] extra = new String[]{"[email protected]"};

        emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        emailIntent.putExtra(Intent.EXTRA_TEXT, body);
		emailIntent.putExtra(Intent.EXTRA_EMAIL, extra);
        emailIntent.setType("message/rfc822");

        startActivity(emailIntent);

 

可以向电子邮件Intent添加的其他”extra”消息包括EXTRA_CC(抄送)、EXTRA_BCC(密送)。如果希望在邮件中发送电子邮件附件。可以使用以下代码。

 

emailIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(new File(myFileName)));

 

 

打电话

播出电话的最简单方法是使用以下代码

 

Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:12345678911"));
startActivity(intent);

 

这段代码需要android.permission.CALL_PHONE权限。如果没有此权限,可以将Intent的操作更改为Intent.ACTION_VIEW.这会导致Dialer应用程序显示要拨打的目标号码,用户需要按下Send按钮才能开始呼叫。

 

 

监听电话状态

监听电话状态最简单的办法是在”android.intent.action.PHONE_STATE”上实现一个广播接收程序。可采用与上面监听传入的SMS消息相同的方式。

该action可以在文档中找到

http://developer.android.com/reference/android/telephony/TelephonyManager.html#ACTION_PHONE_STATE_CHANGED

另一种方式是使用TelephonyManager

 

 private TelephonyManager teleMgr = null;
 private MyPhoneStateListener myListener = null;

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        teleMgr = 
                (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        myListener = new MyPhoneStateListener();
    }

 @Override
    public void onResume() {
    	super.onResume();
    	Log.d("PhoneCallDemo", "In onResume");
        teleMgr.listen(myListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public void onPause() {
    	super.onPause();
    	Log.d("PhoneCallDemo", "In onPause");
        teleMgr.listen(myListener, PhoneStateListener.LISTEN_NONE);
    }

public class MyPhoneStateListener extends PhoneStateListener
    {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch(state)
            {
                case TelephonyManager.CALL_STATE_IDLE:
                    logText = "call state idle...incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                	logText = "call state ringing...incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                	logText = "call state Offhook...incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
                default:
                	logText = "call state ["+state+"]incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
            }
            print(logText);
        }
    }

1 comment

  1. increase height 2013 年 8 月 13 日 at 下午 2:30

    A lot of times I get really exhausted in sorting all the subject for myself and having to end up with the concrete thought.