Android监听手机电话状态与发送邮件通知来电号码的方法(基于PhoneStateListene实现)
本文实例讲述了Android监听手机电话状态与发送邮件通知来电号码的方法。分享给大家供大家参考,具体如下:
在android中可以用PhoneStateListener来聆听手机电话状态(比如待机、通话中、响铃等)。本例是通过它来监听手机电话状态,当手机来电时,通过邮件将来电号码发送到用户邮箱的例子。具体程序如下:
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.widget.TextView; public class A07Activity extends Activity { private TextView tv;//用来显示电话状态 private String emailReceiver="16*****85@qq.com"; //邮箱地址 private String emailSubject="你有来电信息,请查收!"; //作为邮件主题 /** Called when the activity is first created. */ @SuppressWarnings("static-access") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv=(TextView)findViewById(R.id.tv); PhoneCallListener pcl=new PhoneCallListener(); TelephonyManager tm=(TelephonyManager)getSystemService(TELEPHONY_SERVICE); tm.listen(pcl, pcl.LISTEN_CALL_STATE); } public class PhoneCallListener extends PhoneStateListener{ public void onCallStateChanged(int state,String incomingNumber){ //需要重写onCallStateChanged方法 switch(state){ case TelephonyManager.CALL_STATE_IDLE: tv.setText("CALL_STATE_IDLE"); break; case TelephonyManager.CALL_STATE_OFFHOOK: tv.setText("CALL_STATE_OFFHOOK"); break; case TelephonyManager.CALL_STATE_RINGING: tv.setText("来电号码"+incomingNumber); //如果有人打来电话,就会自动发送邮件到邮箱通知用户来电号码 //设置来电时发送邮件 Intent i=new Intent(android.content.Intent.ACTION_SEND); i.setType("plain/text"); i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{emailReceiver.toString()}); i.putExtra(android.content.Intent.EXTRA_SUBJECT, emailSubject.toString()); i.putExtra(android.content.Intent.EXTRA_TEXT, "来电电话"+incomingNumber); startActivity(Intent.createChooser(i, "来电信息")); break; default: break; } super.onCallStateChanged(state, incomingNumber); } } }
其中还需要在AndroidManifest.xml中添加几个相应的权限:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.my.a07" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".A07Activity" 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> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> </manifest>
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android控件用法总结》及《Android开发入门与进阶教程》
希望本文所述对大家Android程序设计有所帮助。
赞 (0)