You can display the Dialog
from the service, by setting the window type as TYPE_SYSTEM_ALERT
. Remember to communicate back the action taken by the user using the JsResult
instance passed to onJsAlert
.
// maintain reference to JsResult instance passed to onJsAlert, in order
// communicate back the action taken by the user.
private JsResult mResult;
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
mResult = result;
AlertDialog dialog = new AlertDialog.Builder(MyService.this)
.setTitle("Custom Dialog")
.setMessage("This is our custom dialog, not the one served by JsDialogHelper")
.setOnCancelListener(new CancelListener())
.setNegativeButton("Cancel", new CancelListener())
.setPositiveButton("Ok", new PositiveListener())
.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
return true;
}
});
private class CancelListener implements DialogInterface.OnCancelListener,
DialogInterface.OnClickListener {
@Override
public void onCancel(DialogInterface dialogInterface) {
mResult.cancel();
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mResult.cancel();
}
}
private class PositiveListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mResult.confirm();
}
}
Add the required permissions to the manifest file:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Alternate solution:
If the web application can be built specific to android webview, then you can create Javascript interfaces which will allow Javascript code to directly invoke the Android code which in turn displays the dialog for you. This avoids the JsDialogHelper
route.
- Define a javascript interface:
public class WebAppInterface {
Context context;
WebAppInterface(Context c) {
context = c;
}
// Annotation required for api >= 17
@JavascriptInterface
public void showDialog() {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Custom Dialog")
.setMessage("This is our custom dialog, not the one served by JsDialogHelper")
.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
}
- Bind the interface between Javascript and Android code, using addJavascriptInterface.
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
- Use the interface in Javascript code.
<input type="button" value="Display dialog" onClick="displayDialog()" />
<script>
function displayDialog() {
//alert("Javascript Dialog");
Android.showDialog();
}
</script>
</input>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…