我尝试检查我的手机是否在使用吐司打电话后显示来电号码,但是它无效,它在号码中显示空值(我使用自己的手机测试应用程序而不是模拟器)。 这是代码:
package com.practise.calling;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView1;
Boolean prevState=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
Toast.makeText(getApplicationContext(), "Phone Is Riging",
Toast.LENGTH_LONG).show();
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
Toast.makeText(getApplicationContext(),
"Phone is Currently in A call", Toast.LENGTH_LONG)
.show();
prevState = true;
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
Toast.makeText(getApplicationContext(),
"phone is neither ringing nor in a call"+incomingNumber,
Toast.LENGTH_LONG).show();
Log.i("NUMBER",incomingNumber);
if(prevState==true){
Intent in = new Intent(MainActivity.this,SecondActivity.class);
in.putExtra("NUMBER",incomingNumber);
startActivity(in);
}
prevState=false;
}
}
};
telephonyManager.listen(callStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
@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;
}
}
答案 0 :(得分:1)
不知怎的,你忘了在你的CALL_STATE_RINGING和CALL_STATE_OFFHOOK中添加incomingNumber吗?
更改此2行
Toast.makeText(getApplicationContext(), "Phone Is Riging"+incomingNumber,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Phone is Currently in A call"+incomingNumber, Toast.LENGTH_LONG)
.show();
答案 1 :(得分:1)
当通话状态为"振铃"那你就可以得到电话号码。否则它无法获得传入的号码。
代码:
PhoneStateListener.CALL_STATE_RINGING:
String number = incomingNumber;
答案 2 :(得分:0)
尝试在BroadcastReceiver中使用它,它将起作用....
String incomingNumber;
if(state==TelephonyManager.CALL_STATE_RINGING){
incomingNumber=intent.getStringExtra("incoming_number");
Toast.makeText(getApplicationContext(), "Phone Is Ringing "+incomingNumber,
Toast.LENGTH_LONG).show();
}else if (state==TelephonyManager.CALL_STATE_IDLE) {
Toast.makeText(context, "Call is Idle "+incomingNumber, Toast.LENGTH_SHORT).show();
} else if (state==TelephonyManager.CALL_STATE_OFFHOOK) {
Toast.makeText(context, "Offhook State "+incomingNumber, Toast.LENGTH_SHORT).show();
}