最近开发项目中需要监听当前手机的状态(空闲,来电,接通),在来电时需要获取来电的手机号码。
写了一个服务一直运行在后台来对手机的状态进行监听,代码如下。
监听手机状态的Service:
import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; public class PhoneService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); manager.listen(new PhoneListener() , PhoneStateListener.LISTEN_CALL_STATE); } }
import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; public class PhoneListener extends PhoneStateListener { /** * state 当前手机的状态 * incomingNumber 呼入的手机号码 */ @Override public void onCallStateChanged(int state, String incomingNumber) { // TODO Auto-generated method stub super.onCallStateChanged(state, incomingNumber); switch (state) { case TelephonyManager.CALL_STATE_IDLE://空闲或者挂断 break; case TelephonyManager.CALL_STATE_OFFHOOK://接通 break; case TelephonyManager.CALL_STATE_RINGING://来电响铃 Log.d("TAG", "得到的来电号码是:" + incomingNumber); break; } } }
MainActivity:
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class MainActivity extends Activity { private Context context; public static final String ACTION = "recordingFlag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); //启动后台监听服务 Intent intent = new Intent(); intent.setAction(ACTION); intent.setPackage(getPackageName()); context.startService(intent); } }
<!-- 注册服务 --> <service android:name="com.example.service.PhoneService"> <intent-filter> <action android:name="recordingFlag"/> </intent-filter> </service>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />