代码如下所示:
1)在清单文件中声明新活动。(AndroidManifest.xml):
<activity
android:name=".ConfirmDialog"
android:label="@string/app_name"
android:theme="@android:style/Theme.Dialog"
android:launchMode="singleTask"
android:screenOrientation="vertical">
</activity>
2)创建新类扩展活动。(公共类 ConfirmDialog 扩展了 Activity)
private static final int DIALOG_YES_NO_MESSAGE = 1;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_YES_NO_MESSAGE:
return new AlertDialog.Builder(ConfirmDialog.this)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.app_name)
.setMessage(R.string.ask_confirm)
.setPositiveButton(R.string.ask_confirm_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
finish();
}
})
.setNegativeButton(R.string.ask_confirm_no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
finish();
}
})
.create();
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog(DIALOG_YES_NO_MESSAGE);
}
3) 在phonestatelistener 中使用新创建的活动。(公共类监听器扩展了 PhoneStateListener)
public void onCallStateChanged(int state, String incomingNumber){
switch(state){
case TelephonyManager.CALL_STATE_OFFHOOK:
confirmCall();
break;
}
super.onCallStateChanged(state, incomingNumber);
}
private void confirmCall(){
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.ConfirmDialog"));
mContext.startActivity(intent);
}