当用户插入辅助线时,我希望显示AlertDialog
消息。当用户拔下辅助线时,我希望警报消息消失。我不希望用户能够摆脱AlertDialog
消息,直到他/她拔掉辅助线。到目前为止,我的BroadcastReceiver
与Toast
一起使用。但它不适用于AlertDialog
。
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.widget.Toast;
public class AuxChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder removeAux = new AlertDialog.Builder(context);
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
final int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
removeAux.setOnDismissListener( new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
if (state==0) {
dialog.dismiss();
}
}
});
break;
case 1:
removeAux.setMessage("Unplug Aux!").create().show();
break;
default:
Toast toast3 = Toast.makeText(context, "No clue", Toast.LENGTH_SHORT);
toast3.show();
}
}
}
}
这是我使用Toast
的代码,但我不想要Toast
:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AuxChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
final int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Toast toast1 = Toast.makeText(context, "There is no aux cord detected", Toast.LENGTH_SHORT);
toast1.show();
break;
case 1:
Toast toast2 = Toast.makeText(context, "Aux Cord Detected, Please unplug it!", Toast.LENGTH_SHORT);
toast2.show();
break;
default:
Toast toast3 = Toast.makeText(context, "No clue", Toast.LENGTH_SHORT);
toast3.show();
}
}
}
}
答案 0 :(得分:1)
解决方案是在AlertDialog
而不是在接收器中创建onCreate()
,以便您可以在活动中的任何位置显示和关闭它 - 如下所示。首先声明你的AlertDialog
如此:
public class MainActivity extends Activity {
private AlertDialog alertDialog;
然后在onCreate()
:
alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Warning");
alertDialog.setMessage("Aux cord plugged in, please unplug...");
然后插入辅助线(case 1:
):
alertDialog.show();
当拔下电源线时(case 0:
):
alertDialog.dismiss();
答案 1 :(得分:0)
你必须像这样
创建一个警告对话框的方法 public AlertDialog CreateAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
alert.show();
return alert;
}
通过调用此方法
来触发所需的警报CreateAlert("YOUR TITTLE", "YOUR MESSAGE");