The answer is simple: You cannot show an AlertDialog
from within a BroadcastReceiver
. You have to start an Activity
(maybe a transparent one) to show an AlertDialog
or simple show a Toast
message.
EDIT
I´m not sure if it is possible to show an Activity while a phone call is received. If yes, it´s not a good idea because You are laying that over the phonecall view from Your device.
2nd EDIT
Here is how to implement an incoming call receiver:
first, create a broadcastReceiver for incoming calls:
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
}
}
}
Then, register receiver in Your manifest:
<receiver android:name=".YourIncommingCallReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and add permission in manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
and delete this ACTION_POWER_CONNECTED reciever in Your code. This will only give a broadcast if device is connected or disconnected but not if a phone call comes in.