如何在手机通话或响铃时在后台运行服务?

时间:2018-06-12 09:58:42

标签: android

我试图在后台运行的服务中获取电话呼叫状态,但是当我拨打电话时,服务停止,在我完成呼叫服务后再次运行。

telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);

private class MyPhoneListener extends PhoneStateListener {

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                callState = "ringing";
                Log.d("xxx", " ----------  phone ringing  " );
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                callState = "active";
                Log.d("xxx", " ----------  phone is active  " );
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                callState = "idle";
                Log.d("xxx", " ----------  phone is idle  " );
                break;
        }
        super.onCallStateChanged(state, incomingNumber);
    }

}

1 个答案:

答案 0 :(得分:0)

我通过在前台运行服务解决了这个问题。

onCreate()方法中的

Intent notificationIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.app_icon)
            .setContentTitle("My Awesome App")
            .setContentText("Doing some work...")
            .setContentIntent(pendingIntent).build();

startForeground(1337, notification);