package com.tx.testsms;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final int MSG_RECEIVED_CODE = 1;
private SmsObserver mSmsObserver;
private Handler mHandler;
private EditText metPhone;
private TextView mtvCode;
private Button mbtnButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
metPhone = (EditText) findViewById(R.id.phone);
mbtnButton = (Button) findViewById(R.id.btn);
mtvCode = (TextView) findViewById(R.id.code);
/**
* 设置手机号,拦截固定的手机号
*/
mbtnButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mSmsObserver.setTel_phone(metPhone.getText().toString());
}
});
/**
* 在子线程中更新UI
*/
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what == MSG_RECEIVED_CODE){
mtvCode.setText("四位短信验证码为:"+msg.obj.toString());
Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
}
}
};
<span style="color:#ff0000;">/**
* 实例化ContentObserver,注册短信监听
*/
mSmsObserver = new SmsObserver(getApplicationContext(), mHandler);
Uri uri = Uri.parse("content://sms");
getContentResolver().registerContentObserver(uri, true, mSmsObserver);</span>
}
/**
* 由于 ContentObserver 的生命周期不同步于 Activity 和 Service ,
* 因此需要手动取消注册
*
*/
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
<span style="color:#ff0000;">getContentResolver().unregisterContentObserver(mSmsObserver);</span>
}
}