-1
public class MyReceiver extends BroadcastReceiver {
    private Context mcontext;
    TelephonyManager telephonyManager =
            (TelephonyManager) mcontext.getSystemService(Context.TELEPHONY_SERVICE);

public void onReceive(Context context, Intent intent) {
    mcontext = context;
    String action = intent.getAction();

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

我为来电接收器实现的上述代码..

4

1 回答 1

0

答案很简单:你不能AlertDialog在 a 中显示 a BroadcastReceiver。您必须启动一个Activity(可能是透明的)来显示一条消息AlertDialog或简单地显示一条Toast消息。

编辑

我不确定是否可以在接到电话时显示活动。如果是,这不是一个好主意,因为您将其放置在您设备的电话视图上。

第二次编辑

以下是如何实现来电接收器:

首先,为来电创建一个广播接收器:

    public class YourIncommingCallReceiver extends BroadcastReceiver {



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


             try{              
                 String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);                     

            if(phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)){

          //example from Android API       
          IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
          Intent batteryStatus = context.registerReceiver(null, ifilter);

          int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
          boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

                 if(isCharging==true){
                       Toast.makeText(mContext,"PLEASE UNPLUG", Toast.LENGTH_LONG).show();
                    }
                  }                
              }

    catch(Exception e)
              {
                 //show error message
              }          
            } 
         }

然后,在您的清单中注册接收器:

<receiver android:name=".YourIncommingCallReceiver" android:enabled="true">
            <intent-filter>
              <action android:name="android.intent.action.PHONE_STATE" />
                </intent-filter>
           </receiver>

并在清单中添加权限:

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

并在您的代码中删除此 ACTION_POWER_CONNECTED 接收器。这只会在设备连接或断开连接时发出广播,但如果有电话打进来则不会。

于 2016-02-16T13:37:35.333 回答