#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
//Do anything with result here :D
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getText().toString()));
startActivity(browserIntent);
mScannerView.resumeCameraPreview(this);
}
}
I want to directly open the URL once scanning is done and then reopen the camera. Can anyone please help me ?
Use a webview load the URL like below:
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
Try and create your own activity to handle request to open URL .
When I started learning about android and its intents I found it very confusing. But category BROWSABLE in the Manifest does the following.
The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message.
Read more on: http://developer.android.com/guide/components/intents-filters.html
The two other answers opens the standard web browser and goes to the address specified. If you want a custom browser make the second activity like a web view like this example.
Related
I've been developing an Android app for my business for a long time and it's been working fine, using a webview and calling back and forth between native features. In case it's relevant, here's the Java entry point to my app:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webview);
final Context that = this;
myWebView.addJavascriptInterface(new WebAppInterface(this, this), "Android");
myWebView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
myWebView.evaluateJavascript("pageFinished()", null);
}
});
pm = this.getPackageManager();
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setDomStorageEnabled(true);
WebView.setWebContentsDebuggingEnabled(true);
Window window = getWindow();
//window.setStatusBarColor(Color.parseColor("#3596d4"));
myWebView.loadUrl("file:///android_asset/index.html");
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
mDetector = new GestureDetectorCompat(that, this);
myWebView.setOnTouchListener(touchListener);
}
Now when I set the minimum version to 18 in my gradle file, some lines got marked by Android Studio as 'not supported by API 18', most notably my myWebView.evaluateJavascript calls, but also some other stuff like WebView.setWebContentsDebuggingEnabled.
How can I do evaluateJavascript in API 18?
Also in some places, when I call evaluateJavascript, I expect a response back, for example:
myWebView.evaluateJavascript("Back.go()", new ValueCallback<String>() {
#Override
public void onReceiveValue(String canGoBack) {
if (canGoBack.equals("false")) {
moveTaskToBack(true);
} else {
// don't need to do anything, already called Back.go()
// that means the javascript already handled navigation
}
}
});
Will that be possible with API 18?
How can I do evaluateJavascript in API 18?
Use loadUrl("javascript:..."), where the...` is your JavaScript code.
Will that be possible with API 18?
No, sorry. The closest thing is to have your JavaScript code call something on your WebAppInterface that you injected via addJavascriptInterface().
Note that at the present time only ~4% of Android devices using the Play Store are running API Level 18 or older.
I'm a beginner at android.
I used javascript method in android. And I want to call it when the app is loaded for first time.
For example,
testMethod = function(str) {
alert("hi" + str);
}//javascript
and
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDefaultTextEncodingName("utf-8");
mWebView.loadUrl("file:///index.html");
mWebView.addJavascriptInterface(androidBridge, "jsinterface");
mWebView.loadUrl("javascript:testMethod('javascript')");
}
What I was thinking here is the alert will pop up immediately when I start the app.
But nothing happens.
About this, I have two questions.
1.Can I call and use the javascript method in Android's onCreate method?
2.If it is possible, How can I do?
if you want to show a popup on start just use the default AlertDialog. see the code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showMessage("My Message Here", "Title here");
}
private void showMessage(String data, String title){
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue
}
})
.show();
}
check out whether index.html is REALLY loaded. I guess that webview didn't load your html properly, bcz it's not an invalid file path. try file:///mnt/sdcard/index.html. (or something likely)
try to put mWebView.loadUrl("javascript:testMethod('javascript')") in view.post or view.postDelayed.
I try to access this page url : DEMO FACE TRACKER using android webview. And I using this code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.webView);
wv.setWebChromeClient(new WebChromeClient());
wv.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(new WebAppInterface(this), "Android");
wv.loadUrl("http://auduno.github.io/clmtrackr/clm_image.html");
}
and IT WORKS!
But when I copy all of page (include javascript) to local, and access it form assets folder then app return NOT RESPONDING.
this is code that I use to access local assets:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.webView);
wv.setWebChromeClient(new WebChromeClient());
wv.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(new WebAppInterface(this), "Android");
wv.loadUrl("file:///android_asset/index.html");
}
For information, all of assets (scripts, css, etc) except media has combined into single page and when I access from browser (on my computer) its working, but not in android webview.
whether on android has special permission for this? please help :) thank you.
Most likely you have pathing issue. It might not be loading from where you think it does. Try adding to see
#Override
public void onLoadResource(WebView view, String resUrl) {
super.onLoadResource(view, resUrl);
Log.d(LOG_TAG,"Loading " + resUrl);
}
Add setAllowUniversalAccessFromFileURLs to address javascript security issue when loading from file.
wv.getSettings().setAllowUniversalAccessFromFileURLs(true);
I'm using mWebView.addJavascriptInterface(this, XXX) to let java
enter code herescript be executed on a webview.
The problem comes when the web page that I'm browsing sends a redirect.
I'm able to capture it an display the new URL in the same webview but javascript will not work.
The only solution that I've found is to create a new intent that load the new page on a new Activity.
public class QBrowser extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.qbrowser_main);
mWebView = (WebView) findViewById(R.id.webview);
webSettings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient());
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// BEGIN: THE WORK AROUND I DONT LIKE
Intent intent = new Intent("com.bcnquark.client.qbrowser.QBROWSER");
intent.putExtra("URL", url);
startActivity(intent);
finish();
// END:THE WORK AROUND I DONT LIKE
return true;
}});
Intent intent = getIntent();
String url = intent.getStringExtra("URL");
mWebView.addJavascriptInterface(this, "XXXX");
}
mWebView.loadUrl(url);
}
}
I have a WebView in which i display web content which i have no control over. The content displays fine, but have links which spawn a popup window. The javascript function that does that looks like this:
function getEntry(id) {
var win = window.open('', 'Booking',
'resizable=yes,scrollbars=yes,status=no,width=500,height=400');
win.document.location = '/some/url/1-' + id ;
}
I can't easily change this, and if the people responsible for the page i download would change it, i guess my app would fail miserably...
My WebView setup in the activity looks like this:
_webview = new WebView(this);
setContentView(_webview);
final Activity activity = this;
_chromeClient = new MyChromeClient();
_webview.setWebChromeClient(_chromeClient);
//I experimented with changing user agent, in case that would have any effect, it didn't...
_webview.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
_webview.setWebViewClient(new MyWebViewClient());
_webview.getSettings().setJavaScriptEnabled(true);
_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
_webview.getSettings().setSupportZoom(true);
_webview.getSettings().setBuiltInZoomControls(true);
_webview.getSettings().setDomStorageEnabled(true);
//Cache settings...
_webview.getSettings().setAppCacheMaxSize(1024*1024*8);
_webview.getSettings().setAppCachePath("/data/data/com.your.package.appname/cache");
_webview.getSettings().setAllowFileAccess(true);
_webview.getSettings().setAppCacheEnabled(true);
MyWebClient:
private class MyWebViewClient extends WebViewClient {
#Override
public void onLoadResource(WebView view, String url) {
Log.d("MyWebViewClient",url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
showProgressDiag();
Log.d("MyWebViewClient","shouldOverride... : " + url);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url){
hideProgressDiag();
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if(failingUrl.equals("file:///android_asset/html/error.html")){
hideProgressDiag();
Toast.makeText(_context, "Error! Check internet connection, or try again later...", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(_context, failingUrl, Toast.LENGTH_SHORT).show();
view.loadUrl("file:///android_asset/html/error.html");
}
}
}
MyChromeClient:
private class MyChromeClient extends WebChromeClient{
#Override
public void onProgressChanged(WebView view, int progress) {
Pdiag.setProgress(progress * 100);
}
}
When clicking one of the links that points to the javascript function all that happens is that the WebView turns grey, without going through shouldOverrideUrlLoading(). When i hit the back key the app exits, meaning that nothing was placed in the nav history of the WebView. Sometimes nothing happens, but then the shouldOverrideUrlLoading() do run and from a Log.d() i can see that the correct URL for the popup has been given to the WebView.
The thing is, on very rare occasions it shows up fine, but i have no clue how to reproduce it, and wether it actually shows in a popup.
I'm lost... And quite frustrated... Thinking of watching a bad sitcom instead :(
EDIT:
Actually, maybe the URL wasn't all that correct after all... In Firefox the URL ends with "X<<<<" but in my Log.d() output it ends with "X%3C%3C%3C%3C"... I'll investigate if i could change that...
EDIT 2:
Nope, didn't do anything... The URL is identical to the one in Firefox...
First of all, you need to set the following settings on your WebView:
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
Then you need to attach a WebChromeClient that overrides onCreateWindow. Your implementation of this method can create a new web view, and display it inside a dialog:
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(MyActivity.this);
WebSettings webSettings = newWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Other configuration comes here, such as setting the WebViewClient
final Dialog dialog = new Dialog(MyActivity.this);
dialog.setContentView(newWebView);
dialog.show();
newWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
dialog.dismiss();
}
});
((WebView.WebViewTransport)resultMsg.obj).setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
Don't forget to set the new web view to the resultMsg, send it to its target and return true, as mentioned in the API documentation.
Please check with adding this -
getSettings().setSupportMultipleWindows(true);