android - 接听或调用电话时 Toast 未出现

标签 android android-service android-broadcast

调用助手类

package com.example.callrecording;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class CallHelper {

    private class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                // called when someone is ringing to this phone

                Toast.makeText(ctx, 
                        "Incoming: "+incomingNumber, 
                        Toast.LENGTH_LONG).show();
                break;
            }
        }
    }

    /**
     * Broadcast receiver to detect the outgoing calls.
     */
    public class OutgoingReceiver extends BroadcastReceiver {
        public OutgoingReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            Toast.makeText(ctx, 
                    "Outgoing: "+number, 
                    Toast.LENGTH_LONG).show();
        }

    }

    private Context ctx;
    private TelephonyManager tm;
    private CallStateListener callStateListener;

    private OutgoingReceiver outgoingReceiver;

    public CallHelper(Context ctx) {
        this.ctx = ctx;

        callStateListener = new CallStateListener();
        outgoingReceiver = new OutgoingReceiver();
    }

    /**
     * Start calls detection.
     */
    public void start() {
        tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        ctx.registerReceiver(outgoingReceiver, intentFilter);
    }

    /**
     * Stop calls detection.
     */
    public void stop() {
        tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
        ctx.unregisterReceiver(outgoingReceiver);
    }

}

主要 Activity

package com.example.callrecording;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private boolean detectEnabled;
    private TextView textViewDetectState;
    private Button buttonToggleDetect;
    private Button buttonExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textViewDetectState = (TextView) findViewById(R.id.textViewDetectState);
        buttonToggleDetect = (Button) findViewById(R.id.buttonDetectToggle);
        buttonToggleDetect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setDetectEnabled(!detectEnabled);
            }
        });

        buttonExit = (Button) findViewById(R.id.buttonExit);
        buttonExit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setDetectEnabled(false);
                MainActivity.this.finish();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private void setDetectEnabled(boolean enable) {
        detectEnabled = enable;

        Intent intent = new Intent(this, callDetectService.class);
        if (enable) {
             // start detect service 
            startService(intent);

            buttonToggleDetect.setText("Turn off");
            textViewDetectState.setText("Detecting");
        }
        else {
            // stop detect service
            stopService(intent);

            buttonToggleDetect.setText("Turn on");
            textViewDetectState.setText("Not detecting");
        }
    }
}

调用检测类

package com.example.callrecording;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class callDetectService extends Service {

    private CallHelper callHelper;

    public callDetectService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        callHelper = new CallHelper(this);

        int res = super.onStartCommand(intent, flags, startId);
        callHelper.start();
        return res;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        callHelper.stop();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // not supporting binding
        return null;
    }
}

list 文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.callrecording"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".CallDetectService"
            android:enabled="true"
            android:exported="false" >
        </service>
    </application>


</manifest>

这是调用助手类中的代码,我正在尝试显示 toast ,但我无法执行相同的操作。 所有文件都已共享。 代码中有什么我可以更改的吗,基本上我正在尝试开发通话记录器,也请根据此分享反馈。 提前谢谢你,我将非常感激。

最佳答案

你应该使用广播接收器来获取通话细节,你应该在你的代码中使用类似的东西,作为引用看看这段代码

public class CallBroadcastReceiver extends BroadcastReceiver {
    Context contxt;
    TelephonyManager telephony;
    private boolean ring = false;
    private boolean callReceived = false;
    static String callerPhoneNumber = "";
    SharePreferenceClass preferenceClass;

    @Override
    public void onReceive(final Context context, Intent intent) { // Get the
                                                                    // current
        // Phone State
        contxt = context;
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        preferenceClass = new SharePreferenceClass(contxt);
        telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(),
                PhoneStateListener.LISTEN_CALL_STATE);
        Bundle bundle = intent.getExtras();
        callerPhoneNumber = bundle.getString("incoming_number");
        if (state == null) {
            callerPhoneNumber = intent
                    .getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            System.out.println("CallFinishingBroadcastReceiver out going "
                    + callerPhoneNumber);
            return;
        }

        // If phone state "Rininging"
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            ring = true;
            System.out.println("CallFinishingBroadcastReceiver ringing "
                    + callerPhoneNumber);
        }

        // If incoming call is received
        if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            callReceived = true;
            System.out.println("offhook " + callerPhoneNumber);
        }

        // If phone is Idle
        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            // If phone was ringing(ring=true) and not
            // received(callReceived=false) , then it is a missed call
            System.out.println("MISSED " + callerPhoneNumber);
            if (ring == true && callReceived == false) {
                System.out.println("CallFinishingBroadcastReceiver idle "
                        + callerPhoneNumber);

            } else if (ring == true && callReceived == true) {
                System.out.println("CallFinishingBroadcastReceiver INCOMING "
                        + callerPhoneNumber);

            }

            ring = false;
            callReceived = false;

        }
    }
}

在 list 文件中注册广播接收器

<receiver android:name=".CallBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" >
                </action>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
        </receiver>

关于android - 接听或调用电话时 Toast 未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27480690/

相关文章:

Android - 广播接收器和服务之间的区别

android - Gradle 同步失败 : Version: 5. 8.0 低于 google-services 插件所需的最低版本 (9.0.0)

android - 如果在服务类上调用 bindService 之后调用 startService 会发生什么情况?

android - 从 android 中的信使/处理程序获取待处理消息的列表

java - "Cannot perform this action on a not sealed instance"java.lang.IllegalStateException异常

android - 如何让应用程序的广播接收器在后台不运行服务的情况下继续收听

android.database.sqlite.SQLiteException 语法错误(代码 1)

java - "xx free bytes and xx until OOM"是什么意思?

android - 在 Android 上呈现动态表单的方法?

android - 单击按钮时触发 BroadcastReceiver