您的位置:首页 > 其它

Andriod 拨打电话、读取、拦截短信及发送短信

2014-06-11 18:38 232 查看
XML的内容

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.helloworld"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
		<uses-permission android:name="android.permission.READ_SMS" />
		<uses-permission android:name="android.permission.SEND_SMS"/>
		<uses-permission android:name="android.permission.CALL_PHONE"/>
		<uses-permission android:name="android.permission.RECEIVE_SMS"/>
		
		
		
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        
        <activity
            android:name="com.android.helloworld.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


代码

package com.android.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.*;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.net.Uri;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.widget.Toast; //提示文字

import java.util.ArrayList; //数组

import android.telephony.SmsManager;//短信发送相关
import android.app.PendingIntent; //返回值处理
import android.content.BroadcastReceiver;//拦截广播消息
import android.telephony.SmsMessage;//短消息

public class MainActivity extends Activity {

	private ProgressDialog progressDialog;
	public EditText editText;
	private IntentFilter mFilter;
	public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent intent) {
			String action = intent.getAction();
			if (SMS_RECEIVED_ACTION.equals(action)) {
								
				Bundle bundle = intent.getExtras();
				if (bundle != null) {
					Object[] pdus = (Object[]) bundle.get("pdus");
					for (Object pdu : pdus) {
						SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
						String content=message.getMessageBody();//获取短信内容
						String sender = message.getOriginatingAddress();//获取发送号码
						Log.v("TAG", sender.toString());						
						Toast.makeText(MainActivity.this, "接收到的短信内容:\r\n"+content,
								Toast.LENGTH_SHORT).show();					
						Log.v("TAG", "111!!!!");						
						if (sender.indexOf(editText.getText().toString()) != -1) {//判断发送号码是否存在过滤号码
							// 屏蔽指定手机号的短信,这里还可以时行一些处理,如把这个信息发送到第三人的手机等等。
							Log.v("TAG", "2222222222222xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!!!!");
							abortBroadcast();
						}
					}
				}
			}
		}
	};
	
	
	@Override
	protected void onResume() {
		super.onResume();
		mFilter = new IntentFilter();
		mFilter.addAction(SMS_RECEIVED_ACTION);
		this.registerReceiver(mReceiver, mFilter);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(mReceiver);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		editText = (EditText) findViewById(R.id.editText1);
		editText.setText("10086");
			
		

		final Button Button1 = (Button) findViewById(R.id.button1);
		Button1.setOnClickListener(new OnClickListener() { // 实现行为功能
			public void onClick(View v) {
				// Intent intent = new Intent(Intent.ACTION_VIEW);
				// intent.setType("vnd.android-dir/mms-sms");
				// intent.setData(Uri.parse("content://mms-sms/conversations/"));//此为号码
				// startActivity(intent);
				getSmsAndSendBack();
			}
		});

		final Button btn2 = (Button) findViewById(R.id.button2);
		btn2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.v("TAG", "123");

				progressDialog = ProgressDialog.show(MainActivity.this,
						"加载中...", "请等待...", true, false);

				// 新建线程
				new Thread() {

					@Override
					public void run() {
						// 需要花时间计算的方法
						try {
							Thread.sleep(4 * 1000);
						} catch (Exception e) {
							// TODO: handle exception
						}

						// 向handler发消息
						handler.sendEmptyMessage(0);
					}
				}.start();

			}

		});

		final Button SmsBtn = (Button) findViewById(R.id.button3);
		SmsBtn.setOnClickListener(new OnClickListener() {// 发送短信
			public void onClick(View v) {
				Log.v("TAG", editText.getText().toString());

				String SENT_SMS_ACTION = "SENT_SMS_ACTION";
				String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

				Intent sentIntent = new Intent(SENT_SMS_ACTION);
				PendingIntent sentPI = PendingIntent.getBroadcast(
						MainActivity.this, 0, sentIntent, 0);

				// register the Broadcast Receivers
				MainActivity.this.registerReceiver(new BroadcastReceiver() {
					@Override
					public void onReceive(Context _context, Intent _intent) {
						switch (getResultCode()) {
						case Activity.RESULT_OK:
							Toast.makeText(MainActivity.this, "短信发送成功",
									Toast.LENGTH_SHORT).show();
							break;
						case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
							break;
						case SmsManager.RESULT_ERROR_RADIO_OFF:
							break;
						case SmsManager.RESULT_ERROR_NULL_PDU:
							break;
						}
					}
				}, new IntentFilter(SENT_SMS_ACTION));

				Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
				PendingIntent deliverPI = PendingIntent.getBroadcast(
						MainActivity.this, 0, deliverIntent, 0);
				MainActivity.this.registerReceiver(new BroadcastReceiver() {
					@Override
					public void onReceive(Context _context, Intent _intent) {
						Toast.makeText(MainActivity.this, "收信人已经成功接收",
								Toast.LENGTH_SHORT).show();
					}
				}, new IntentFilter(DELIVERED_SMS_ACTION));

				SmsManager smsManager = SmsManager.getDefault();
				String strMessage = "我的安卓测试程序--->短信1234567890!!@##@!¥%@!#%#@¥%@%";
				ArrayList<String> list = smsManager.divideMessage(strMessage); // 因为一条短信有字数限制,因此要将长短信拆分
				for (String text : list) {
					smsManager.sendTextMessage(editText.getText().toString(),
							null, text, sentPI, deliverPI);
				}

			}
		});

		final Button DailBtn = (Button) findViewById(R.id.button4);
		DailBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {// 打电话
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
						+ editText.getText().toString()));
				startActivity(intent);
			}
		});

	}

	/**
	 * 用Handler来更新UI
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			// 关闭ProgressDialog
			progressDialog.dismiss();

		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private static final String LOG_TAG = "Sms Query";

	/**
	 * 读取短信
	 * 
	 * @return
	 */
	public String getSmsAndSendBack() {
		String[] projection = new String[] { "_id", "address", "person", "body" };
		StringBuilder str = new StringBuilder();
		try {
			Cursor myCursor = managedQuery(Uri.parse("content://sms/inbox"),
					projection, null, null, "date desc");
			str.append(processResults(myCursor, true));
			str.append("getContactsAndSendBack has executed!");
			/*
			 * myCursor = managedQuery(Uri.parse("content://sms/inbox"), new
			 * String[] { "_id", "address", "read" }, " address=? and read=?",
			 * new String[] { "12345678901", "0" }, "date desc");
			 */

		} catch (SQLiteException ex) {
			Log.d(LOG_TAG, ex.getMessage());
		}
		return str.toString();
	}

	/**
	 * 处理短信结果
	 * 
	 * @param cur
	 * @param all
	 *            用来判断是读一条还是全部读。后来没有用all,可以无视
	 */
	private StringBuilder processResults(Cursor cur, boolean all) {
		// TODO Auto-generated method stub
		StringBuilder str = new StringBuilder();
		if (cur.moveToFirst()) {

			String name;
			String phoneNumber;
			String sms;

			int nameColumn = cur.getColumnIndex("person");
			int phoneColumn = cur.getColumnIndex("address");
			int smsColumn = cur.getColumnIndex("body");
			int nNum = 0;
			do {
				// Get the field values
				name = cur.getString(nameColumn);
				phoneNumber = cur.getString(phoneColumn);
				sms = cur.getString(smsColumn);

				str.append("{");
				str.append(name + ",");
				str.append(phoneNumber + ",");
				str.append(sms);
				str.append("}");

				Log.v(LOG_TAG, ++nNum + "." + "[" + phoneNumber + "]" + "["
						+ sms + "]");

				if (null == sms)
					sms = "";

				/*
				 * if (all)
				 * mView.loadUrl("javascript:navigator.SmsManager.droidAddContact('"
				 * + name + "','" + phoneNumber + "','" + sms +"')"); else
				 * mView.loadUrl("javascript:navigator.sms.droidFoundContact('"
				 * + name + "','" + phoneNumber + "','" + sms +"')");
				 */

			} while (cur.moveToNext());
			/*
			 * if (all)
			 * mView.loadUrl("javascript:navigator.SmsManager.droidDone()");
			 * else mView.loadUrl("javascript:navigator.sms.droidDone();");
			 */
		} else {
			str.append("no result!");
			/*
			 * if(all) mView.loadUrl("javascript:navigator.SmsManager.fail()");
			 * else
			 * mView.loadUrl("javascript:navigator.sms.fail('None found!')");
			 */
		}

		return str;
	}// processResults

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: