How to remove the button after purchase - java

Please help!!!
I am creating a screen capture application and the problem is that after clicking the PRO button and after the purchase, the ads and the button do not hide.
I am trying to remove a button and ads using layout changes:
setContentView (R.layout.main_pro)
the code:
IabHelper.OnIabPurchaseFinishedListener () {
#Override
public void onIabPurchaseFinished (IabResult result, purchase purchase) {
if (result.isFailure ()) {
Log.d (TAG, "Purchase Error:" result);
return;
}
even if (purchase.getSku (). equals (SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView (R.layout.main_pro);
remove ads ();
Toast.makeText (MainActivity.this, “The purchase was successful,” Toast.LENGTH_LONG) .show ();
}
}
};
}
Full code:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.icu.text.SimpleDateFormat;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ViewFlipper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.davidgrigoryan.screenrecorder.util.Constants;
import com.davidgrigoryan.screenrecorder.util.IabHelper;
import com.davidgrigoryan.screenrecorder.util.IabResult;
import com.davidgrigoryan.screenrecorder.util.Inventory;
import com.davidgrigoryan.screenrecorder.util.Purchase;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 1000;
private int mScreenDensity;
File file;
private Context context;
private ShareActionProvider mShareActionProvider;
private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
static final String SKU_REMOVE_ADS = "android.test.purchased";
static final int RC_REQUEST = 10111;
private MediaProjectionCallback mMediaProjectionCallback;
private MediaRecorder mMediaRecorder;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int REQUEST_PERMISSION_KEY = 1;
boolean isRecording = false;
private FloatingActionButton rec;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Intent intent;
private Activity activity;
private boolean URL_TO_SHARE;
private ImageView wm;
private NotificationManagerCompat notificationManager;
private String title;
private String message;
private InterstitialAd mInterstitialAd;
private String testDeviceId;
AdRequest adRequest;
private AdView adView;
IabHelper mHelper;
String base64EncodedPublicKey = "PublicKey";
Boolean isAdsDisabled = false;
String payload = "Upgrade PRO";
private Inventory i;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
private static boolean isWidget = false;
private static Context appContext;
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView pro = (ImageView) findViewById(R.id.buy);
final SharedPreferences prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
pro.setVisibility(prefs.getBoolean("isPurchase", true) ? View.VISIBLE : View.INVISIBLE);
pro.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
purchaseRemoveAds();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Handler handler = new Handler();
final Timer timer = new Timer();
final TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 120000);
adView = (AdView) findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-9842509861911521/3646081879");
AdRequest adRequestInterstitial = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = new AdSize(320, 50);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-9842509861911521/3646081879");
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-9842509861911521/1961271598");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
if (!Service.hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
}
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mMediaRecorder = new MediaRecorder();
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
rec = (FloatingActionButton) findViewById(R.id.rec);
rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onToggleScreenShare();
}
});
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(false);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#Override
public void onIabSetupFinished(IabResult result, IabHelper.QueryInventoryFinishedListener mGotInventoryListener) throws IabHelper.IabAsyncInProgressException {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
return;
}
if (mHelper == null)
return;
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
queryPurchased();
IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView(R.layout.main_pro);
removeAds();
Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
}
}
};
}
private void queryPurchased() {
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else{
// does the user have the premium upgrade?
isAdsDisabled = inventory.hasPurchase(SKU_REMOVE_ADS);
// update UI accordingly
}
}
};
}
public void purchaseRemoveAds() {
try {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, 9, mPurchaseFinishedListener, "SECURITYSTRING");
} catch (Exception e) {
e.printStackTrace();
mHelper.flagEndAsync();
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.error)
.setMessage(R.string.error_play_store)
.setPositiveButton("OK", null)
.show();
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase finished: " + result + ", purchase: "
+ purchase);
if (mHelper == null)
return;
if (result.isFailure()) {
return;
}
if (!verifyDeveloperPayload(purchase)) {
return;
}
if (isAdsDisabled == true){
setContentView(R.layout.main_pro);
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
removeAds();
}
}
};
}
private void removeAds() {
adView.setEnabled(false);
adView.setVisibility(View.INVISIBLE);
}
public void onToggleScreenShare() {
if (!isRecording) {
Toast.makeText(getApplicationContext(), R.string.start_rec, Toast.LENGTH_LONG).show();
startService();
initRecorder();
shareScreen();
} else {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ads not loaded!");
}
Toast.makeText(getApplicationContext(), R.string.stop_rec, Toast.LENGTH_LONG).show();
stopService();
mMediaRecorder.stop();
mMediaRecorder.reset();
stopScreenSharing();
}
}
private void shareScreen() {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
private VirtualDisplay createVirtualDisplay() {
return mMediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
}
private void initRecorder() {
try {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //THREE_GPP
mMediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(16); // 30
mMediaRecorder.setVideoEncodingBitRate(3000000);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
private File initFile() {
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator + "ScreenRecorder");
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG,
R.string.error_folder
+ dir.getAbsolutePath());
file = null;
} else {
file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"'VIDEO-'yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return file;
}
private void stopScreenSharing() {
if (mVirtualDisplay == null) {
return;
}
mVirtualDisplay.release();
destroyMediaProjection();
isRecording = false;
}
private void destroyMediaProjection() {
if (mMediaProjection != null) {
mMediaProjection.unregisterCallback(mMediaProjectionCallback);
mMediaProjection.stop();
mMediaProjection = null;
}
Log.i(TAG, "MediaProjection Stopped");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_CODE) {
Log.e(TAG, "Unknown request code: " + requestCode);
return;
}
if (resultCode != RESULT_OK) {
Toast.makeText(this, R.string.denied, Toast.LENGTH_SHORT).show();
isRecording = false;
return;
}
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
} else
Log.d(TAG, "onActivityResult handled by IABUtil.");
mMediaProjectionCallback = new MediaProjectionCallback();
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
mMediaProjection.registerCallback(mMediaProjectionCallback, null);
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_KEY: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
onToggleScreenShare();
} else {
isRecording = false;
Snackbar.make(findViewById(android.R.id.content), R.string.message,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.enable,
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
private class MediaProjectionCallback extends MediaProjection.Callback {
#Override
public void onStop() {
if (isRecording) {
isRecording = false;
mMediaRecorder.stop();
mMediaRecorder.reset();
}
mMediaProjection = null;
stopScreenSharing();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onDestroy() {
if (mHelper != null)
try {
mHelper.dispose();
mHelper = null;
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
if (adView != null) {
adView.destroy();
}
super.onDestroy();
destroyMediaProjection();
}
private void about() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(R.string.about);
builder1.setMessage(R.string.description);
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#SuppressLint("ResourceType")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
about();
return true;
case R.id.share:
shareApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void shareApp() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
#SuppressLint({"StringFormatInvalid", "LocalSuppress"})
String extraText = getString(R.string.share_desc, getString(R.string.link));
intent.putExtra(Intent.EXTRA_TEXT, extraText);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
public void startService() {
Intent serviceIntent = new Intent(this, Background.class);
serviceIntent.putExtra("inputExtra", "Notification");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, Background.class);
stopService(serviceIntent);
}
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
return true;
}
}
And it looks like this:
What am I doing wrong? How can I fix this?
Thanks for any help!

Related

Waiting for the text optional module to be downloaded. Please wait. On Android Studio

I'm a new android developer and trying to make image to text app. I watched some tutorials and pretty sure that i don't make any mistakes. I'm using ML Kit for this project and got error when i tried to convert the image to text.
My main activity
package com.gorkemtand.textrecognition;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
import java.io.IOException;
import java.security.Permission;
public class MainActivity extends AppCompatActivity {
private MaterialButton inputImageBtn;
private MaterialButton recognizeTextBtn;
private ShapeableImageView imageIv;
private EditText recognizedTextEt;
private static final String TAG = "MAIN_TAG";
private Uri imageUri = null;
//to handle the result of Camere/Gallery permissions
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
//arrays of permission required to pick image from Camera,gallery
private String[] cameraPermissions;
private String[] storagePermissions;
private ProgressDialog progressDialog;
private TextRecognizer textRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputImageBtn = findViewById(R.id.inputImageBtn);
recognizeTextBtn = findViewById(R.id.recognizeBtn);
imageIv = findViewById(R.id.imageIv);
recognizedTextEt = findViewById(R.id.recognizedTextEd);
cameraPermissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please Wait");
progressDialog.setCanceledOnTouchOutside(false);
textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
inputImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInputImageDialog();
}
});
recognizeTextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageUri == null){
Toast.makeText(MainActivity.this,"Pick image first...",Toast.LENGTH_SHORT).show();
}
else {
recognizeTextFromImage();
}
}
});
}
private void recognizeTextFromImage() {
Log.d(TAG, "recognizeTextFromImage: ");
progressDialog.setMessage("Preparing image...");
progressDialog.show();
try {
InputImage inputImage = InputImage.fromFilePath(this,imageUri);
progressDialog.setMessage("Recognizing text...");
Task<Text> textTaskResult = textRecognizer.process(inputImage).addOnSuccessListener(new OnSuccessListener<Text>() {
#Override
public void onSuccess(Text text) {
progressDialog.dismiss();
String recognizedText = text.getText();
Log.d(TAG, "onSuccess: recognizedText: "+recognizedText);
recognizedTextEt.setText(recognizedText);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Log.e(TAG, "onFailure: ",e);
Toast.makeText(MainActivity.this,"Failed recognizing text due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
progressDialog.dismiss();
Log.e(TAG, "recognizeTextFromImage: ",e);
Toast.makeText(MainActivity.this,"Failed preparing image due to"+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
private void showInputImageDialog() {
PopupMenu popupMenu = new PopupMenu(this, inputImageBtn);
popupMenu.getMenu().add(Menu.NONE,1,1,"CAMERA");
popupMenu.getMenu().add(Menu.NONE,2,2,"GALLERY");
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if(id == 1){
Log.d(TAG, "onMenuItemClick: Camera Clicked...");
if(checkCameraPermissions()){
pickImageCamera();
}
else{
requestCameraPermissions();
}
}
else if(id == 2){
Log.d(TAG, "onMenuItemClick: Gallery Clicked...");
if(checkStoragePermision()){
pickImageGallery();
}
else{
requestStoragePermission();
}
}
return false;
}
});
}
private void pickImageGallery(){
Log.d(TAG, "pickImageGallery: ");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
galleryActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> galleryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
//image picked
Intent data = result.getData();
imageUri = data.getData();
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
//set to imageview
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled...",Toast.LENGTH_SHORT).show();
}
}
}
);
private void pickImageCamera(){
Log.d(TAG, "pickImageCamera: ");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Sample Title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraActivityResultLauncher.launch(intent);
}
private ActivityResultLauncher<Intent> cameraActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: imageUri "+imageUri);
imageIv.setImageURI(imageUri);
}
else{
Log.d(TAG, "onActivityResult: cancelled");
Toast.makeText(MainActivity.this,"Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
);
private boolean checkStoragePermision(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermissions(){
boolean cameraResult = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean storafeResult = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return cameraResult && storafeResult;
}
private void requestCameraPermissions(){
ActivityCompat.requestPermissions(this,cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && storageAccepted){
pickImageCamera();
}
else {
Toast.makeText(this, "Camera && Storage permissions are required", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
if(grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickImageGallery();
}
else {
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
Also i implemented these two
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
implementation 'com.google.android.gms:play-services-mlkit-text-recognition-common:18.0.0'
And give the permissions to manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the error i got:
Error
I searched the google and cnat find a solution. If u can help me i will be very happy.
I searched google and can't find anything works.
I solved by implementing com.google.mlkit:text-recognition:16.0.0-beta6
Are you testing on device without play store services? For example on an emulator? In order to use com.google.android.gms:play-services-mlkit-text-recognition:18.0.2 it has to be on a device with play store services.

How to open links in the corresponding page in webview android application and not in browser

I was tired of searching and trying months ago to try opening links in my webview app but not the browser. I hope I find a solution here.
if I add any links in my notifications, it only opens the application homepage.
I use onesignal to send push notification
This is my app class:
package com.drbrandat.grinta;
public class App extends MultiDexApplication {
private static final String ONESIGNAL_APP_ID = "4cda77cb-1587-4b27-b708-7a427b9c1b1b";
private String push_url = null;
#Override
public void onCreate() {
super.onCreate();
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
//OneSignal Push
OneSignal.initWithContext(this);
OneSignal.setAppId(String.valueOf(R.string.ONESIGNAL_APP_ID));
OneSignal.setNotificationOpenedHandler(new NotificationHandler());
}
private class NotificationHandler implements OneSignal.OSNotificationOpenedHandler {
#Override
public void notificationOpened(OSNotificationOpenedResult result) {
try {
JSONObject data = result.getNotification().getAdditionalData();
String webViewUrl = (data != null) ? data.optString("url", null) : null;
String browserUrl = result.getNotification().getLaunchURL();
if (webViewUrl != null || browserUrl != null) {
if (browserUrl != null) {
browserUrl = (browserUrl == null) ? webViewUrl : browserUrl;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(browserUrl));
startActivity(browserIntent);
Log.v("INFO", "Received notification while app was on foreground or url for browser");
} else {
push_url = webViewUrl;
}
} else {
Intent mainIntent;
mainIntent = new Intent(App.this, MainActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
public synchronized String getPushUrl(){
String url = push_url;
push_url = null;
return url;
}
public synchronized void setPushUrl(String url){
this.push_url = url;
}
}
This is my main activity:
package com.drbrandat.grinta.activity;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.drbrandat.grinta.App;
import com.drbrandat.grinta.Config;
import com.drbrandat.grinta.R;
import com.drbrandat.grinta.adapter.NavigationAdapter;
import com.drbrandat.grinta.drawer.menu.Action;
import com.drbrandat.grinta.drawer.menu.MenuItemCallback;
import com.drbrandat.grinta.drawer.menu.SimpleMenu;
import com.drbrandat.grinta.fragment.WebFragment;
import com.drbrandat.grinta.util.ThemeUtils;
import com.drbrandat.grinta.widget.SwipeableViewPager;
import com.drbrandat.grinta.widget.webview.WebToAppWebClient;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.onesignal.OneSignal;
import com.tjeannin.apprate.AppRate;
public class MainActivity extends AppCompatActivity implements MenuItemCallback{
//Views
public Toolbar mToolbar;
public View mHeaderView;
public TabLayout mSlidingTabLayout;
public SwipeableViewPager mViewPager;
//App Navigation Structure
private NavigationAdapter mAdapter;
private NavigationView navigationView;
private SimpleMenu menu;
private WebFragment CurrentAnimatingFragment = null;
private int CurrentAnimation = 0;
//Identify toolbar state
private static int NO = 0;
private static int HIDING = 1;
private static int SHOWING = 2;
//Keep track of the interstitials we show
private int interstitialCount = -1;
private InterstitialAd mInterstitialAd;
// OneSignal
private static final String ONESIGNAL_APP_ID = "4cda77cb-1587-4b27-b708-7a427b9c1b1b";
ImageView previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
try {
WebFragment.notification_url = getIntent().getExtras().getString("Notification_url","");
}catch (Exception e){
WebFragment.notification_url = "";
}
ThemeUtils.setTheme(this);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mHeaderView = (View) findViewById(R.id.header_container);
mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (SwipeableViewPager) findViewById(R.id.pager);
previous = (ImageView) findViewById(R.id.previous);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mAdapter = new NavigationAdapter(getSupportFragmentManager(), this);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String data = intent.getDataString();
((App) getApplication()).setPushUrl(data);
}
//Hiding ActionBar/Toolbar
if (Config.HIDE_ACTIONBAR)
getSupportActionBar().hide();
if (getHideTabs())
mSlidingTabLayout.setVisibility(View.GONE);
hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
if ((Config.HIDE_ACTIONBAR && getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) && getCollapsingActionBar())){
lp.topMargin = 0;
} else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR && !getHideTabs() && getCollapsingActionBar())){
lp.topMargin = getActionBarHeight();
} else if (!Config.HIDE_ACTIONBAR && !getHideTabs()){
lp.topMargin = getActionBarHeight() * 2;
}
mViewPager.setLayoutParams(lp);
//Tabs
mViewPager.setAdapter(mAdapter);
mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1);
mSlidingTabLayout.setupWithViewPager(mViewPager);
mSlidingTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (getCollapsingActionBar()) {
showToolbar(getFragment());
}
mViewPager.setCurrentItem(tab.getPosition());
showInterstitial();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
for (int i = 0; i < mSlidingTabLayout.getTabCount(); i++) {
if (Config.ICONS.length > i && Config.ICONS[i] != 0) {
mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]);
}
}
//Drawer
if (Config.USE_DRAWER) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout drawer = ((DrawerLayout) findViewById(R.id.drawer_layout));
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, 0, 0);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Menu items
navigationView = (NavigationView) findViewById(R.id.nav_view);
menu = new SimpleMenu(navigationView.getMenu(), this);
configureMenu(menu);
if (Config.HIDE_DRAWER_HEADER) {
navigationView.getHeaderView(0).setVisibility(View.GONE);
navigationView.setFitsSystemWindows(false);
} else {
if (Config.DRAWER_ICON != R.mipmap.ic_launcher)
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setImageResource(Config.DRAWER_ICON);
else {
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.launcher_icon)).setVisibility(View.VISIBLE);
((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setVisibility(View.INVISIBLE);
}
}
} else {
((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//Admob
if (!getResources().getString(R.string.ad_banner_id).equals("")) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
adView.loadAd(adRequest);
} else {
AdView adView = (AdView) findViewById(R.id.adView);
adView.setVisibility(View.GONE);
}
if (getResources().getString(R.string.ad_interstitial_id).length() > 0 && Config.INTERSTITIAL_INTERVAL > 0){
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id));
AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
mInterstitialAd.loadAd(adRequestInter);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build());
}
});
}
//Application rating
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.rate_title))
.setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name)))
.setPositiveButton(getString(R.string.rate_yes), null)
.setNegativeButton(getString(R.string.rate_never), null)
.setNeutralButton(getString(R.string.rate_later), null);
new AppRate(this)
.setShowIfAppHasCrashed(false)
.setMinDaysUntilPrompt(2)
.setMinLaunchesUntilPrompt(2)
.setCustomDialog(builder)
.init();
//Showing the splash screen
if (Config.SPLASH) {
findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
findViewById(R.id.mmprogressbar).setVisibility(View.VISIBLE);
//getFragment().browser.setVisibility(View.GONE);
}
//Toolbar styling
if (Config.TOOLBAR_ICON != 0) {
getSupportActionBar().setTitle("");
ImageView imageView = findViewById(R.id.toolbar_icon);
imageView.setImageResource(Config.TOOLBAR_ICON);
imageView.setVisibility(View.VISIBLE);
if (!Config.USE_DRAWER){
imageView.setScaleType(ImageView.ScaleType.FIT_START);
}
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WebView browser = getFragment().browser;
browser.goBack();
}
});
}
// using the back button of the device
#Override
public void onBackPressed() {
View customView = null;
WebChromeClient.CustomViewCallback customViewCallback = null;
if (getFragment().chromeClient != null) {
customView = getFragment().chromeClient.getCustomView();
customViewCallback = getFragment().chromeClient.getCustomViewCallback();
}
if ((customView == null)
&& getFragment().browser.canGoBack()) {
getFragment().browser.goBack();
} else if (customView != null
&& customViewCallback != null) {
customViewCallback.onCustomViewHidden();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if(isHome){
previous.setVisibility(View.GONE);
inflater.inflate(R.menu.menu2, menu);
}else{
previous.setVisibility(View.VISIBLE);
inflater.inflate(R.menu.menu, menu);
}
//Adjust menu item visibility/availability based on settings
if (Config.HIDE_MENU_SHARE) {
menu.findItem(R.id.share).setVisible(false);
}
if (Config.HIDE_MENU_HOME) {
menu.findItem(R.id.home).setVisible(false);
}
if (Config.HIDE_MENU_NAVIGATION){
menu.findItem(R.id.previous).setVisible(false);
menu.findItem(R.id.next).setVisible(false);
}
if (!Config.SHOW_NOTIFICATION_SETTINGS || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
menu.findItem(R.id.notification_settings).setVisible(false);
}
ThemeUtils.tintAllIcons(menu, this);
return true;
}
//added
public static boolean isHome = true;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
WebView browser = getFragment().browser;
if (item.getItemId() == (R.id.next)) {
browser.goForward();
return true;
} else if (item.getItemId() == R.id.previous) {
browser.goBack();
return true;
} else if (item.getItemId() == R.id.share) {
getFragment().shareURL();
return true;
} else if (item.getItemId() == R.id.about) {
AboutDialog();
return true;
} else if (item.getItemId() == R.id.home) {
browser.loadUrl(getFragment().mainUrl);
return true;
} else if (item.getItemId() == R.id.close) {
finish();
Toast.makeText(getApplicationContext(),
getText(R.string.exit_message), Toast.LENGTH_SHORT).show();
return true;
} else if (item.getItemId() == R.id.notification_settings){
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
/**
* Showing the About Dialog
*/
private void AboutDialog() {
// setting the dialogs text, and making the links clickable
final TextView message = new TextView(this);
// i.e.: R.string.dialog_message =>
final SpannableString s = new SpannableString(
this.getText(R.string.dialog_about));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setTextSize(15f);
int padding = Math.round(20 * getResources().getDisplayMetrics().density);
message.setPadding(padding, 15, padding, 15);
message.setText(Html.fromHtml(getString(R.string.dialog_about)));
message.setMovementMethod(LinkMovementMethod.getInstance());
// creating the actual dialog
AlertDialog.Builder AlertDialog = new AlertDialog.Builder(this);
AlertDialog.setTitle(Html.fromHtml(getString(R.string.about)))
// .setTitle(R.string.about)
.setCancelable(true)
// .setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("ok", null).setView(message).create().show();
}
/**
* Set the ActionBar Title
* #param title title
*/
public void setTitle(String title) {
if (mAdapter != null && mAdapter.getCount() == 1 && !Config.USE_DRAWER && !Config.STATIC_TOOLBAR_TITLE)
getSupportActionBar().setTitle(title);
}
/**
* #return the Current WebFragment
*/
public WebFragment getFragment(){
return (WebFragment) mAdapter.getCurrentFragment();
}
/**
* Hide the Splash Screen
*/
public void hideSplash() {
if (Config.SPLASH) {
if (findViewById(R.id.imageLoading1).getVisibility() == View.VISIBLE) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
// hide splash image
findViewById(R.id.imageLoading1).setVisibility(
View.GONE);
}
// set a delay before splashscreen is hidden
}, Config.SPLASH_SCREEN_DELAY);
}
if (findViewById(R.id.mmprogressbar).getVisibility() == View.VISIBLE) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
// hide splash image
findViewById(R.id.mmprogressbar).setVisibility(
View.GONE);
}
// set a delay before splashscreen is hidden
}, Config.SPLASH_SCREEN_DELAY);
}
}
}
/**
* Hide the toolbar
*/
public void hideToolbar() {
if (CurrentAnimation != HIDING) {
CurrentAnimation = HIDING;
AnimatorSet animSetXY = new AnimatorSet();
ObjectAnimator animY = ObjectAnimator.ofFloat(getFragment().rl, "y", 0);
ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, "y", -getActionBarHeight());
animSetXY.playTogether(animY, animY1);
animSetXY.start();
animSetXY.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
CurrentAnimation = NO;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
/**
* Show the toolbar
* #param fragment for which to show the toolbar
*/
public void showToolbar(WebFragment fragment) {
if (CurrentAnimation != SHOWING || fragment != CurrentAnimatingFragment) {
CurrentAnimation = SHOWING;
CurrentAnimatingFragment = fragment;
AnimatorSet animSetXY = new AnimatorSet();
ObjectAnimator animY = ObjectAnimator.ofFloat(fragment.rl, "y", getActionBarHeight());
ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, "y", 0);
animSetXY.playTogether(animY, animY1);
animSetXY.start();
animSetXY.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
CurrentAnimation = NO;
CurrentAnimatingFragment = null;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
public int getActionBarHeight() {
int mHeight = mToolbar.getHeight();
//Just in case we get a unreliable result, get it from metrics
if (mHeight == 0){
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
mHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
}
return mHeight;
}
boolean getHideTabs(){
if (mAdapter.getCount() == 1 || Config.USE_DRAWER){
return true;
} else {
return Config.HIDE_TABS;
}
}
public static boolean getCollapsingActionBar(){
if (Config.COLLAPSING_ACTIONBAR && !Config.HIDE_ACTIONBAR){
return true;
} else {
return false;
}
}
/**
* Check permissions on app start
* #param context
* #param permissions Permissions to check
* #return if the permissions are available
*/
private static boolean hasPermissionToDo(final Activity context, final String[] permissions) {
boolean oneDenied = false;
for (String permission : permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED)
oneDenied = true;
}
if (!oneDenied) return true;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.common_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(permissions,1);
}
});
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
/**
* Show an interstitial ad
*/
public void showInterstitial(){
if (interstitialCount == (Config.INTERSTITIAL_INTERVAL - 1)) {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
interstitialCount = 0;
} else {
interstitialCount++;
}
}
/**
* Configure the navigationView
* #param menu to modify
*/
public void configureMenu(SimpleMenu menu){
for (int i = 0; i < Config.TITLES.length; i++) {
//The title
String title = null;
Object titleObj = Config.TITLES[i];
if (titleObj instanceof Integer && !titleObj.equals(0)) {
title = getResources().getString((int) titleObj);
} else {
title = (String) titleObj;
}
//The icon
int icon = 0;
if (Config.ICONS.length > i)
icon = Config.ICONS[i];
menu.add((String) Config.TITLES[i], icon, new Action(title, Config.URLS[i]));
}
menuItemClicked(menu.getFirstMenuItem().getValue(), menu.getFirstMenuItem().getKey());
}
#Override
public void menuItemClicked(Action action, MenuItem item) {
if (WebToAppWebClient.urlShouldOpenExternally(action.url)){
//Load url outside WebView
try {
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url)));
} catch(ActivityNotFoundException e) {
if (action.url.startsWith("intent://") || (action.url.startsWith("whatsapp:")
|| (action.url.startsWith("tel:")))){
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("intent://", "http://"))));
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("whatsapp:", "http://")));
new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace("tel:", "http://")));
} else {
Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show();
}
}
} else {
//Uncheck all other items, check the current item
for (MenuItem menuItem : menu.getMenuItems())
menuItem.setChecked(false);
item.setChecked(true);
//Close the drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
//Load the url
if (getFragment() == null) return;
getFragment().browser.loadUrl("about:blank");
getFragment().setBaseUrl(action.url);
//Show intersitial if applicable
showInterstitial();
Log.v("INFO", "Drawer Item Selected");
}
}
}

How to make BLE scan and MQTT publish work in background Android Studio Java

I want make some project where Android can scan nearby Beacon/BLE and send it using MQTT. But I want the service to work in the background if the service work in the foreground it will interrupt the scanning process when screen is off.
This is my code for scanning:
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
// final Handler handlerStop = new Handler();
// handlerStop.postDelayed(new Runnable() {
// #Override
// public void run() {
// bluetoothAdapter.cancelDiscovery();
// Log.d("Logger", "Cancel Dsicovery");
// handlerStop.postDelayed(this, 2000);
// }
// }, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
Log.d("Logger", "Discover");
bluetoothAdapter.startDiscovery();
}
}
}
// else {
// Log.d("Logger", "Cancel");
// bluetoothAdapter.cancelDiscovery();
// }
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
Log.d("Logger", "Recive data "+device.getAddress());
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Sending data");
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
Log.d("Logger", "Error Sending "+e);
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
App Flow:
Insert MQTT server, port, id, topic.
Turn on the proccess.
Android scan BLE/Beacon
Android sending MAC/RSSI to MQTT
I hope someone can help to guide me, on how to make the application run in the background?
I'm a beginner, and I don't understand how to implement background service in my application. Please help me!
You need to implement a foreground service that will handle your ble scanning and MQTT logic.
See this article with an overview of how to do it. Depending on your build/target SDK, the implementation will vary.

Green N White Screen issue in Camera activity Android

This bug is only on some devices.
Project scope:
Indoor navigation system used in malls/ships to locate shops.
It uses beacons to locate shops with bluetooth connection. It uses camera to show directions (arrow) image overlays.
In ArCameraActivity, half green screen shows up in camera preview.
code:
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.Matrix;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dagger.android.support.DaggerAppCompatActivity;
public class ARActivity extends DaggerAppCompatActivity implements SensorEventListener, LocationListener,
ActivityCompat.OnRequestPermissionsResultCallback, ARView {
private static boolean IS_NAVIGATION_CLICKED = false;
#Inject
ARPresenter presenter;
#BindView(R.id.img_clear)
ImageView imgClear;
#BindView(R.id.img_logout)
ImageView imgLogout;
#BindView(R.id.img_map)
ImageView imgMap;
#BindView(R.id.img_navigation)
ImageView imgNavigation;
final static String TAG = "ARActivity";
private SurfaceView surfaceView;
private FrameLayout cameraContainerLayout;
private AROverlayView arOverlayView;
private Camera camera;
private ARCamera arCamera;
private TextView tvCurrentLocation;
private SensorManager sensorManager;
private final static int REQUEST_CAMERA_PERMISSIONS_CODE = 11;
public static final int REQUEST_LOCATION_PERMISSIONS_CODE = 0;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute
private LocationManager locationManager;
public Location location;
boolean isGPSEnabled;
boolean isNetworkEnabled;
boolean locationServiceAvailable;
private ScanRegionsService scanRegionsService;
private boolean isBeaconLoaded = false;
// private static GetMallResponse.Data.Mall identifiedMall;
private Dialog dialog = null;
private static final String IMAGE_URL = "http://98.156.231.92/maps/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ar);
ButterKnife.bind(this);
sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
cameraContainerLayout = (FrameLayout) findViewById(R.id.camera_container_layout);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
tvCurrentLocation = (TextView) findViewById(R.id.tv_current_location);
arOverlayView = new AROverlayView(this);
scanRegionsService = new ScanRegionsService(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
beginService();
}
}
if (Util.getSelectedShop() != null) {
showLoading();
}
}
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (!isBeaconLoaded) {
Log.d(TAG, "run: "+ isBeaconLoaded);
dismissLoading();
if(!isFinishing()) {
new AlertDialog.Builder(ARActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("There is no beacon in your surroundings")
.setMessage("Are you sure you want to stop navigation?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.setSelectedShop(null);
finish();
}
})
.show();
}
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION) &&
grantResults[i] == PackageManager.PERMISSION_GRANTED) {
beginService();
} else if (permissions[i].equalsIgnoreCase(Manifest.permission.CAMERA) &&
grantResults[i] == PackageManager.PERMISSION_DENIED) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
}
private void beginService() {
isBeaconLoaded = false;
arOverlayView.registerReceiver();
scanRegionsService.setupSpaces();
scanRegionsService.startScanning();
onMallIdentified(Util.getSelectedMall());
new Handler().postDelayed(mRunnable, 10000);
}
#OnClick(R.id.img_map)
public void onMapClicked() {
arOverlayView.unregisterReceiver();
// Util.getRouteMap().clear();
Util.setSelectedShop(null);
// Intent intent = new Intent(this, MainActivity.class);
// startActivity(intent);
finish();
}
#OnClick(R.id.img_navigation)
public void onNavClicked() {
if (!IS_NAVIGATION_CLICKED) {
IS_NAVIGATION_CLICKED = true;
arOverlayView.showNavigationMap();
imgNavigation.setImageDrawable(getResources().getDrawable(R.drawable.navigation_on));
} else {
IS_NAVIGATION_CLICKED = false;
arOverlayView.hideNavigationMap();
imgNavigation.setImageDrawable(getResources().getDrawable(R.drawable.navigation_off));
}
}
#OnClick(R.id.img_logout)
public void onLogoutClicked() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to logout?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.set("authToken", "");
Intent intent = new Intent(ARActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onBackPressed() {
if(!((Activity) this).isFinishing()) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to exit the screen?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
#Override
public void onResume() {
super.onResume();
requestLocationPermission();
requestCameraPermission();
registerSensors();
initAROverlayView();
IntentFilter intentFilter = new IntentFilter(ForegroundScanService.ACTION_DEVICE_DISCOVERED);
registerReceiver(scanningBroadcastReceiver, intentFilter);
}
public void showClearMap() {
imgClear.setVisibility(View.VISIBLE);
}
public void hideClearMap() {
imgClear.setVisibility(View.GONE);
}
#OnClick(R.id.img_clear)
public void onClearClicked() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to stop navigation?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.setSelectedShop(null);
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onPause() {
unregisterReceiver(scanningBroadcastReceiver);
releaseCamera();
super.onPause();
}
public void requestCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSIONS_CODE);
} else {
initARCameraView();
}
}
public void requestLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSIONS_CODE);
} else {
initLocationService();
}
}
public void initAROverlayView() {
if (arOverlayView.getParent() != null) {
((ViewGroup) arOverlayView.getParent()).removeView(arOverlayView);
}
cameraContainerLayout.addView(arOverlayView);
}
public void initARCameraView() {
reloadSurfaceView();
if (arCamera == null) {
arCamera = new ARCamera(this, surfaceView);
}
if (arCamera.getParent() != null) {
((ViewGroup) arCamera.getParent()).removeView(arCamera);
}
cameraContainerLayout.addView(arCamera);
arCamera.setKeepScreenOn(true);
initCamera();
}
private void initCamera() {
int numCams = Camera.getNumberOfCameras();
if (numCams > 0) {
try {
camera = Camera.open();
camera.startPreview();
arCamera.setCamera(camera);
} catch (RuntimeException ex) {
Toast.makeText(this, "Camera not found", Toast.LENGTH_LONG).show();
}
}
}
private void reloadSurfaceView() {
if (surfaceView.getParent() != null) {
((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
}
cameraContainerLayout.addView(surfaceView);
}
private void releaseCamera() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
arCamera.setCamera(null);
camera.release();
camera = null;
}
}
private void registerSensors() {
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
float[] rotationMatrixFromVector = new float[16];
float[] projectionMatrix = new float[16];
float[] rotatedProjectionMatrix = new float[16];
SensorManager.getRotationMatrixFromVector(rotationMatrixFromVector, sensorEvent.values);
if (arCamera != null) {
projectionMatrix = arCamera.getProjectionMatrix();
}
Matrix.multiplyMM(rotatedProjectionMatrix, 0, projectionMatrix, 0, rotationMatrixFromVector, 0);
this.arOverlayView.updateRotatedProjectionMatrix(rotatedProjectionMatrix);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
//do nothing
}
private void initLocationService() {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
this.locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
this.locationServiceAvailable = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateLatestLocation();
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateLatestLocation();
}
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
private void updateLatestLocation() {
if (arOverlayView != null && location != null) {
arOverlayView.updateCurrentLocation(location);
tvCurrentLocation.setText(String.format("lat: %s \nlon: %s \naltitude: %s \n",
location.getLatitude(), location.getLongitude(), location.getAltitude()));
}
}
#Override
public void onLocationChanged(Location location) {
updateLatestLocation();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private final BroadcastReceiver scanningBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: ");
isBeaconLoaded = true;
String shopname=Util.getSelectedShop().getShopImage();
Toast.makeText(context, "You are in "+shopname, Toast.LENGTH_LONG).show();
int devicesCount = intent.getIntExtra(BackgroundScanService.EXTRA_DEVICES_COUNT, 0);
RemoteBluetoothDevice device = intent.getParcelableExtra(BackgroundScanService.EXTRA_DEVICE);
Log.i("BEACON", String.format("Total discovered devices: %d\n\nLast scanned device:\n%s", devicesCount, device.toString()));
// statusText.setText(String.format("Total discovered devices: %d\n\nLast scanned device:\n%s", devicesCount, device.toString()));
}
};
#Override
public void onMallIdentified(GetMallResponse.Data.Mall mall) {
// identifiedMall = mall;
// Toast.makeText(this, "Identified "+mall.getPropertyName(), Toast.LENGTH_LONG).show();
presenter.loadShops(mall.getId());
presenter.loadRouteBeacons(mall.getId());
}
public void onUnkownPlaceIdentified() {
arOverlayView.registerReceiver();
Toast.makeText(this, "Unknown place identified", Toast.LENGTH_LONG).show();
List<GetRouteBeaconsResponse.Data.Route> floorRoute = new ArrayList<>();
}
#Override
public void onShopLoaded(List<GetShopsResponse.Data.Shop> shops) {
Log.i(TAG, "onShopLoaded");
if (shops.size() > 0) {
Util.shopMap.clear();
Log.i(TAG, "onShopLoaded shops.size " + shops.size());
Util.activeDeviceMap.clear();
for (GetShopsResponse.Data.Shop shop : shops) {
Util.shopMap.put("" + shop.getId(), shop);
if (shop.getAdImage().length() > 0) {
Drawable drbl = Util.promoImageMap.get(IMAGE_URL + shop.getAdImage());
if (drbl == null) {
String imgkey = IMAGE_URL + shop.getAdImage();
drbl = getResources().getDrawable(R.drawable.promo1, null);
Util.promoImageMap.put(imgkey, drbl);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Drawable drb2 = drawableFromUrl(imgkey);
Util.promoImageMap.put(IMAGE_URL + shop.getAdImage(), drb2);
} catch (Exception e) {
Log.i(TAG, "Unable to download image");
}
}
};
new Thread(runnable).start();
}
}
}
}
}
#Override
public void onRouteBeaconLoaded(List<GetRouteBeaconsResponse.Data.Route> floors) {
Log.d(TAG, "onRouteBeaconLoaded: ");
Log.i(TAG, "onRouteBeaconLoaded");
// if (floors.size()>0 && Util.getSelectedShop()!=null){
// Log.i(TAG, "onRouteBeaconLoaded floors.size "+floors.size());
// Util.getRouteMap().clear();
// for (GetRouteBeaconsResponse.Data.Route route: floors){
// String comkey = route.proximityUUID+route.major+route.minor;
// Util.getRouteMap().put(comkey, route);
// }
// Util.setSelectedShop(Util.getSelectedShop());
// Log.i(TAG, "onShopLoaded setup space scanRegionsService");
// scanRegionsService.setupSpaces();
// Log.i(TAG, "onShopLoaded startScanning");
// scanRegionsService.startScanning();
// }
if (floors.size() > 0) {
Log.i(TAG, "onRouteBeaconLoaded floors.size " + floors.size());
Util.getRouteMap().clear();
for (GetRouteBeaconsResponse.Data.Route route : floors) {
String comkey = route.proximityUUID + route.major + route.minor;
Util.getRouteMap().put(comkey, route);
}
Log.i(TAG, "onShopLoaded setup space scanRegionsService");
scanRegionsService.setupSpaces();
Log.i(TAG, "onShopLoaded startScanning");
scanRegionsService.startScanning();
}
arOverlayView.registerReceiver();
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
private void initLoadingDialog() {
dialog = new Dialog(this);
dialog.setCancelable(false);
dialog.setContentView(R.layout.show_loading);
TextView txtFind = dialog.findViewById(R.id.findingBeacons);
txtFind.setVisibility(View.VISIBLE);
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss();
}
return true;
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
public void showLoading() {
try {
if (dialog != null) {
dialog.show();
} else {
initLoadingDialog();
dialog.show();
}
} catch (Exception e) {
}
}
public void dismissLoading() {
try {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
}
green screen
Getting like this for camera activity in redmi y2 phone only. Its works well on other models. What might be issue? It shows directions in camera to shop using beacon device. Android os version is not problem.
white screen on some devices - samsung tab, oneplus 7, BLU G9 Pro phone
white screen
this activity shows navigation with help of beacons in camera shows overlay of imageview. it works on some devices, i have tried various methods to resolve it,
doesn't work. added latest camera v2 api.
How can i resolve this issue? thanks in advance.
Sometimes this "green screen" issue is caused by the camera's preview resolution. Try to get supported preview size from camera instance.
mParams = mCamera.getParameters();
List<Camera.Size> supportedPreviewSizes = mParams.getSupportedPreviewSizes();
Camera.Size bestPreviewSize = supportedPreviewSizes.get(0);
for (Camera.Size sz : supportedPreviewSizes) {
/* perfect match */
if(sz.width == mWidth && sz.height == mHeight) {
bestPreviewSize = sz;
break;
} else {
int bestArea = bestPreviewSize.width*bestPreviewSize.height;
int currArea = sz.width*sz.height;
int targetArea = mWidth*mHeight;
if (Math.abs(currArea-targetArea) < Math.abs(bestArea-targetArea)) {
bestPreviewSize = sz;
}
}
}
mCurrWidth = bestPreviewSize.width;
mCurrHeight = bestPreviewSize.height;
mParams.setPreviewSize(mCurrWidth, mCurrHeight);
/* Set preview format */
mParams.setPreviewFormat(ImageFormat.NV21);
/* Apply Parameters */
mCamera.setParameters(mParams);
mCamera.startPreview();
You can also try to force some fixed resolution depending on some device conditions, like display width, for example. Some resolutions i found useful on my use case:
width = 1280;
heigth = 720;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics windowMetrics = getWindowManager().getCurrentWindowMetrics();
if (isPortrait) {
if (windowMetrics.getBounds().width() <= 720) {
width = 720;
heigth = 480;
}
} else {
if (windowMetrics.getBounds().width() <= 1344) {
width = 960;
heigth = 540;
}
}
} else {
if (isPortrait) {
if (getDisplay().getWidth() <= 720) {
width = 720;
heigth = 480;
}
} else {
if (getDisplay().getWidth() <= 1344) {
width = 960;
heigth = 540;
}
}
}
Keep in mind that the best solution for me was getting the supported sizes to calculate the best preview size.

Facebook Login doesn't work, what did I forget?

Ok,
I'm doing this for 4 straight hours. And the facebook Login still doesn't work. The session state is always OPENING. ALWAYS. onActivityResult NEVER gets called. The key in the developer console is correct, the starting class is correct, and this is my code
package XXXXX
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import ua.org.zasadnyy.zvalidations.Field;
import ua.org.zasadnyy.zvalidations.Form;
import ua.org.zasadnyy.zvalidations.validations.HasMinimumLength;
import ua.org.zasadnyy.zvalidations.validations.IsEmail;
import ua.org.zasadnyy.zvalidations.validations.NotEmpty;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class SplashScreen extends FragmentActivity {
public static String TAG = "SplashScreen";
/**
* LoginActivity
*/
private static final int LOGIN = 0;
private static final int SIGNUP = 1;
private static final int SELECTUSERNAME = 2;
private static final int FRAGMENT_COUNT = SELECTUSERNAME +1;
private boolean isResumed = false;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private MenuItem settings;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback =
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/**
* UI Elements
*/
Button btn_signUp;
Button btn_signUpSubmit;
LoginButton btn_facebookAuth;
//Edit Text
EditText edittextEmail;
EditText edittextPassword;
//Form
Form signUpForm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.splash);
FragmentManager fm = getSupportFragmentManager();
fragments[LOGIN] = fm.findFragmentById(R.id.loginFragment);
fragments[SIGNUP] = fm.findFragmentById(R.id.signUpFragment);
fragments[SELECTUSERNAME] = fm.findFragmentById(R.id.selectUserNameFragment);
FragmentTransaction transaction = fm.beginTransaction();
for(int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
btn_signUp = ( Button ) findViewById(R.id.btn_signUpMail);
btn_signUp.setOnClickListener( listener_btn_signUp );
btn_signUpSubmit = (Button) findViewById(R.id.btn_signUpSubmit);
btn_signUpSubmit.setOnClickListener(listener_btn_signUpSubmit);
edittextEmail = (EditText)findViewById(R.id.et_signUpMail);
edittextPassword = (EditText)findViewById(R.id.et_signUpPw);
signUpForm = new Form ( this );
signUpForm.addField(Field.using(edittextEmail).validate(NotEmpty.build(this.getApplicationContext())).validate(IsEmail.build(this.getApplicationContext())));
signUpForm.addField(Field.using(edittextPassword).validate(NotEmpty.build(this.getApplicationContext())).validate(HasMinimumLength.build(this.getApplicationContext(), 8)));
btn_facebookAuth = (LoginButton)findViewById(R.id.login_button);
btn_facebookAuth.setReadPermissions(Arrays.asList("email"));
}
private OnClickListener listener_btn_signUp = new OnClickListener() {
#Override
public void onClick(View v) {
showFragment(SIGNUP, true);
}
};
private OnClickListener listener_btn_signUpSubmit = new OnClickListener() {
#Override
public void onClick(View v) {
if (signUpForm.isValid()) {
Log.i("SignupFragment", "Form is valid");
// User userModel = new User();
// userModel.isFacebookConnected = "0";
// userModel.userEmail = edittextEmail.getText().toString();
// userModel.userPassword = edittextPassword.getText().toString();
// SelectUserNameFragment selectUserNameFragment = new SelectUserNameFragment();
// SelectUserNameFragment.user = userModel;
// getFragmentManager()
// .beginTransaction()
// .replace(android.R.id.content, selectUserNameFragment)
// .addToBackStack("")
// .commit();
} else {
Log.i("SignupFragment", "Form not valid");
}
}
};
private void showFragment(int fragmentIndex, boolean addToBackStack) {
Log.i(TAG, "showFragment");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.i(TAG, "onSessionStateChange");
FragmentManager manager = getSupportFragmentManager();
int backStackSize = manager.getBackStackEntryCount();
for (int i = 0; i < backStackSize; i++) {
manager.popBackStack();
}
System.out.println ( state.name() );
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
User userModel = new User();
userModel.facebookId = user.getId();
Map<String, String> where = new HashMap<String, String>();
where.put("where", "WHERE facebookId='" + user.getId() + "'" );
userModel.loadModelFrom(where);
if ( userModel.userData.isEmpty() ) {
userModel.isFacebookConnected = "1";
userModel.userEmail = user.asMap().get("email").toString();
SelectUserNameFragment.user = userModel;
showFragment(SELECTUSERNAME, true);
} else {
Intent intent = new Intent ( getApplicationContext(), DashboardActivity.class );
intent.putExtra("User", userModel);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
// showFragment(DASHBOARD, false);
} else if (state.isClosed()) {
showFragment(LOGIN, false);
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
Log.i(TAG, "onResumeFragments");
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Intent intent = new Intent ( this, DashboardActivity.class );
intent.putExtra("Session", session);
startActivity(intent);
} else {
showFragment(LOGIN, false);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume");
uiHelper.onResume();
isResumed = true;
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "onPause");
uiHelper.onPause();
isResumed = false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
uiHelper.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
uiHelper.onSaveInstanceState(outState);
}
}
What did I forget?
Apparently it is not allowed to have
android:noHistory="true" in your manifest. I removed it and now it works.

Categories