【问题标题】:Android Broadcast receiver for call not working? (Marshmallow)用于通话的 Android 广播接收器不起作用? (棉花糖)
【发布时间】:2016-08-11 17:48:09
【问题描述】:

我试图在接到电话后显示 toast,我已经实现了注册广播接收器所需的所有必要的东西,但它没有显示 toast。我正在尝试在 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。

【问题讨论】:

  • 你检查包名了吗。您的应用程序包名称是 com.example.suhas.msgmanager 并且您在 com.suhas.callreceiver 包中定义了接收者
  • 我在棉花糖设备上运行,那么如何在棉花糖中指定运行时权限。因为棉花糖需要运行时权限

标签: java android android-studio android-broadcastreceiver


【解决方案1】:

在棉花糖版本的情况下,我们有一个叫做运行时权限的概念,它是在 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 设备的方法

【讨论】:

  • 搜索了至少3个小时,终于找到了正确的答案。
【解决方案2】:

您在接收器中输入了错误的包名。

你应该如下定义接收者:

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

【讨论】:

【解决方案3】:

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

this link can help you

【讨论】:

    【解决方案4】:

    我在我们的 App 中成功实现了。从这里获取参考。

    呼叫接收方法

    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;
    }} }
    

    获取完整参考solution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2020-09-14
      • 1970-01-01
      相关资源
      最近更新 更多