I want to open external webview links in browser so please update my codes. Actually the problem is that my webview contains some google drive links so i want to open all external links in browser and i searches too much about it on the web but i can't find the right solution.
I'm new on android studio so please help me guys.
package com.iaritoppers;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.renderscript.Sampler;
import android.view.KeyEvent;
import android.view.View;
import androidx.appcompat.widget.AppCompatRatingBar;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
private WebView mWebviewPop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppRater.app_launched(this);
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
mwebView.loadUrl("https://www.iaritoppers.com/");
mwebView.setWebViewClient(new MyWebviewClient());
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "abc");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_icar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-e-course-pdf.html");
return true;
}
if (id == R.id.action_share) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "*I recommend you to download this very useful App For Agriculture Students -* ");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
} else if (id == R.id.nav_icar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-e-course-pdf.html");
} else if (id == R.id.nav_agronomyicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/agronomy-icar-ecourse-pdf-books.html");
} else if (id == R.id.nav_hortiicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/horticulture-icar-ecourse-pdf-books.html");
} else if (id == R.id.nav_dairyicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/dairy-technology-icar-e-course-free-pdf.html");
} else if (id == R.id.nav_tnau) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/tnau-notes-pdf-download-agri-study-material.html");
} else if (id == R.id.nav_angrau) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/angrau-notes-download-angrau-study-material.html");
} else if (id == R.id.nav_syllabus) {
mwebView.loadUrl("https://www.iaritoppers.com/p/agriculture-exams-syllabus.html");
} else if (id == R.id.nav_jrfold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-jrf-old-papers.html");
} else if (id == R.id.nav_bhuold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/bhu-old-paper-ug-and-pg.html");
} else if (id == R.id.nav_iariold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/iari-old-question-papers-download-for.html");
} else if (id == R.id.nav_prepgold) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/07/rajasthan-pre-pg-agriculture-old-question-paper.html");
} else if (id == R.id.nav_afoold) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/ibps-afo-old-question-papers-pdf-download-for-agriculture-field-officer.html");
} else if (id == R.id.nav_agribook) {
mwebView.loadUrl("https://www.iaritoppers.com/p/best-agriculture-books-for-icar-jrf-srf.html");
} else if (id == R.id.nav_entrance) {
mwebView.loadUrl("https://www.iaritoppers.com/search/label/agriculture%20entrance%20exams");
} else if (id == R.id.nav_jobs) {
mwebView.loadUrl("https://www.iaritoppers.com/search/label/Latest%20agriculture%20jobs");
} else if (id == R.id.nav_discussion) {
mwebView.loadUrl("https://www.iaritoppers.com/p/discussion-desk_23.html");
} else if (id == R.id.nav_top) {
mwebView.loadUrl("https://www.iaritoppers.com/p/our-top-contributors.html");
} else if (id == R.id.nav_contact) {
mwebView.loadUrl("https://www.iaritoppers.com/p/about-us.html");
} else if (id == R.id.nav_share) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "*I recommend you to download this very useful App For Agriculture Students -* ");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebviewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar2).setVisibility(View.GONE);
}
}
//goto previous page when pressing back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebView.canGoBack()) {
mwebView.goBack();
} else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I would recommend using a chrome custom tab.
Here is a link to the docs
However, have just pasted the information you need here:
First, add chrome custom tabs to your Gradle file
dependencies {
...
compile 'com.android.support:customtabs:23.3.0'
}
Then create the chrome custom tab and show it:
// Use a CustomTabsIntent.Builder to configure CustomTabsIntent.
// Once ready, call CustomTabsIntent.Builder.build() to create a CustomTabsIntent
// and launch the desired Url with CustomTabsIntent.launchUrl()
String url = ¨https://paul.kinlan.me/¨;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
Related
I am opening a URL in webview .there is input field initial value is blank .and a button in my application.on button click I am opening my camera and capture image and back to my web view to show the image.
Issue is
Initially, the input field is blank .now I type “abc” in the input field when I click the button to capture an image.The image is shown but web view is reloaded and my input field become blank again why ?? It should persist in his state.
package com.example.myapp.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
WebView webView;
public static Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("http://100.50.100.97:32671");
// webView.loadUrl("http://115.10.74.180:30019");
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.addJavascriptInterface(jsInterface, "JSInterface");
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
// Log.d("My map",photo,"");
if (webView != null) {
// webView.loadUrl("http://100.50.100.97:32671");
webView.loadUrl("http://115.10.74.180:30019");
}
}
}
public void checkTest(){
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
class JavaScriptInterface {
private MainActivity activity;
public JavaScriptInterface(MainActivity activity) {
this.activity = activity;
}
#JavascriptInterface
public void test() {
this.activity.checkTest();
}
#JavascriptInterface
public String bitMapToBase64()
{
if (MainActivity.photo != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//add support for jpg and more.
MainActivity.photo.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
return "null image";
}
}
the issue is on this line
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
// Log.d("My map",photo,"");
if (webView != null) {
// webView.loadUrl("http://100.50.100.97:32671");
webView.loadUrl("http://115.10.74.180:30019");
}
}
}
why whole content is refreshed?
I found that window.location = '/Mobile/Main'; does not work in WebChromeClient. I mean it does not redirect to the page but it work fine under any PC internet browser.
I have tried
history.pushState(null, '', '#Url.Action("Main", "Mobile")');
window.open('#Url.Action("Main", "Mobile")');
And it does not redirect as it works normally.
How to fix it?
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (data) {
if (data.success === true) {
// It does not redirect in Android WebClient
window.location = '/Mobile/Main';
}
else {
$('#msgModalBody').html(data.msg);
$('#msgModal').modal({
keyboard: false
});
}
},
error: function (jqXHR, exception) {
}
}).done(function (data) {
// It does not redirect in Android WebClient
window.location = '/Mobile/Main';
});
Java
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ValueCallback<Uri[]> mUploadMessage;
private String mCameraPhotoPath;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebSettings webSettings;
private long size = 0;
// Storage Permissions variables
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
try {
String file_path = mCameraPhotoPath.replace("file:","");
File file = new File(file_path);
size = file.length();
}catch (Exception e){
Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage());
}
if (data != null || mCameraPhotoPath != null) {
Integer count = 0; //fix fby https://github.com/nnian
ClipData images = null;
try {
images = data.getClipData();
}catch (Exception e) {
Log.e("Error!", e.getLocalizedMessage());
}
if (images == null && data != null && data.getDataString() != null) {
count = data.getDataString().length();
} else if (images != null) {
count = images.getItemCount();
}
Uri[] results = new Uri[count];
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (size != 0) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else if (data.getClipData() == null) {
results = new Uri[]{Uri.parse(data.getDataString())};
} else {
for (int i = 0; i < images.getItemCount(); i++) {
results[i] = images.getItemAt(i).getUri();
}
}
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
int cameraPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title
getSupportActionBar().hide(); //hide the title bar
setContentView(R.layout.activity_main);
verifyStoragePermissions(this);
webView = (WebView)findViewById(R.id.website);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webSettings = webView.getSettings();
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
// Очищать весь кэш https://stackoverflow.com/questions/2465432/android-webview-completely-clear-the-cache
webSettings.setSaveFormData(false);
webSettings.setCacheMode(webSettings.LOAD_NO_CACHE);
webView.clearHistory();
webView.clearFormData();
webView.clearCache(true);
// Javascript inabled on webview
//webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
//webView.getSettings().setLoadWithOverviewMode(true);
//Other webview settings
//webView.getSettings().setGeolocationEnabled(true);
//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
//webView.setScrollbarFadingEnabled(false);
//webView.getSettings().setBuiltInZoomControls(true);
//webView.getSettings().setAllowFileAccess(true);
//webView.getSettings().setSupportZoom(true);
//webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//webView.getSettings().setAllowContentAccess(true);
//webView.getSettings().setAllowFileAccessFromFileURLs(true);
//webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
//webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//webView.getSettings().setAppCacheEnabled(true);
// webView.setWebViewClient(new WebViewClient());
webView.setWebViewClient(new Client());
webView.setWebChromeClient(new ChromeClient());
//if SDK version is greater of 19 then activate hardware acceleration otherwise activate software acceleration
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
/* context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");*/
//Load url in webview
webView.loadUrl("http://172.16.10.3:7777");
}
//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
public static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public class ChromeClient extends WebChromeClient {
// For Android 5.0+
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = filePath;
Log.e("FileCooserParams => ", filePath.toString());
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[2];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), 1);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public class Client extends WebViewClient {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// If url contains mailto link then open Mail Intent
if (url.contains("mailto:")) {
// Could be cleverer and use a regex
//Open links in new browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// Here we can open new activity
return true;
}else {
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
}
//Show loader on url load
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Then show progress Dialog
// in standard case YourActivity.this
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Загружается...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function(){ " +
"document.getElementById('android-app').style.display='none';})()");
try {
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
Huh! :)
Mega solution I just have found.
We have to simulate to post an empty form.
HTML
<form id="myForm" action='#Url.Action("Details","Main")'></form>
JS
document.getElementById("myForm").submit();
instead of
window.location = '/Mobile/Main';
That does the trick!
I previously used Android Location Manager to retrieve location. However, when I run wikitude apps, the POIs are loaded but are not displayed. I read a few posts saying that this may caused by basic Location Strategy. Therefore, I decided to use Fused Location Provider. The problem still occur. Please help me anyone
package xyz.arlayer.scratch;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
import java.io.IOException;
public class Augmented extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int WIKITUDE_PERMISSIONS_REQUEST_CAMERA = 2;
private ArchitectView architectView;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_augmented);
this.architectView = this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("AOfmybWCEL410fS81fIe29RwjF2eLJ00DCjmqSl+xZaUQc6E48KtXM9oxnbRayoGTjCzG2hSfq7oxzLDO0K8fVZfNyUs1DnLzm+p4jPSHEotpKJOrMmH8aOJoGLsiFfTcXzJY58Kj/EJt0dOHZvBXz/KBka4EPhvcvoDVq//6FFTYWx0ZWRfX9YCljHdYuEA0smGRDePFWZ3TTxz6sxXRJNfTU2P4aKDSsN1hXCicvw/Yf0cs8/v7xjI7UgOk+HZ+qkU2oDidWOPvPji7cbOhZ6pq3vA35s5aNJQU5t1o2LpaLuJyANaRgS/nGpmTYi/fRB6clGZcwEUgvyEl+OcNFL/7BFJUSJQTBdD6UBXy8Dfioh4mlupKMkIHn1d6nSYgTmu1tMn2MFVKTIL9O1qzopPe9O+J945Pq5NCvXbzaIL+6mn7BO6r+KxEY3XNKnpnmER0lnNxEobpY65Byy1v+oWFSCAi65mzEvGSzhGMMaqzlWHx7vJeaPRSoxqUcokvi8iLfiowRRptkiE+VQmNyb03gEViQd2LaQXl6aY+J2jKTIDXGuOLQ1C6hg0CY1AdKXjaslV4YETAkrpqIGbt+tSEeHPH+dL8gFh4UZe2g6JGQCyR4xRA0CtbAXY3CbSNCNypDox8cqOvwRnl0Jx5iwtuyQ4oOKfA6rV+94ZeLg=");
this.architectView.onCreate(config);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{android.Manifest.permission.CAMERA}, WIKITUDE_PERMISSIONS_REQUEST_CAMERA);
}}
#Override
protected void onPostCreate (Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
architectView.load("file:///android_asset/08_Browsing$Pois_5_Native$Detail$Screen/index.html"); } catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
if (location!=null && Augmented.this.architectView != null ) {
// check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
if ( location.hasAltitude() && location.hasAccuracy() && location.getAccuracy()<7) {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy() );
} else {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000 );
}
}
}
#Override
public void onResume() {
super.onResume();
architectView.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
#Override
protected void onPause() {
architectView.onPause();
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
protected void onDestroy(){
super.onDestroy();
architectView.onDestroy();
}
}
As I'm new to android I got a small problem where I actually do not know how to do it. Actually I'm looking for a Navigation Drawer menus to link to each tabs. eg: swipe tabs as 'tab1', 'tab2' and 'tab3' and Navigation drawer menu also listed as 'tab1', 'tab2' and ;tab3'. So, when i click 'tab2' from Navigation Drawer it should take me to 'tab2' of swipe tabs. Could someone help me out please.
thanks
//MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this;
list=LoadingContentActivity.list;
Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionar=getSupportActionBar();
actionar.setDisplayHomeAsUpEnabled(true);
actionar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.tab_11) {
startActivity(new Intent(MainActivity.this, FragmentTab1.class));
} else if (menuItem.getItemId() == R.id.tab_22) {
startActivity(new Intent(MainActivity.this, FragmentTab2.class));
} else if (menuItem.getItemId() == R.id.tab_33) {
startActivity(new Intent(MainActivity.this, FragmentTab3.class));
}
return true;
}
});
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new FragmentTab1(), "CALLS");
adapter.addFragment(new FragmentTab2(), "CHATS");
adapter.addFragment(new FragmentTab3(), "CONTACTS");
viewPager.setAdapter(adapter);
}
//TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FragmentTab1();
case 1:
return new FragmentTab2();
case 2:
return new FragmentTab3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
You don't have to start the same activity again, as this will cause it to be pushed into backstack. I would suggest you simply change the current fragment in ViewPager
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code
mViewPager = (ViewPager) findViewById(R.id.viewpager);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.tab_11) {
mViewPager.setCurrentItem(0);
} else if (menuItem.getItemId() == R.id.tab_22) {
mViewPager.setCurrentItem(1);
} else if (menuItem.getItemId() == R.id.tab_33) {
mViewPager.setCurrentItem(2);
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
I make simple webview app. using Webview fragment. App working properly. but problem is i click back button app close down. and second problem is i click on html page link. link not open in default browser. error says webpage not open. i want all tab open in same webview and back button and download link work properly. my code is
MyWebViewFragment.java
package com.example.com;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
MainActivity.java
package com.example.com;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
To open urls in webview use the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.OFF);
webSettings.setSupportMultipleWindows(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheMaxSize(1);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
// webView.setVerticalScrollBarEnabled(false);
// webView.setHorizontalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
// webView.setInitialScale(100);
// webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e("", "shouldOverrideUrlLoading load url" + url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
isLoaded = false;
progressDialog.setMessage("Unknown Error!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
displayProgress(getString(R.string.loading), getString(R.string.loading));
Log.e("onPageStarted",url);
}
public void onPageFinished(WebView view, String url) {
isLoaded = true;
super.onPageFinished(view, url);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
});
web_link = "https://twitter.com";
webView.loadUrl(web_link);
}
public void displayProgress(String title,String mes){
if (progressDialog!=null)
progressDialog.dismiss();
progressDialog = new ProgressDialog(MainActivity.this);
// progressDialog.setTitle(title);
progressDialog.setMessage(mes);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
try {
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
To go back on web view override this method to your activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (web_link!=null && !webView.getUrl().equals(web_link))
webView.goBack();
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.to_exit)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
return super.onKeyDown(keyCode, event);
}