Nothing happens when I click "Browse Image" on my webview app - java

Recently I made webview app on Android Studio. And I notice weird problem: When user click on "Browse Image" link nothing happens. I am trying to make a code so user can choose file from their Gallery on mobile phone.
emulator screenshot
Here is my MainActivity.java
package com.ijust2.ijust2;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
public class MainActivity extends Activity {
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
private static final int PICK_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://ijust2.com");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ijust2.ijust2.MainActivity">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
Can anyone give me some tips or suggest what should I do. I am newbie.
Thanks, Edi

I found a solution. Here is a code:
package it.floryn90.webapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
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 WebView webView;
private WebSettings webSettings;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
webView.setWebViewClient(new Client());
webView.setWebChromeClient(new ChromeClient());
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);
}
webView.loadUrl("http://example.com"); //change with your website
}
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 (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
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.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
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(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
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("Loading...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
try {
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}

Related

Unable to Resolve errors while adding file download code to webview app in android studio

Trying to make a web view app for a site. although everything works fine, unable to resolve few errors that are popping up while I add this "file download" code.
Here's the android code :
Activity Main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webview_sample"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Main Activity.java
package com.appgrep.urstudymate;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
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 final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
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();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview_sample);
if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
webView.loadUrl("https://urstudymate.com/");
webView.setWebChromeClient(new WebChromeClient() {
private File createImageFile() throws IOException {
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 boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
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.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
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(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
});
}
webView.setDownloadListener(new DownloadListener(){
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager myManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(getApplicationContext(), "File is Downloading...", Toast.LENGTH_SHORT).show();
}
});
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
}
return true;
}
private void GoForward() {
if (webView.canGoForward()) {
webView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
}
}
}
Super Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.filechooser.file.MainActivity">
<item android:id="#+id/myMenuOne" android:icon="#drawable/ic_arrow_back_black_24dp" android:title="Item" app:showAsAction="always" />
<item android:id="#+id/myMenuTwo" android:icon="#drawable/ic_arrow_back_black_24dp" android:title="Item" app:showAsAction="always" />
</menu>
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.appgrep.urstudymate">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
However the piece of code I added is :
webView.setDownloadListener(new DownloadListener(){
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager myManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(getApplicationContext(), "File is Downloading...", Toast.LENGTH_SHORT).show();
}
});
(which i added already for which I got error at "setDownloadListener", "DownloadListener", "DownloadManager" and so on. almost all words in that piece.)
SCREENSHOT :
Any help is greatly appreciated.

Captured image is not creating new file

There are two Standard options 'Camera' and 'Gallery'. First I choose the option 'Camera', then capture the image and then edit and save.
HomeActivity.java file:
package com.saashtechs.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private static final int GALLERY_RESULT = 1;
private static final int CAMERA_RESULT = 2;
private static final String FILE_PROVIDER_AUTHORITY = "com.saashtechs.photoeditor";
private static final int CAMERA_PERMISSION_REQ_CODE = 1001;
private static final int STORAGE_PERMISSION_REQ_CODE = 1002;
private Uri imageToUploadUri;
private String mCapturedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void openCamera(View view) {
// check for camera permission if not granted before
if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED) {
String[] cameraPermission = {CAMERA};
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_PERMISSION_REQ_CODE);
} else {
dispatchImageCaptureIntent();
}
}
public void openGallery(View view) {
// check for storage permission if not granted before
if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
String[] storagePermissions = {READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_PERMISSION_REQ_CODE);
} else {
dispatchGalleryIntent();
}
}
private void dispatchGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY_RESULT);
}
private void dispatchImageCaptureIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoFileUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);
Log.d(TAG, "dispatchImageCaptureIntent:photoFileUri: " + photoFile.toString());
imageToUploadUri = photoFileUri;
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchImageCaptureIntent();
} else {
Toast.makeText(this, "Required camera permission not granted", Toast.LENGTH_SHORT).show();
}
break;
case STORAGE_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchGalleryIntent();
} else {
Toast.makeText(this, "Required storage permission not granted", Toast.LENGTH_SHORT)
.show();
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
private File createImageFile() throws IOException {
String timeStamp = DateFormat.getDateTimeInstance().format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCapturedImagePath = image.getAbsolutePath();
Log.d(TAG, "createImageFile: " + mCapturedImagePath);
return image;
}
private Bundle uriToBundle(Uri imageUri) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.IMAGE_URI, imageUri.toString());
return bundle;
}
public Bitmap resizeBitmap(Bitmap getBitmap, int maxSize) {
int width = getBitmap.getWidth();
int height = getBitmap.getHeight();
double resized_image;
if (width >= height && width > maxSize) {
resized_image = width / height;
width = maxSize;
height = (int) (maxSize / resized_image);
} else if (height >= width && height > maxSize) {
resized_image = height / width;
height = maxSize;
width = (int) (maxSize / resized_image);
}
return Bitmap.createScaledBitmap(getBitmap, width, height, false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY_RESULT) {
Uri imageUri = data.getData();
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
} else if (requestCode == CAMERA_RESULT) {
File imageFile = new File(mCapturedImagePath);
Bitmap image = BitmapFactory.decodeFile(mCapturedImagePath);
image = Bitmap.createScaledBitmap(image, 4477, 3351, false);
image = resizeBitmap(image, 4477);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename.jpg");
boolean result;
result = file.createNewFile();
if (result) {
FileOutputStream fo = new FileOutputStream(imageFile);
fo.write(bytes.toByteArray());
fo.close();
}
} catch(IOException ie) {
ie.printStackTrace();
}
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageToUploadUri))));
}
} else {
Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
}
}
public static Intent getIntent(Context context) {
return new Intent(context, HomeActivity.class);
}
}
When the app is used for the first time, after image is captured, the folder is not getting created for the saved image to be stored in Gallery/Photos app. If I use 'Gallery' as the option to save the image, folder gets created. After the folder gets created, then if I capture the image, the captured image gets stored since folder is already created through 'Gallery' option
Can anyone please help?
Thanks in advance
How about changing File imageFile = new File(mCapturedImagePath); with
File imageFile = new File(intent.getData());
mCapturedImagePath is always empty when activityResult is being called. you would need to get the image path from the intent and then get a File instance from the path or uri. intent#getData() returns the uri of the image.

How to fix bitmap resizing the captured image in android

My Photo Editor Android application has some issue. After capturing the image from the 20MegaPixel (5184x3880) camera through the app, I am resizing the image through Bitmap to 15MegaPixel (4477 x 3351) and then saving the image in the Gallery/Photos folder in the phone
Following is the HomeActivity code:
package com.saashtechs.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private static final int GALLERY_RESULT = 1;
private static final int CAMERA_RESULT = 2;
private static final String FILE_PROVIDER_AUTHORITY = "com.saashtechs.photoeditor";
private static final int CAMERA_PERMISSION_REQ_CODE = 1001;
private static final int STORAGE_PERMISSION_REQ_CODE = 1002;
private Uri imageToUploadUri;
private String mCapturedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void openCamera(View view) {
// check for camera permission if not granted before
if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED) {
String[] cameraPermission = {CAMERA};
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_PERMISSION_REQ_CODE);
} else {
dispatchImageCaptureIntent();
}
}
public void openGallery(View view) {
// check for storage permission if not granted before
if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
String[] storagePermissions = {READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_PERMISSION_REQ_CODE);
} else {
dispatchGalleryIntent();
}
}
private void dispatchGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY_RESULT);
}
private void dispatchImageCaptureIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoFileUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);
Log.d(TAG, "dispatchImageCaptureIntent:photoFileUri: " + photoFile.toString());
//Add URI to imageToUploadUri. You forgot to add it.
imageToUploadUri = photoFileUri;
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchImageCaptureIntent();
} else {
Toast.makeText(this, "Required camera permission not granted", Toast.LENGTH_SHORT).show();
}
break;
case STORAGE_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchGalleryIntent();
} else {
Toast.makeText(this, "Required storage permission not granted", Toast.LENGTH_SHORT)
.show();
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
private File createImageFile() throws IOException {
String timeStamp = DateFormat.getDateTimeInstance().format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCapturedImagePath = image.getAbsolutePath();
Log.d(TAG, "createImageFile: " + mCapturedImagePath);
return image;
}
private Bundle uriToBundle(Uri imageUri) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.IMAGE_URI, imageUri.toString());
return bundle;
}
public Bitmap resizeBitmap(Bitmap getBitmap, int maxSize) {
int width = getBitmap.getWidth();//5184
int height = getBitmap.getHeight();//3880
double resized_image;
if (width >= height && width > maxSize) {
resized_image = width / height;
width = maxSize;
height = (int) (maxSize / resized_image);
} else if (height >= width && height > maxSize) {
resized_image = height / width;
height = maxSize;
width = (int) (maxSize / resized_image);
}
return Bitmap.createScaledBitmap(getBitmap, width, height, false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY_RESULT) {
Uri imageUri = data.getData();
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
} else if (requestCode == CAMERA_RESULT) {
File imageFile = new File(mCapturedImagePath);
Bitmap image = BitmapFactory.decodeFile(mCapturedImagePath);
image = Bitmap.createScaledBitmap(image, 4477, 3351, false);
image = resizeBitmap(image, 4477);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename.jpg");
boolean result;
result = file.createNewFile();
if (result) {
FileOutputStream fo = new FileOutputStream(imageFile);
fo.write(bytes.toByteArray());
fo.close();
}
} catch(IOException ie) {
ie.printStackTrace();
}
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageToUploadUri))));
}
} else {
Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
}
}
public static Intent getIntent(Context context) {
return new Intent(context, HomeActivity.class);
}
}
Following is the MainActivity code:
package com.saashtechs.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
public class MainActivity extends AppCompatActivity {
public static final String IMAGE_URI = "IMAGE_URI_KEY";
private static final String TAG = "MainActivity";
private static final int IMAGE_EDITOR_RESULT = 1;
private ImageView mEditedImageView;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditedImageView = (ImageView) findViewById(R.id.edited_image_view);
Bundle extras = getIntent().getExtras();
if (extras != null) {
Uri imageUri = Uri.parse(getIntent().getExtras().getString(IMAGE_URI));
Intent imageEditorIntent = new AdobeImageIntent.Builder(this).setData(imageUri).build();
startActivityForResult(imageEditorIntent, IMAGE_EDITOR_RESULT);
finish();
}
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case IMAGE_EDITOR_RESULT:
Uri editedImageUri = data.getParcelableExtra(AdobeImageIntent.EXTRA_OUTPUT_URI);
Log.d(TAG, "editedImageUri: " + editedImageUri.toString());
Bundle extra = data.getExtras();
if (extra != null) {
boolean changed = extra.getBoolean(AdobeImageIntent.EXTRA_OUT_BITMAP_CHANGED);
Log.d(TAG, "Image edited: " + changed);
if (changed) {
mEditedImageView.setImageURI(editedImageUri);
}
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
}
public static Intent getIntent(Context context, Bundle bundle) {
Intent intent = new Intent(context, MainActivity.class);
if (bundle != null) {
intent.putExtras(bundle);
}
return intent;
}
}
So when I capture the image and then when the user is taken to edit the application, it doesn't, it takes me back to Home page again after capturing the image
Error log is:
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor bitmap.size: 5184x3880
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor resize(15)
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor bitmap MP: 20, max MP: 15
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor Image must be resized! 20MP -> 15MP
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor target: 15MP = (4477x3351), max size: 4477
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor original: 20MP = (5184x3880)
2018-11-04 14:56:40.629 20408-21385/com.saashtechs.photoeditor maxWidth: 4477, maxHeight: 3351
Can you please tell me where am I going wrong ?
Thanks in advance
if (extras != null) {
Uri imageUri = Uri.parse(getIntent().getExtras().getString(IMAGE_URI));
Intent imageEditorIntent = new AdobeImageIntent.Builder(this).setData(imageUri).build();
startActivityForResult(imageEditorIntent, IMAGE_EDITOR_RESULT);
// below line of code is not possible. your trying to receive result over
//here.
// . but your finishing it before it receives result
finish();
}
use below method close activity once data received. Pass data with set result method and then close. so your activity will have edited data.
better solution - you dont need this intermediate activity.
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case IMAGE_EDITOR_RESULT:
Uri editedImageUri = data.getParcelableExtra(AdobeImageIntent.EXTRA_OUTPUT_URI);
Log.d(TAG, "editedImageUri: " + editedImageUri.toString());
Bundle extra = data.getExtras();
if (extra != null) {
boolean changed = extra.getBoolean(AdobeImageIntent.EXTRA_OUT_BITMAP_CHANGED);
Log.d(TAG, "Image edited: " + changed);
if (changed) {
mEditedImageView.setImageURI(editedImageUri);
}
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
}
As guidance -- below code is very bad practise in android
public static Intent getIntent(Context context, Bundle bundle) {
Intent intent = new Intent(context, MainActivity.class);
if (bundle != null) {
intent.putExtras(bundle);
}
return intent;
}
Good practise.
private void navigateToPhotoEditActivity(Context context, Bundle bundle)
{
Intent intent = new Intent(context, MainActivity.class);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}

how to make a voice recorder

I want to make a voice recorder so that my client can record the voice note and upload it to the system then the manager can review as voice note. Please, I don't know where to start. thanks.
what show when i use chrome to upload to my website
What show when I try to upload from my android app
my Java code i used from the
package com.pemasoft.checklistsystem;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int FCR = 1;
private WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= 21) {
Uri[] results = null;
//Check if response is positive
if (resultCode == Activity.RESULT_OK) {
if (requestCode == FCR) {
if (null == mUMA) {
return;
}
if (intent == null) {
//Capture Photo if no image available
if (mCM != null) {
results = new Uri[]{Uri.parse(mCM)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
} else {
if (requestCode == FCR) {
if (null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
//private WebView My_Web_View;
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getSupportActionBar().hide();
if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
webView = (WebView) findViewById(R.id.mwebview);
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setLoadWithOverviewMode(true);
//webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
webSettings.setAllowContentAccess(true);
webSettings.setMediaPlaybackRequiresUserGesture(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.OFF);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setUserAgentString("Android Mozilla/5.0 AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
webView.getSettings().setAllowFileAccess(true);
//webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().supportZoom();
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
if (isNetworkAvailable() == true) {
webView.loadUrl("https://app.enterprise360.co/mobile/");
} else {
webView.loadUrl("file:///android_asset/www/main.html");
}
//
webView.setWebChromeClient(new WebChromeClient() {
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FCR);
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
mCM = "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.setType("*/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
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(chooserIntent, FCR);
return true;
}
});
//
}
// Create an image file
private File createImageFile() throws IOException {
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName, ".jpg", storageDir);
}
#Override
public boolean onKeyDown(int keyCode, #NonNull KeyEvent event) {
// if (event.getAction() == KeyEvent.ACTION_DOWN) {
//
// switch (keyCode) {
// case KeyEvent.KEYCODE_BACK:
//
// if (webView.canGoBack()) {
// webView.goBack();
// } else {
// finish();
// }
//
// return true;
// }
// }
//
return super.onKeyDown(keyCode, event);
//return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
boolean isNetworkAvailable() {
boolean isConnected = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null && (
(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) ||
(cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED))) {
isConnected = true;
//You are connected, do something online.
} else if (cm != null && (
(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) ||
(cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED))) {
isConnected = false;
//Not connected.
Toast.makeText(getApplicationContext(), "You must be connected to the internet", Toast.LENGTH_LONG).show();
}
return isConnected;
//ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
//boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
//return isConnected;
}
}
I think our question is demanding a tutorial. Try this one:
https://medium.com/#ssaurel/create-an-audio-recorder-for-android-94dc7874f3d

how to open target _blank links in WebView with external browser

I have this code, but not because it works, it keeps opening in webview and what I want is that the links do not belong to my website open in default browser. Any idea?
Can someone tell me if it's possible and how to do it? Thank you very much!
package com.example.webviewapp;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.MimeTypeMap;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class MainActivity extends Activity {
private WebView mainWebView;
private String HomeUrl, AppName, ShareUrl, AD_ID, sdrUrl, ext;
private VideoView mVideoView;
private RelativeLayout mContentView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private AdView adView;
Integer vidPosition;
ProgressBar progressBar;
#SuppressWarnings("deprecation")
#SuppressLint({"CutPasteId","NewApi", "SetJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ========================Create adView
AD_ID = getString(R.string.admob_publisher_id);
adView = new AdView(this, AdSize.BANNER, AD_ID);
/* // Dynamic add LinearLayout
// android:id="#+id/adLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
// Add adView
layout.addView(adView);*/
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
//========================== home url
HomeUrl = getString(R.string.base_url);
//First share link
ShareUrl = HomeUrl;
// App name url
AppName = getString(R.string.app_name);
//Find objects with ID
mainWebView = (WebView) findViewById(R.id.webView1);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
// focus with touch
mainWebView.setFocusable(true);
mainWebView.setFocusableInTouchMode(true);
mainWebView.requestFocus(View.FOCUS_DOWN|View.FOCUS_UP);
mainWebView.getSettings().setLightTouchEnabled(true);
// enabled Java Script
mainWebView.getSettings().setJavaScriptEnabled(true);
mainWebView.getSettings().setPluginState(PluginState.ON_DEMAND);
mainWebView.getSettings().setDomStorageEnabled(true);
//mainWebView.getSettings().setUseWideViewPort(true);
//Customaze Web View
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setWebChromeClient(new MyChromeClient());
//Webview scroll
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//Cache enable
mainWebView.getSettings().setAppCacheEnabled(true);
mainWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
// Load Home url
mainWebView.loadUrl(HomeUrl);
mainWebView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
v.requestFocusFromTouch();
}
break;
}
return false;
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("url");
//mainWebView.getSettings().setUseWideViewPort(true);
mainWebView.loadUrl(value);
}
// Menu category
TextView text1= (TextView) findViewById(R.id.title_bar_home);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mainWebView.loadUrl(HomeUrl);
}
});
// Menu category
TextView text2= (TextView) findViewById(R.id.title_bar_share);
text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ShareUrl);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Interesting for you!");
startActivity(Intent.createChooser(intent, "Share via"));
}
});
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
// On load Spinner visible
progressBar.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
//#SuppressWarnings("deprecation")
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// On load Spinner hide
progressBar.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
#SuppressLint("NewApi")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//share page or link
ShareUrl = url;
// One touch call link Call
if (url.startsWith("tel:"))
{
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
}
else
// One touch sms link Sms
if (url.startsWith("sms:"))
{
Intent message = new Intent(Intent.ACTION_SENDTO,
Uri.parse(url));
startActivity(message);
}
// One share text or url link share text
else
if (url.startsWith("share:"))
{
String[] share_link = url.split(":");
try {
String ID= URLDecoder.decode(share_link[1], "UTF-8");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.youtube.com/watch?v="+ID);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Interesting for you!");
startActivity(Intent.createChooser(intent, "Share via"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// One touch image link Image
else
if(url.endsWith(".jpg") || url.endsWith(".png") || url.endsWith(".gif") || url.endsWith(".JPG") || url.endsWith(".jpeg") )
{
Intent intent=new Intent (MainActivity.this, Image.class);
intent.putExtra("href", url);
startActivity(intent);
}
else
// else if it's a 3GP file link
if(url.endsWith(".3gp")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/3gp");
startActivity(intent);
return true;
}
else
//Link mp4 file Download mp4
if(url.endsWith(".mp4")){
if(url.startsWith("download")){
String[] download_link = url.split(":");
try {
//Download mp4
sdrUrl= URLDecoder.decode(download_link[1], "UTF-8")+":"+URLDecoder.decode(download_link[2], "UTF-8");
ext = MimeTypeMap.getFileExtensionFromUrl(sdrUrl);
if (ext != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String mimeType = mime.getMimeTypeFromExtension(ext);
if (mimeType != null) {
if (ext.toLowerCase().contains("mp4")) {
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(sdrUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(true);
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(sdrUrl, ext));
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
}
}
}
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);
return true;
}
}
else
//Open MP3 file Download mp3
if(url.endsWith(".mp3") || url.endsWith(".MP3")){
// Download files
if(url.startsWith("download")){
String[] download_link = url.split(":");
try {
//Download mp3
sdrUrl= URLDecoder.decode(download_link[1], "UTF-8")+":"+URLDecoder.decode(download_link[2], "UTF-8");
//ext=url.substring(url.lastIndexOf("."));
ext = MimeTypeMap.getFileExtensionFromUrl(sdrUrl);
if (ext != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String mimeType = mime.getMimeTypeFromExtension(ext);
if (mimeType != null) {
if (ext.toLowerCase().contains("mp3")) {
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(sdrUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(true);
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(sdrUrl, ext));
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
}
}
}
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
return true;
}
}
//View file < a href="www.text.com/test.txt"> View text</a>
if (
url.endsWith(".pdf")
|| url.endsWith(".txt")
|| url.endsWith(".doc")
|| url.endsWith(".docx")
|| url.endsWith(".xls")
|| url.endsWith(".xlsx")
|| url.endsWith(".ppt")
|| url.endsWith(".pptx")
|| url.endsWith(".pages")
|| url.endsWith(".ai")
|| url.endsWith(".psd")
|| url.endsWith(".tiff")
|| url.endsWith(".dxf")
|| url.endsWith(".svg")
|| url.endsWith(".eps")
|| url.endsWith(".ps")
|| url.endsWith(".ttf")
|| url.endsWith(".xps")
|| url.endsWith(".zip")
|| url.endsWith(".rar")
)
{
if(url.startsWith("download")){
String[] download_link = url.split(":");
try {
sdrUrl= URLDecoder.decode(download_link[1], "UTF-8")+":"+URLDecoder.decode(download_link[2], "UTF-8");
ext = MimeTypeMap.getFileExtensionFromUrl(sdrUrl);
if (ext != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String mimeType = mime.getMimeTypeFromExtension(ext);
if (mimeType != null) {
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(sdrUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(true);
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(sdrUrl, ext));
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
}
}
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
String googleDocs = "https://docs.google.com/viewer?url=";
mainWebView.loadUrl(googleDocs + url);
return true;
}
}
else
if(url.startsWith("http:") || url.startsWith("https:")) {view.loadUrl(url); }
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/error.html");
}
}
private class MyChromeClient extends WebChromeClient implements OnCompletionListener, OnErrorListener {
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
#Override
public void onShowCustomView(View view, int requestedOrientation,
WebChromeClient.CustomViewCallback callback) // Available in API level 14+, deprecated in API level 18+
{
onShowCustomView(view, callback);
if(Build.VERSION.SDK_INT >=14) {
if (view instanceof FrameLayout) {
mainWebView.addView(view, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER));
mainWebView.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
if (view instanceof FrameLayout) {
// mainWebView is the view that the video should've played inside.
mainWebView = (WebView)findViewById(R.id.webView1);
mCustomViewContainer = (FrameLayout) view;
mCustomViewCallback = callback;
// mainLayout is the root layout that (ex. the layout that contains the webview)
mContentView = (RelativeLayout)findViewById(R.id.RootLayout);
if (mCustomViewContainer.getFocusedChild() instanceof VideoView) {
mVideoView = (VideoView) mCustomViewContainer.getFocusedChild();
// frame.removeView(video);
mContentView.setVisibility(View.GONE);
mCustomViewContainer.setVisibility(View.VISIBLE);
setContentView(mCustomViewContainer);
mVideoView.setOnCompletionListener((OnCompletionListener) this);
mVideoView.setOnErrorListener((OnErrorListener) this);
mVideoView.start();
}
}
}
public void onHideCustomView() {
if (mVideoView == null){
return;
}else{
// Hide the custom view.
mVideoView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mVideoView);
mVideoView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
}
public void onCompletion(MediaPlayer mp) {
mp.stop();
mCustomViewContainer.setVisibility(View.GONE);
onHideCustomView();
setContentView(mContentView);
}
#SuppressWarnings("unused")
public void onPrepared(MediaPlayer mp) {
mCustomViewCallback.onCustomViewHidden();
}
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
setContentView(mContentView);
return true;
}
//Java script alert dialog
#Override
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Attention !")
.setMessage(message)
.setPositiveButton(R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
//Java script confirm dialog
#Override
public boolean onJsConfirm(WebView view, String url, String message,
final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Confirm !")
.setMessage(message)
.setPositiveButton(R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
//Java script Prompt dialog
#Override
public boolean onJsPrompt(WebView view, String url, String message,
String defaultValue, final JsPromptResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Prompt Alert !")
.setMessage(message)
.setPositiveButton(R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_rate:
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);
break;
case R.id.action_refresh:
mainWebView.loadUrl( "javascript:window.location.reload( true )" );
break;
case R.id.action_exit:
finish();
break;
default:
break;
}
return true;
}
#Override
protected void onPause() {
if(mCustomViewContainer != null){
vidPosition = mVideoView.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
if(mCustomViewContainer != null){
mVideoView.seekTo(vidPosition);
}
super.onResume();
}
#Override
public void onBackPressed() {
if(mCustomViewContainer != null){
mVideoView.stopPlayback();
mCustomViewContainer.setVisibility(View.GONE);
if (mVideoView == null){
return;
}else{
// Hide the custom view.
mVideoView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mVideoView);
mVideoView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
setContentView(mContentView);
mCustomViewContainer = null;
}
}else if(mainWebView.canGoBack()){
mainWebView.goBack();
}else{
super.onBackPressed();
}
}
public String getFileName(String url, String ext1) {
String filenameWithoutExtension = "";
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()+"."+ext1);
return filenameWithoutExtension;
}
}
There is no built in "Popup" class in Android. So it depends on what do you need from "Popup". You can use dialog as it says here. Or you can create dynamically WebView and add it into some container (RelativeLayout for instance).
An intent is an abstract description of an operation to be performed.To open a URL/website you do the following:
String url = "http://www.stackexchange.com";
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setData(Uri.parse(url));
startActivity(browserIntent);

Categories

Resources