在充电和接听来电时,手机中的AlertDialog

时间:2014-02-24 20:28:43

标签: android

  

我是Android编程的新手。这是我的代码。我希望在手机充电时显示屏幕上的警告对话框,并且在来电同时接到来电,虽然我采取了适当的权限但是没有用。

  public class Callprotection extends BroadcastReceiver {
  private Context mContext;
  private Intent mIntent;

@Override
public void onReceive(Context context, Intent intent) {
    mContext = context;
    mIntent = intent;
    TelephonyManager tm = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    int events = PhoneStateListener.LISTEN_CALL_STATE;
    tm.listen(phoneStateListener, events);
}

    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        String callState = "UNKNOWN";
        switch (state) {
        case TelephonyManager.CALL_STATE_RINGING:
            // write your code display Toast or Dialog
            if(isCharging()){
            new AlertDialog.Builder(mContext)
            .setTitle("ALERT!!")
            .setMessage("PLEASE UNPLUG THEN ATTEND!")
            .setNeutralButton("Close", new      DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sumthin) {
            // do nothing – it will close on its own
            }
            })
            .show(); 
            //}
            break;
        }
        Log.i(">>>Broadcast", "onCallStateChanged " + callState);
        super.onCallStateChanged(state, incomingNumber);
    }
    }
};

public boolean isCharging() {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent mIntent = mContext.getApplicationContext().registerReceiver(null,         ifilter);
    int status = mIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean bCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
    return bCharging;
}

}

 //Manifest

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <receiver
        android:name=".Callprotection"
        android:enabled="true" >
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" >
            </action>
        </intent-filter>
    </receiver>

    <activity
        android:name="com.phone.phoneprotection.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.phone.phoneprotection.MAINACTIVITY" />

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

1 个答案:

答案 0 :(得分:-1)

尝试添加

<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />

到您活动的xml中的<intent-filter>标记