Android监听来电
下面是我的源码,从哪里判断监听到没监听到啊。
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
public final static String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*
* 按钮-监听电话
* @param v
*/
public void createPhoneListener(View v) {
TelephonyManager telephony = (TelephonyManager)getSystemService(
Context.TELEPHONY_SERVICE);
telephony.listen(new OnePhoneStateListener(),
PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* 电话状态监听.
* @author stephen
*/
class OnePhoneStateListener extends PhoneStateListener{
@Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.i(TAG, "[Listener]电话号码:"+incomingNumber);
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.i(TAG, "[Listener]等待接电话:"+incomingNumber);
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(TAG, "[Listener]电话挂断:"+incomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i(TAG, "[Listener]通话中:"+incomingNumber);
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}