【发布时间】:2020-06-27 07:48:11
【问题描述】:
根据文档,PhoneStateListener 是一个处理手机状态变化的类, onCallStateChanged 方法应该获取 2 个参数,状态(整数)和字符串 -> 电话号码。
package com.eddieharari.shippit;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneStateBcListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state,String phone) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("SHIPIT","Call State Idle");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("SHIPIT","Call State OffHook:");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d("SHIPIT","Call State Ringing:"+phone);
break;
}
if (phone == null) {
Log.d("SHIPPIT","Number is null");
} else Log.d("SHIPPIT","Number is not Null");
}
}
上面的代码是我的 PhoneStateListener 类,我从服务中调用它:
package com.eddieharari.shippit;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class GetCallService extends Service {
TelephonyManager telephony;
PhoneStateBcListener myListener = new PhoneStateBcListener();
@Override
public IBinder onBind(Intent i) {
return null;
}
@Override
public void onCreate() {
Log.d("SHIPT","Inside Oncreate");
Log.d("SHIPPIT","Started Receiver");
telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(myListener, PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
public void onStart(Intent i, int start ) {
Log.d("SHIPIT","Inside START");
}
@Override
public void onDestroy() {
Log.d("SHIPIT","Inside Ondestroy");
}
}
我从我的主要活动开始服务,但是我从来没有得到号码(它不是 NULL,但它是一个空字符串)。我已经看到人们使用广播接收器的例子,但我不明白为什么文档声明该号码应该可以使用 PhoneStateListener。
这是我的清单:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.READ_PHONE_STATE"> </uses-permission>
<uses-permission android:name="android.permission.READ_CALL_LOG"> </uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GetCallService"
android:enabled="true" />
</application>
【问题讨论】:
-
我有一些进展,因为似乎有了新的 API 级别,我需要询问运行时的权限,但是即使我只能获得传入的号码而不是传出的号码,而且它也无法正常工作模拟器,仅在实际设备上...
标签: android service permissions state phone-state-listener