繁体   English   中英

用于通话的 Android 广播接收器不起作用? (棉花糖)

[英]Android Broadcast receiver for call not working? (Marshmallow)

我试图在接到电话后显示吐司,我已经实现了注册广播接收器所需的所有必要的东西,但它没有显示吐司。 我正在尝试在 Marshmallow 设备上运行此程序

MyCallReceiver.java -

package com.suhas.callreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class MyCallReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        // This code will execute when the phone has an incoming call

        // get the phone number
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Toast.makeText(context, "Call from:" +incomingNumber, Toast.LENGTH_LONG).show();
        Log.d("MyTrack call", "call receive");

    } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
            TelephonyManager.EXTRA_STATE_IDLE))
    {
        Toast.makeText(context, "Detected call hangup event", Toast.LENGTH_LONG).show();
    }
    else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
            TelephonyManager.EXTRA_STATE_OFFHOOK)) {
        // This code will execute when the call is disconnected

    }
}
}

AndroidManifest.xml -

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

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

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

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


    <activity android:name="com.example.suhas.msgmanager.MyDialog" android:launchMode="singleTask"
        android:theme="@android:style/Theme.Translucent" />

    <service android:name="com.example.suhas.msgmanager.ChatHeadService"></service>

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

    <activity android:name=".AddMessageActivity">
    </activity>
</application>

</manifest>

我有一个MainActivity和一个默认标签,上面写着Hello World

在棉花糖版本的情况下,我们有一个称为运行时权限的概念,它是在 Activity 中创建的,以便使用该权限。 运行时权限提供了一种在用户第一次运行活动时在运行时询问特定权限的方法。

这是您必须指定的两件事:

//为权限指定任意常数

  public final static int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 11;

// 在 OnCreate 方法中指定以下代码

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.READ_PHONE_STATE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_CONTACTS)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }
    }
}

//指定这个方法,它会在运行时弹出窗口询问用户权限

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
            }
            return;
        }
    }
}

这将提供一种使用 Marshmallow 设备的方法

您在接收器中给出了错误的包名称。

您应该定义接收器如下:

<receiver android:name="com.suhas.callreceiver.MyCallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

在目标 API 23 或更高版本中,根据 Marshmallow 应用程序需要运行时权限或在您的设备设置>>应用程序>>选择您的应用程序>>权限中手动

这个链接可以帮助你

我在我们的应用程序中成功实施。 从这里获取参考。

呼叫接收方法

public class CallReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    //Log.w("intent " , intent.getAction().toString());
    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    MyPhoneStateListener customPhoneListener = new MyPhoneStateListener();

    telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

    Bundle bundle = intent.getExtras();
    String phone_number = bundle.getString("incoming_number");

    String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
    // String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
    int state = 0;
    if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
        state = TelephonyManager.CALL_STATE_IDLE;
    }
    else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
        state = TelephonyManager.CALL_STATE_OFFHOOK;
    }
    else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
        state = TelephonyManager.CALL_STATE_RINGING;
    }
    if (phone_number == null || "".equals(phone_number)) {
        return;
    }
    customPhoneListener.onCallStateChanged(context, state, phone_number);
    Toast.makeText(context, "Phone Number " + phone_number , Toast.LENGTH_SHORT).show();
}}

侦听器方法

public class MyPhoneStateListener extends PhoneStateListener {

private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;

public void onCallStateChanged(Context context, int state, String phoneNumber){
    if(lastState == state){
        //No change, debounce extras
        return;
    }

    System.out.println("Number inside onCallStateChange : "  + phoneNumber);
    switch(state){
        case TelephonyManager.CALL_STATE_RINGING:
            isIncoming = true;
            callStartTime = new Date();

            Toast.makeText(context, "Incoming Call Ringing " + phoneNumber, Toast.LENGTH_SHORT).show();
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            if(lastState != TelephonyManager.CALL_STATE_RINGING){
                isIncoming = false;
                callStartTime = new Date();
                Toast.makeText(context, "Outgoing Call Started " + phoneNumber, Toast.LENGTH_SHORT).show();
            }
            break;

        case TelephonyManager.CALL_STATE_IDLE:
            //Went to idle-  this is the end of a call.  What type depends on previous state(s)
            if(lastState == TelephonyManager.CALL_STATE_RINGING){
                //Ring but no pickup-  a miss
                Toast.makeText(context, "Ringing but no pickup" + phoneNumber + " Call time " + callStartTime +" Date " + new Date() , Toast.LENGTH_SHORT).show();
            }
            else if(isIncoming){

                Toast.makeText(context, "Incoming " + phoneNumber + " Call time " + callStartTime  , Toast.LENGTH_SHORT).show();
            }
            else{

                Toast.makeText(context, "outgoing " + phoneNumber + " Call time " + callStartTime +" Date " + new Date() , Toast.LENGTH_SHORT).show();

            }

            break;
    }
    lastState = state;
}} }

获取完整解决方案的参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM