Redirect in AJAX in Android WebClient - javascript

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!

Related

Calling a java jar method via mid server probe designed in javascript

I'm setting up an environment where I pass 4 parameters (Encrypted file, Key File, Pass Phase and Default File name) to a .Jar and it decrypts the file.
I have achieved it via Bouncycastle API and it works fine on the eclipse IDE.
Now I have to set this up in my servicenow mid-server.
So the javascript probe should call this jar file and pass the parameters as strings and the encrypted file (which resides on the mid-server) gets decrypted.
I have tried creating a mid-server script include in servicenow and a probe but it returns with an error that the method is not found (which is actually there)
CLASS INSIDE .JAR
package pgpDecrypt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Iterator;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.CompressionAlgorithmTags;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;
import org.bouncycastle.util.io.Streams;
public class PGPDecryption {
public static void decryptFile(String inputFileName, String keyFileName, char[] passwd, String defaultFileName)
throws IOException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
decryptFiles(in, keyIn, passwd, defaultFileName);
System.out.print("Default File Name : "+ defaultFileName);
keyIn.close();
in.close();
}
/**
* decrypt the passed in message stream
*/
public static void decryptFiles(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName)
throws IOException, NoSuchProviderException {
in = PGPUtil.getDecoderStream(in);
try {
JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
new JcaKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PGPUtilE.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe
.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) plainFact.nextObject();
InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(compressedStream);
Object message = pgpFact.nextObject();
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
String outFileName = ld.getFileName();
if (outFileName.length() == 0) {
outFileName = defaultFileName;
}
InputStream unc = ld.getInputStream();
OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));
Streams.pipeAll(unc, fOut);
fOut.close();
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
System.err.println("message failed integrity check");
} else {
System.err.println("message integrity check passed");
}
} else {
System.err.println("no message integrity check");
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}
private static void encryptFile(String outputFileName, String inputFileName, String encKeyFileName, boolean armor,
boolean withIntegrityCheck) throws IOException, NoSuchProviderException, PGPException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
PGPPublicKey encKey = PGPUtilE.readPublicKey(encKeyFileName);
encryptFile(out, inputFileName, encKey, armor, withIntegrityCheck);
out.close();
}
private static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor,
boolean withIntegrityCheck) throws IOException, NoSuchProviderException {
if (armor) {
out = new ArmoredOutputStream(out);
}
try {
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5).setWithIntegrityPacket(withIntegrityCheck)
.setSecureRandom(new SecureRandom()).setProvider("BC"));
cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream cOut = cPk.open(out, new byte[1 << 16]);
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(cOut), PGPLiteralData.BINARY, new File(fileName),
new byte[1 << 16]);
comData.close();
cOut.close();
if (armor) {
out.close();
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
if (args.length == 0) {
System.err.println(
"usage: PGPDecryption -d file [secretKeyFile passPhrase|pubKeyFile]");
return;
}
if (args[0].equals("-e")) {
if (args[1].equals("-a") || args[1].equals("-ai") || args[1].equals("-ia")) {
encryptFile(args[2] + ".asc", args[2], args[3], true, (args[1].indexOf('i') > 0));
} else if (args[1].equals("-i")) {
encryptFile(args[2] + ".bpg", args[2], args[3], false, true);
} else {
encryptFile(args[1] + ".bpg", args[1], args[2], false, false);
}
} else if (args[0].equals("-d")) {
decryptFile(args[1], args[2], args[3].toCharArray(), new File(args[1]).getName() + ".out");
} else {
System.err.println(
"usage: PGPDecryption -d|-e [-a|ai] file [secretKeyFile passPhrase|pubKeyFile]");
}
}
}
SCRIPT INCLUDE :
var ProcessPGP = Class.create();
ProcessPGP.prototype = {
initialize: function() {
this.Pgp = Packages.pgpDecrypt.PGPDecryption.decryptFile;
this.inputFile = probe.getParameter("inputFile");
this.secretFile = probe.getParameter("secretFile");
this.passPhase = probe.getParameter("passPhase");
this.defaultName = probe.getParameter("defaultName");
},
execute: function() {
var pgpObj = new this.Pgp(this.inputFile, this.secretFile, this.passPhase, this.defaultName);
},
type: ProcessPGP
};
PROBE :
var jspr = new JavascriptProbe('ANIRUDGU-68LCS_Dev1');
jspr.setName('TestPGPDemo5');
jspr.setJavascript('var pdf = new ProcessPGP(); res = pdf.execute();');
jspr.addParameter("inputFile", "C:\Users\anirudgu\Desktop\PGPTestKey\TestRun2.pgp");
jspr.addParameter("secretFile", "C:\Users\anirudgu\Desktop\PGPTestKey\anirudguciscocomprivate.asc");
jspr.addParameter("passPhase", "Hello");
jspr.addParameter("defaultName", "FilefromProbe");
jspr.create();
But I am facing the below mentioned error :
08/22/19 23:21:58 (097) Worker-Standard:JavascriptProbe-ce4567ebdb9b330045bb9b81ca961910 WARNING *** WARNING *** org.mozilla.javascript.EvaluatorException: Can't find method pgpDecrypt.PGPDecryption.decryptFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String). (script_include:ProcessPGP; line 32)
EvaluatorException(var pdf = new ProcessPGP(); res = pdf.execute();)
The method decryptFile is static. The new keyword can only be used to create instances.
Therefore, try:
var pgpObj = this.Pgp(this.inputFile, this.secretFile, this.passPhase, this.defaultName);
Try to remove "new" from:
jspr.setJavascript('var pdf = new ProcessPGP(); res =
pdf.execute();');

How to Open External WebView Links in Browser?

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));

Why web view refresh in android after camera close?

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?

After builing my app and Installing Google Maps API, My APP crashes anytime I tend to search for Location

I am new to this programming and I am finding it difficult to get past this stage. After building APP successfully, I added Google Map to get real time Location. After doing this, my app crashes each time I click the switch button.
Please if you can help me source out the issue, I would be very happy as this will help me a lot. Below is my Logcat
09-22 15:59:04.636 4803-4803/com.example.mac.uberclone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mac.uberclone, PID: 4803
java.lang.NullPointerException: Attempt to read from field 'int com.google.android.gms.location.LocationRequest.a' on a null object reference
at android.os.Parcel.createException(Parcel.java:1948)
at android.os.Parcel.readException(Parcel.java:1910)
at android.os.Parcel.readException(Parcel.java:1860)
at com.google.android.gms.internal.location.zza.transactAndReadExceptionReturnVoid(Unknown Source:10)
at com.google.android.gms.internal.location.zzap.zza(Unknown Source:9)
at com.google.android.gms.internal.location.zzas.zza(Unknown Source:44)
at com.google.android.gms.internal.location.zzaz.zza(Unknown Source:5)
at com.google.android.gms.internal.location.zzr.doExecute(Unknown Source:25)
at com.google.android.gms.common.api.internal.BaseImplementation$ApiMethodImpl.run(Unknown Source:10)
at com.google.android.gms.common.api.internal.zzag.execute(Unknown Source:71)
at com.google.android.gms.common.api.internal.zzbd.execute(Unknown Source:5)
at com.google.android.gms.common.api.internal.zzav.execute(Unknown Source:137)
at com.google.android.gms.internal.location.zzq.requestLocationUpdates(Unknown Source:14)
at com.example.mac.uberclone.Welcome.startLocationUpdate(Welcome.java:269)
at com.example.mac.uberclone.Welcome.onConnected(Welcome.java:283)
at com.google.android.gms.common.internal.GmsClientEventManager.onConnectionSuccess(Unknown Source:109)
at com.google.android.gms.common.api.internal.zzav.zzb(Unknown Source:22)
at com.google.android.gms.common.api.internal.zzaj.zzat(Unknown Source:92)
at com.google.android.gms.common.api.internal.zzaj.onConnected(Unknown Source:21)
at com.google.android.gms.common.api.internal.zzbd.onConnected(Unknown Source:7)
at com.google.android.gms.common.api.internal.zzp.onConnected(Unknown Source:5)
at com.google.android.gms.common.internal.zzf.onConnected(Unknown Source:2)
at com.google.android.gms.common.internal.BaseGmsClient$PostInitCallback.handleServiceSuccess(Unknown Source:130)
at com.google.android.gms.common.internal.BaseGmsClient$zza.deliverCallback(Unknown Source:62)
at com.google.android.gms.common.internal.BaseGmsClient$zza.deliverCallback(Unknown Source:2)
at com.google.android.gms.common.internal.BaseGmsClient$CallbackProxy.deliverCallback(Unknown Source:51)
at com.google.android.gms.common.internal.BaseGmsClient$zzb.handleMessage(Unknown Source:270)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Also in my Build Gradle App
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.github.glomadrian:MaterialAnimatedSwitch:1.1#aar'
implementation 'com.firebase:geofire-android:2.3.1'
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:16.0.3'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.google.android.gms:play-services-analytics:16.0.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//Add Library
implementation 'com.github.d-max:spots-dialog:0.7#aar'
implementation 'uk.co.chrisjenx:calligraphy:latest.integration'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.google.firebase:firebase-database:16.0.2'
implementation 'com.firebaseui:firebase-ui-database:4.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
apply plugin: 'com.google.gms.google-services'
this is my Welcome activity
package com.example.mac.uberclone;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
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.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Welcome extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
//Play Service
private static final int MY_PERMISSION_REQUEST_CODE = 7000;
private static final int PLAY_SERVICE_RES_REQUEST = 7001;
private LocationRequest locationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Init View
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline)
{
startLocationUpdate();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are online",Snackbar.LENGTH_SHORT)
.show();
}
else
{
stopLocationUpdate();
mCurrent.remove();
Snackbar.make(mapFragment.getView(),"You are offline",Snackbar.LENGTH_SHORT)
.show();
}
}
});
//Geo Fire
drivers = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire (drivers);
setUpLocation();
}
//Press Ctrl+O
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
private void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICE_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
if (location_switch.isChecked())
{
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
//Update to firebase
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
//Add marker
if (mCurrent != null)
mCurrent.remove(); //Remove already marker
mCurrent = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
.position(new LatLng(latitude,longitude))
.title("You"));
// Move camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
//Draw animation rotate marker
rotateMarker(mCurrent,-360,mMap);
}
});
}
else
{
Log.d("Error", "Cannot get your location");
}
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = mCurrent.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot > 180?rot/2:rot);
if (t<1.0)
{
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest,this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdate();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
}
You try to ask for location updates using that line
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest,this);
The problem is that you never initialize locationRequest variable. You have next function
private void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
To fix your problem add this line at the end of createLocationRequest()
this.locationRequest = locationRequest
private void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority (LocationRequest.PRIORITY_HIGH_ACCURACY);
this.locationRequest = locationRequest;
}
This was the solution to the problem.

Cordova custom plugin with third party native android library not working

In my cordova project, I need to use native code that scan via scan device on PDA, not by camera. I have working native android project and I changed it to android library project. Then I copied res, src, project.properties and AndroidManifest.xml files into myCordovaPlugin-> src-> android-> LibraryProject. When I build my cordova app in Ripple, there is no error. But when I build in device, I'm getting this error message. "Error 102 cmd: Command failed with exit code 8". I tried some solutions that I found online. But still the error is there.
Please help me. I'm very new to cordova and this is my first applicaton. I'm very appreciate any help. Thank you.
Here is Scanner.java.
package com.customplugin.barcodescanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import android.util.Log;
public class Scanner extends CordovaPlugin {
public static final int REQUEST_CODE = 1;
private static final String SCAN_INTENT = com.adlink.sample.SDK.SCAN;
private CallbackContext callbackContext;
public Scanner() {
}
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
this.callbackContext = callbackContext;
if (action.equals(SCAN)) {
scan(args);
} else {
return false;
}
return true;
}
}
public void scan(JSONArray args) {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// add config as intent extras
if(args.length() > 0) {
JSONObject obj;
JSONArray names;
String key;
Object value;
for(int i=0; i<args.length(); i++) {
try {
obj = args.getJSONObject(i);
} catch(JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
names = obj.names();
for(int j=0; j<names.length(); j++) {
try {
key = names.getString(j);
value = obj.get(key);
if(value instanceof Integer) {
intentScan.putExtra(key, (Integer)value);
} else if(value instanceof String) {
intentScan.putExtra(key, (String)value);
}
} catch(JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
}
}
}
// avoid calling other phonegap apps
intentScan.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
this.cordova.startActivityForResult((CordovaPlugin) this, intentScan, REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, intent.getStringExtra("SCAN_RESULT"));
obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT"));
obj.put(CANCELLED, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else if (resultCode == Activity.RESULT_CANCELED) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, "");
obj.put(FORMAT, "");
obj.put(CANCELLED, true);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else {
//this.error(new PluginResult(PluginResult.Status.ERROR), this.callback);
this.callbackContext.error("Unexpected error");
}
}
}
/**
* Initiates a barcode encode.
*
* #param type Endoiding type.
* #param data The data to encode in the bar code.
*/
public void encode(String type, String data) {
Intent intentEncode = new Intent(ENCODE_INTENT);
intentEncode.putExtra(ENCODE_TYPE, type);
intentEncode.putExtra(ENCODE_DATA, data);
// avoid calling other phonegap apps
intentEncode.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
this.cordova.getActivity().startActivity(intentEncode);
}
}
And here is Scanner.js.
cordova.define('cordova/plugin/Scanner', function(require, exports, module) {
var exec = require("cordova/exec");
/**
* Empty constructor
*/
var customScanner = function() {
};
customScanner.prototype.scan=
function (successCallback, errorCallback) {
exec(successCallback,
errorCallback,
"Scanner",
"scan",
[]);
}
module.exports = new customScanner();
});
Here is plugin call from onDeviceReady function of index.js.
var Scanner = cordova.require("cordova/plugin/Scanner");
Scanner.scan();
Here is my Native ScannerActivity.java.
package com.mypackage.sample.SDK;
import com.mypackage.sample.SDK.ENGINE;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.RadioButton;
import android.widget.TextView;
public class ScanActivity extends Activity implements OnClickListener
{
private static FakeR fakeR;
private static final String TAG = "ScanActivity";
private static final int DIALOG_WAITTING = 2;
private BroadcastReceiver m_msgReceiver = null;
private DBaseUtil m_db = null;
private SparseArray<Boolean> m_engineSupported = null;
private TextView m_btnScan = null;
private RadioButton m_rbBarcode1D = null;
private RadioButton m_rbBarcodeCCD = null;
private TextView m_scanSymbology = null;
private TextView m_scanSize = null;
private TextView m_scanValue = null;
private TextView m_scanElapse = null;
private boolean m_inProgress = false;
private boolean m_scanStarted = false;
private int m_nextEngine = ADMSG.ENGINE.None;
private ProgressDialog m_dlgProgress = null;
private boolean m_showMoreInfo = false;
private long m_scanStartTime = 0;
private int m_scanMode = ADMSG.SCANMODE.ONETIME;
private int m_scanKeycode = -1;
#Override
public void onCreate(Bundle savedInstanceState)
{
fakeR = new FakeR(this);
super.onCreate(savedInstanceState);
setContentView(fakeR.getId("layout", "scan_main"));
m_db = new DBaseUtil(this);
m_engineSupported = new SparseArray<Boolean>();
decideScanEngine();
boolean Barcode1D_enabled = engineEnabled(ADMSG.ENGINE.Barcode_1D);
boolean BarcodeCCD_enabled = engineEnabled(ADMSG.ENGINE.Barcode_CCD);
Log.d(TAG, "onCreate - Barcode_1D="+Barcode1D_enabled+", Barcode_CCD="+BarcodeCCD_enabled);
if(!Barcode1D_enabled && !BarcodeCCD_enabled)
{
showDialog_noSupportedEngine();
}
m_btnScan = (TextView)findViewById(fakeR.getId("id", "btnScan"));
m_btnScan.setOnClickListener(this);
//m_btnScan.setOnKeyListener(this);
m_rbBarcode1D = setEngineSwitch(fakeR.getId("id", "Reader_Barcode_1D"), Barcode1D_enabled);
m_rbBarcodeCCD = setEngineSwitch(fakeR.getId("id", "Reader_Barcode_CCD"), BarcodeCCD_enabled);
m_scanKeycode = getBgScanKeycode();
//Log.d(TAG, "onCreate - scanKeycode="+m_scanKeycode);
int currentEngine = checkAndCorrectEngine(m_db.getCurrentEngine());
Log.d(TAG, "onCreate - currentEngine="+currentEngine);
switch(currentEngine)
{
case ADMSG.ENGINE.Barcode_1D: m_rbBarcode1D.setChecked(true); break;
case ADMSG.ENGINE.Barcode_CCD: m_rbBarcodeCCD.setChecked(true); break;
}
m_scanSymbology = (TextView)findViewById(fakeR.getId("id", "scan_symbology"));
//m_scanSymbology.setVisibility((m_rbBarcodeCCD.isChecked())?(View.GONE):(View.VISIBLE));
if(m_showMoreInfo)
{
m_scanSize = (TextView)findViewById(fakeR.getId("id", "scan_size"));
m_scanSize.setVisibility(View.VISIBLE);
m_scanElapse = (TextView)findViewById(fakeR.getId("id", "scan_elapse"));
m_scanElapse.setVisibility(View.VISIBLE);
}
m_scanValue = (TextView)findViewById(fakeR.getId("id", "scan_value"));
m_scanValue.setMovementMethod(new ScrollingMovementMethod());
}
#Override
public void onRestart()
{
Log.d(TAG, "onRestart");
super.onRestart();
m_scanSymbology.setText(null);
m_scanValue.setText(null);
if(m_scanSize != null)
{
m_scanSize.setText(null);
}
if(m_scanElapse != null)
{
m_scanElapse.setText(null);
}
}
#Override
public void onResume()
{
Log.d(TAG, "onResume");
super.onResume();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
if(pref != null)
{
m_scanMode = (pref.getBoolean("_System_ScanMode_Continuous_", false))?(ADMSG.SCANMODE.CONTINUOUS):(ADMSG.SCANMODE.ONETIME);
}
switch(m_db.getCurrentEngine())
{
case ADMSG.ENGINE.Barcode_1D: m_rbBarcode1D.setChecked(true); break;
case ADMSG.ENGINE.Barcode_CCD: m_rbBarcodeCCD.setChecked(true); break;
}
disableBgScanMode();
enableFgScanMode();
registerMessageReceivers();
}
#Override
public void onPause()
{
Log.d(TAG, "onPause");
unregisterMessageReceivers();
disableFgScanMode();
enableBgScanMode();
setScanButtonState(false);
super.onPause();
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
if(keyCode == m_scanKeycode)
{
onClick(m_btnScan);
return(true);
}
return(super.onKeyUp(keyCode, event));
}
#Override
public void onClick(View view)
{
if(view == m_btnScan)
{
if(m_inProgress)
{
if(m_scanMode == ADMSG.SCANMODE.CONTINUOUS)
{
stopScan();
}
}
else
{
startScan();
}
}
else if(view == m_rbBarcode1D)
{
changeEngine(ADMSG.ENGINE.Barcode_1D);
}
else if(view == m_rbBarcodeCCD)
{
changeEngine(ADMSG.ENGINE.Barcode_CCD);
}
}
private void decideScanEngine()
{
boolean enable_1D = m_db.getEngineSupported(ADMSG.ENGINE.Barcode_1D);
boolean enable_CCD = m_db.getEngineSupported(ADMSG.ENGINE.Barcode_CCD);
m_engineSupported.put(ADMSG.ENGINE.Barcode_1D, enable_1D);
m_engineSupported.put(ADMSG.ENGINE.Barcode_CCD, enable_CCD);
int currentEngine = m_db.getCurrentEngine();
Log.d(TAG, "decideScanEngine - currentEngine="+currentEngine);
if(!isValidEngine(currentEngine))
{
m_db.setCurrentEngine(checkAndCorrectEngine(currentEngine));
}
}
private boolean engineEnabled(int id)
{
return(m_engineSupported.get(id));
}
private boolean isValidEngine(int engine)
{
return((engine == ENGINE.Barcode_1D) || (engine == ENGINE.Barcode_CCD));
}
private int checkAndCorrectEngine(int engine)
{
int validEngine = engine;
/*
if(!isValidEngine(validEngine))
{
validEngine = m_db.getCurrentEngine();
}
*/
if(!isValidEngine(validEngine))
{
if(engineEnabled(ADMSG.ENGINE.Barcode_CCD))
{
validEngine = ADMSG.ENGINE.Barcode_CCD;
}
else if(engineEnabled(ADMSG.ENGINE.Barcode_1D))
{
validEngine = ADMSG.ENGINE.Barcode_1D;
}
else
{
validEngine = ADMSG.ENGINE.None;
}
}
Log.d(TAG, "checkAndCorrectEngine - validEngine="+validEngine);
return(validEngine);
}
private RadioButton setEngineSwitch(int resId, boolean enabled)
{
RadioButton rb = (RadioButton)findViewById(resId);
if(rb != null)
{
rb.setOnClickListener(this);
if(!enabled)
{
rb.setVisibility(View.GONE);
}
}
return(rb);
}
private void registerMessageReceivers()
{
if(m_msgReceiver == null)
{
m_msgReceiver = new MessageReceiver();
}
IntentFilter filter = new IntentFilter();
filter.addAction(ADMSG.ACTION.OBTAIN_SCAN_DATA);
filter.addAction(ADMSG.ACTION.ENGINE_STATE_CHANGED);
registerReceiver(m_msgReceiver, filter);
}
private void unregisterMessageReceivers()
{
if(m_msgReceiver != null)
{
unregisterReceiver(m_msgReceiver);
}
}
private class MessageReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(TAG, "onReceive - action="+action);
if(ADMSG.ACTION.OBTAIN_SCAN_DATA.equals(action))
{
String value = intent.getStringExtra(ADMSG.KEY.SCAN.VALUE);
String symbology = intent.getStringExtra(ADMSG.KEY.SCAN.SYMBOLOGY);
boolean finished = intent.getBooleanExtra(ADMSG.KEY.SCAN.FINISHED, true);
Log.d(TAG, "\tvalue="+value);
m_scanSymbology.setText(symbology);
m_scanValue.setText(value);
m_scanValue.scrollTo(0, 0);
if(m_scanSize != null)
{
int dataCnt = (value != null)?(value.length()):(0);
m_scanSize.setText(String.format("%d", dataCnt));
}
if(m_scanElapse != null)
{
long elapse = SystemClock.elapsedRealtime() - m_scanStartTime;
m_scanElapse.setText(String.format("%dms", elapse));
}
setScanButtonState(!finished);
}
else if(ADMSG.ACTION.ENGINE_STATE_CHANGED.equals(action))
{
Bundle extras = intent.getExtras();
if(extras == null)
{
return;
}
int currentEngine = m_db.getCurrentEngine();
int state = extras.getInt(ADMSG.KEY.ENGINE.STATE);
boolean engineChanged = extras.getBoolean(ADMSG.KEY.ENGINE.CHANGED);
Log.d(TAG, "onReceive - ENGINE_STATE_CHANGED - state="+state+", engineChanged="+engineChanged);
if(state == ADMSG.ENGINE.STATE.STARTED)
{
showInitEngineProgress(false);
}
else if((state == ADMSG.ENGINE.STATE.STARTING) ||
(state == ADMSG.ENGINE.STATE.STOPPING))
{
}
else if(state == ADMSG.ENGINE.STATE.STOPPED)
{
Log.d(TAG, "\tSTOPPED - engine: "+currentEngine+" -> "+m_nextEngine);
if((m_nextEngine == currentEngine) ||
!isValidEngine(m_nextEngine))
{
return;
}
m_db.setCurrentEngine(checkAndCorrectEngine(currentEngine));
m_nextEngine = ADMSG.ENGINE.None;
}
}
}
}
private void setScanMode(boolean bgScan, boolean enable)
{
Log.d(TAG, "setScanMode - bgScan="+bgScan+", enable="+enable);
Intent in = new Intent();
in.setAction((bgScan)?(ADMSG.ACTION.BGSCAN_MODE):(ADMSG.ACTION.FGSCAN_MODE));
in.putExtra(ADMSG.KEY.SCAN.COMMAND, (enable)?(ADMSG.CMD.ENABLE):(ADMSG.CMD.DISABLE));
in.putExtra(ADMSG.KEY.REQUESTER.PACKAGE, getPackageName());
in.putExtra(ADMSG.KEY.REQUESTER.CLASS, getClass().getName());
in.putExtra(ADMSG.KEY.SCAN.MODE, m_scanMode);
if(m_scanMode == ADMSG.SCANMODE.CONTINUOUS)
{
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.FIXED_PERIOD, false);
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.IGNORE_SAME_ONE, true);
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.STOP_IF_SUCCESS, true);
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.TIME_INTERVAL, 1500);
}
//in.putExtra(ADMSG.KEY.BGSCAN_KEYCODE, KeyEvent.KEYCODE_ENTER);
sendBroadcast(in);
}
private void enableBgScanMode()
{
setScanMode(true, true);
}
private void disableBgScanMode()
{
setScanMode(true, false);
}
private void enableFgScanMode()
{
setScanMode(false, true);
}
private void disableFgScanMode()
{
setScanMode(false, false);
}
private void startScan()
{
m_scanSymbology.setText(null);
m_scanValue.setText(null);
if(m_scanSize != null)
{
m_scanSize.setText(null);
}
if(m_scanElapse != null)
{
m_scanElapse.setText(null);
}
setScanButtonState(true);
sendScanCommand(this, -1, ADMSG.CMD.START);
m_scanStartTime = SystemClock.elapsedRealtime();
}
private void stopScan()
{
sendScanCommand(this, -1, ADMSG.CMD.STOP);
}
private void changeScanEngine(Context context, int engine)
{
//Log.d(TAG, "chageEngine - engine="+engine);
Intent in = new Intent();
in.setAction(ADMSG.ACTION.ENGINE_CHANGE);
in.putExtra(ADMSG.KEY.ENGINE.ID, engine);
context.sendBroadcast(in);
}
private void sendScanCommand(Context context, int engine, String cmd)
{
//Log.d(TAG, "startScanService - engine="+engine+", cmd="+cmd);
Bundle extras = new Bundle();
extras.putString(ADMSG.KEY.SCAN.COMMAND, cmd);
extras.putInt(ADMSG.KEY.SCAN.ENGINE, engine);
sendScanCommand(context, extras);
}
private void sendScanCommand(Context context, Bundle extras)
{
Intent in = new Intent();
in.setAction(ADMSG.ACTION.SCAN);
in.putExtras(extras);
context.sendBroadcast(in);
}
private void enableScanButton(boolean enabled)
{
//Log.d(TAG, "> enableScanButton - m_scanStarted="+m_scanStarted);
m_inProgress = !enabled;
Resources rcs = getResources();
if(m_scanMode == ADMSG.SCANMODE.CONTINUOUS)
{
int txtRes = (enabled)?(fakeR.getId("string", "txt_Scan")):(fakeR.getId("string", "txt_Stop"));
m_btnScan.setText(txtRes);
}
else
{
int txtColorRes = (enabled)?(fakeR.getId("color", "text_color_tab_checked")):(fakeR.getId("color", "text_color_tab_unchecked"));
m_btnScan.setTextColor(rcs.getColor(txtColorRes));
m_btnScan.setEnabled(enabled);
}
}
private void setScanButtonState(boolean pressed)
{
Log.d(TAG, ">> setScanButtonState - pressed="+pressed);
m_scanStarted = pressed;
enableScanButton(!pressed);
}
private void changeEngine(int engine)
{
int currentEngine = m_db.getCurrentEngine();
Log.d(TAG, "changeEngine - engine: "+currentEngine+" -> "+engine);
if(engine == currentEngine)
{
return;
}
showInitEngineProgress(true);
m_scanSymbology.setText(null);
m_scanValue.setText(null);
if(m_scanSize != null)
{
m_scanSize.setText(null);
}
if(m_scanElapse != null)
{
m_scanElapse.setText(null);
}
changeScanEngine(this, engine);
m_nextEngine = engine;
}
private void showInitEngineProgress(boolean show)
{
if(show)
{
enableScanButton(false);
showDialog(DIALOG_WAITTING);
return;
}
Log.d(TAG, "showInitEngineProgress - m_dlgProgress="+m_dlgProgress);
if(m_dlgProgress != null)
{
m_dlgProgress.dismiss();
//m_dlgProgress = null;
}
if(!m_scanStarted)
{
enableScanButton(true);
}
}
private int getBgScanKeycode()
{
try
{
return(Integer.valueOf(m_db.getBgScanKeycode()));
}
catch(NumberFormatException e)
{
Log.e(TAG, "getBgScanKeycode - "+e.toString());
}
catch(NullPointerException e)
{
Log.e(TAG, "getBgScanKeycode - "+e.toString());
}
return(KeyEvent.KEYCODE_DPAD_CENTER);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case DIALOG_WAITTING:
{
String msg = getResources().getString(fakeR.getId("string", "txt_Engine_initializing"));
if(m_dlgProgress == null)
{
m_dlgProgress = new ProgressDialog(this);
m_dlgProgress.setIndeterminate(true);
m_dlgProgress.setCancelable(false);
}
m_dlgProgress.setMessage(msg);
return(m_dlgProgress);
}
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(fakeR.getId("menu", "settings_menu"), menu);
MenuItem item = null;
item = menu.getItem(0);
item.setIcon(fakeR.getId("drawable", "ic_menu_preferences"));
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem item)
{
Intent preferences = new Intent();
preferences.setClass(ScanActivity.this, SettingsActivity.class);
startActivity(preferences);
return(true);
}
});
return(true);
}
private void showDialog_noSupportedEngine()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//builder.setTitle(R.string.txt_ResetToDefault);
builder.setMessage(fakeR.getId("string", "txt_NoAnyValidScanEngine"));
builder.setPositiveButton(fakeR.getId("string", "txt_OK"), null);
builder.show().setOnDismissListener(m_dlgResetDismissListener);
}
OnDismissListener m_dlgResetDismissListener = new OnDismissListener()
{
public void onDismiss(DialogInterface dialog)
{
finish();
}
};
}

Categories