在Android上手机号码,可以使用TelephonyManager类来实现。以下是一个示例代码:
```java
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 检查权限并请求
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_CODE);
} else {
// 权限已授予,开始
startPhoneStateListener();
}
}
// 函数
private void startPhoneStateListener() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//电话空闲状态
break;
case TelephonyManager.CALL_STATE_RINGING:
//电话响铃状态
Log.d(TAG, "Incoming call: " + incomingNumber);
Toast.makeText(MainActivity.this, "Incoming call: " + incomingNumber, Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//电话接起状态
break;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
// 权限请求结果处理
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限已授予,开始
startPhoneStateListener();
} else {
// 权限被拒绝
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
```
在AndroidManifest.xml中添加以下权限:
```xml
```
这样当有电话呼入时,可以在Logcat中看到呼入号码,并且弹出一个Toast提示。