致电给getSystemService(...)
之前不会工作onCreate()
由Android框架调用。当服务启动时会发生这种情况(即通过 [Context#bindService(...)][1] 或上下文#startService(...))。我在尝试致电时看到了相同的 NPEgetSystemService()
来自构造函数(即之前onCreate()
叫做)。
你只是简单地打电话(new TMLService()).ManageIncomingCall(incomingNumber)
,这不允许Android初始化你的服务,这就是这个NPE的根本原因。
为了使其正常工作,您必须启动该服务,然后调用该服务的方法。要调用一个方法,我认为你必须使用它来公开它AIDL。它可能比您需要的更复杂(也许?)。
我听说过意向服务是一种在服务中执行操作的更简单方法,没有 AIDL 的复杂性。以下是我认为 IntentService 应该如何工作的示例。尚未测试过,但希望它对入门有用。
呼叫接收器
public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyPhoneStateListener phoneListener = new MyPhoneStateListener(context);
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
我的电话状态监听器
public class MyPhoneStateListener extends PhoneStateListener {
private final Context mContext;
public MyPhoneStateListener(Context context) {
this.mContext = context;
}
public void onCallStateChanged(int state, String incomingNumber){
if (state == TelephonyManager.CALL_STATE_RINGING)
{
Log.d("DEBUG", "RINGING");
// OPTION 1: Do it on the main thread (might be bad :) )
//AudioManager audioManage = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
//audioManage.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// OPTION 2: Use an IntentService (a bit easier than AIDL)
Intent intent = new Intent(TMLIntentService.ACTION_SILENCE_RINGER);
mContext.startService(intent);
}
}
}
TML意图服务
public class TMLIntentService extends IntentService {
public static final String ACTION_SILENCE_RINGER = "org.example.intentservice.ACTION_SILENCE_RINGER";
@Override
public void onHandleIntent(Intent intent) {
if(ACTION_SILENCE_RINGER.equals( intent.getAction() ) {
AudioManager audioManage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManage.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
}
AndroidManifest.xml
<service android:name=".TMLIntentService">
<intent-filter>
<action android:name="org.example.intentservice.ACTION_SILENCE_RINGER" />
</intent-filter>
</service>
[1]: http://d.android.com/reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)