Android Studio - if file exists in system folder then - java

It's my first project in java.
I want to add wallpaper backup/restore functionality to my app.
Code to backup:
public void btnBackupWallpaper(View view) {
File wallpaper = new File("/data/system/users/0/wallpaper");
if(wallpaper.exists()){
RootCmd.RunRootCmd("cp -f /data/system/users/0/wallpaper /data/local/tmp/wallpaper");
Toast.makeText(getApplicationContext(), "Wallpaper backup completed.",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Wallpaper not found.",
Toast.LENGTH_LONG).show();
}
}
Code to restore
public void btnRestoreWallpaper(View view) {
File wallpaper = new File("/data/local/tmp/wallpaper");
if(wallpaper.exists()){
RootCmd.RunRootCmd("cp /data/local/tmp/wallpaper /data/system/users/0/wallpaper");
RootCmd.RunRootCmd("chmod 0700 /data/system/users/0/wallpaper");
RootCmd.RunRootCmd("chown system.system /data/system/users/0/wallpaper");
RootCmd.RunRootCmd("rm /data/local/tmp/wallpaper");
Toast.makeText(getApplicationContext(), "Wallpaper restore completed.",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Wallpaper backup not found.",
Toast.LENGTH_LONG).show();
}
}
Restore working fine, but backup always says "Wallpaper not found".
File wallpaper = new File("/data/system/users/0/wallpaper");
if(wallpaper.exists()){}
Why is this part of code doesn't work?
Thanks.

My solution is to use RootTools:
public void btnBackupWallpaper(View view) {
if(RootTools.exists("/data/system/users/0/wallpaper")) {
RootCmd.RunRootCmd("cp -f /data/system/users/0/wallpaper /data/local/tmp/wallpaper");
Context context = getApplicationContext();
Toast.makeText(context, context.getString(R.string.wallpaper_backup_completed), Toast.LENGTH_LONG).show();
} else {
Context context = getApplicationContext();
Toast.makeText(context, context.getString(R.string.wallpaper_not_found), Toast.LENGTH_LONG).show();
}
}

Related

Firebase authentication with onCompleteListener not working

I am trying to implement a basic android authentication system with Firebase. The following is my code:
Toast.makeText(MainActivity.this, "BEFORE ON-COMPLETE", Toast.LENGTH_SHORT).show(); //this shows up
mAuth.signInWithEmailAndPassword(emailInputted, passInputted).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(MainActivity.this, "in OnComplete", Toast.LENGTH_SHORT).show(); //this does not show up
if(task.isSuccessful()){
Intent i = new Intent(MainActivity.this, Dashboard.class);
i.putExtra("EMAIL", emailInputted);
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(i);
} else {
Toast.makeText(MainActivity.this, "Please check email/password", Toast.LENGTH_SHORT).show();
}
}
});
Toast.makeText(MainActivity.this, "after OnComplete", Toast.LENGTH_SHORT).show(); //this shows up
I took this code from the official Firebase docs, but for some reason it is not working. The onComplete method is not being called for some reason. I can see the "before on-Complete" and "after on-complete" toasts, but not the "in OnComplete" one. I have added the users in my authentication table in the firebase console, and I am positive that I am entering the correct password.
After using the debugger, I saw that my code just skips over the onComplete() method, and does not even get to the isSuccessful() method. How do I fix this?
Thanks in advance!
Follow this, I hop you will get your answer.
lBut = findViewById(R.id.log_btn);
lBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a = usrn.getText().toString().trim();
String b = pswd.getText().toString().trim();
if (TextUtils.isEmpty(a) && TextUtils.isEmpty(b)) {
usrn.setError("Empty Email !!");
pswd.setError("Empty Password !!");
lBut.setClickable(false);
} else {
lBut.setClickable(true);
mAuth.signInWithEmailAndPassword(a, b).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#SuppressLint("ShowToast")
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Successfully Login!!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), HomeP.class);
ProgressBar prb = findViewById(R.id.progressBar);
prb.setVisibility(View.VISIBLE);
startActivity(i);
finish();
} else
Toast.makeText(getApplicationContext(), "Check Error And Try Again!!", Toast.LENGTH_SHORT).show();
}
});
}
}
});
This is the Event on the Login Button, you have more doubt then reply me.
So it fixed itself after I restarted my computer. No code changes. Maybe Android Studio was being wacky.

Display a download failed notification using Download Manager for Android TV?

I,m trying to build my first app using Android Studio.Its for Android TV. I can't figure out how to notify the user if a download fails.
It's an Android TV app so threes no status bar to display download managers progress in.The code as is displays results from any button click including ones from mainactivity2. However obviously the way I have it it displays the same message when receiving ACTION_DOWNLOAD_COMPLETE regardless of success or failure.
I've tried many methods but most assume I have a better grasp on coding than I do, or had many errors I'm not knowledgeable enough to understand, so I've been unable to incorporate them.
I did manage to get a progress bar to work but with the files being less than a megabyte, and only providing an empty progress bar when download was unsuccessfull, it was less than ideal.
I'm hoping someone can help me display failure or success.
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "Your download is complete.", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onClick(View view) {
registerReceiver(receiver, filter);
int id = view.getId();
if (id == R.id.myfile) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request1 = new DownloadManager.Request(
Uri.parse("https://myurl.zip"));
request1.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/mydir/myfile.zip");
dm.enqueue(request1);
Toast.makeText(MainActivity.this, "Your chose myfile.zip", Toast.LENGTH_SHORT).show();
} else if (id == R.id.myfile2) {
DownloadManager dm;
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request2 = new DownloadManager.Request(
Uri.parse("https://myurl2.zip"));
request2.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/mydir2/myfile2.zip");
dm.enqueue(request2);
Toast.makeText(MainActivity.this, "You chose myfile2.zip.", Toast.LENGTH_SHORT).show();
}
}
}
I thought I should post my resolution to my problem in hopes it may assist someone with a similar situation.
I ultimately abandoned DownloadManager in favor of the fast Android networking library from https://github.com/amitshekhariitbhu/Fast-Android-Networking.
I'm sure there was a way to accomplish my goal with DownloadManager but this worked for me.
Here's an Example of receiving a success or failure toast when downloading a file. Progress status is unused in this example.
#Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.example) {
Toast.makeText(MainActivity.this, "You chose The example.", Toast.LENGTH_SHORT).show();
AndroidNetworking.download("https://example.github.io/repository.0.3.1.zip",Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/example", "/repository.0.3.1.zip")
.setTag("Download")
.setPriority(Priority.MEDIUM)
.build()
.setDownloadProgressListener(new DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long totalBytes) {
}
})
.startDownload(new DownloadListener() {
#Override
public void onDownloadComplete() {
Toast.makeText(MainActivity.this, "The download is complete.", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(ANError error) {
Toast.makeText(MainActivity.this, "The download failed.", Toast.LENGTH_SHORT).show();
}
});

How to directly upload images to server without click button?

Hye.I'm doing apps that comparing two faces between image in ID Card and live capture face image.User capture image of ID card at UploadActivity.Then,front camera at LivenessActivity will be prompted to capture face image.Then UploadActivity will automatically appear along with both images that were captured.User need to click button "verify" and it will show progress bar and upload the images to server to compare them.But,what code I have to put so that it can upload both images to the server without clicking the "verify" button?Perhaps after images appear at UploadActivity,it will directly show progress bar and upload the images to the server .This is my code for your references.Thank you in advance.
UploadActivity:
btnCaptureId.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
captureImage();
}
});
// boolean flag to identify the media type, image or video
final boolean isImage = i.getBooleanExtra("isImage",true);
previewMedia(isImage);
if (fileUri != null )
{
//go to LivenessActivity to caoture image of face
Intent intent = new Intent(this, LivenessActivity.class);
startActivityForResult(intent, 2);
}
btnverify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// uploading the file to server
try {
new UploadFileToServer(Config.IMAGE_DOC, Config.IMAGE_FACE).execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
LivenessActivity:
#Override
public Detector.DetectionType onDetectionSuccess(DetectionFrame validFrame) {
FaceIDDataStruct dataStruct = mDetector.getFaceIDDataStruct();
if (dataStruct != null) {
face = dataStruct.images.get("image_best");
Intent returnIntent = new Intent();
returnIntent.putExtra("image_best",face);
//result go to UploadActivity
setResult(UploadActivity.PAGE_INTO_LIVENESS, returnIntent);
finish();
}
if (face == null) {
face = validFrame.getCroppedFaceImageData();
}
//do something with liveness face
return DetectionType.DONE;
}
button.performClick(); to click programmatically
This is the code that I add to make it automatically upload without click button.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
if (requestCode == 2) {
if (resultCode == PAGE_INTO_LIVENESS) {
Bundle extras = getIntent().getExtras();
byte[] face = extras.getByteArray("image_best");
viewImage();
//automatically upload to server
try {
new UploadFileToServer(Config.IMAGE_DOC, Config.IMAGE_FACE).execute();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
}
}
}
Just Follow the steps
After set/show the image on imageview, start server call to upload it.
show progress dialog until the uploading finished

Using Telegram to send a message

I'm trying to send a message to a telegram-app user, but the intent opens only the telegram app - it don't choose a conctact and send the message:
public void shareTelegram(String message)
{
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
waIntent.setPackage("org.telegram.messenger");
if (waIntent != null)
{
waIntent.putExtra(Intent.EXTRA_TEXT, message);//
startActivity(Intent.createChooser(waIntent, "Daniel"));
}
else
{
Toast.makeText(getApplicationContext(), "Telegram is not installed", Toast.LENGTH_SHORT).show();
}
}
Is there a way to send the message completely?
Can I send the message completely without displaying telegram ?
TLSharp is basic implementation of Telegram API on C#. See it here https://github.com/sochix/TLSharp
Try this.
try {
Toast.makeText(getApplicationContext(), "Sharing Via telegram !", Toast.LENGTH_LONG).show();
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("image/*");
waIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);//Check if package exists or not. If not then code
waIntent.setPackage("org.telegram"); //package check whether telegram is installed
waIntent.putExtra(Intent.EXTRA_TEXT, txt.getText().toString());//place your text here
startActivity(Intent.createChooser(waIntent, "Share with"));
}
catch (PackageManager.NameNotFoundException e)
{
Toast.makeText(SingleItemView.this, "telegram not installed", Toast.LENGTH_SHORT).show();
}

Activity context.this cannot be resolved to a variable (inside Toast)

I'm trying to insert a button to rate app in my activity, with a toast for if market isn't found. But I'm getting a "Context cannot be resolved to a variable" on Activity.this:
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(Activity.this, "Couldn't launch the market", Toast.LENGTH_LONG).show();
}
I've also tried:
Toast.makeText(this, "Couldn't launch the market", Toast.LENGTH_LONG).show();
But then I get Multiple markers at this line
- The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new View.OnClickListener(){}, String, int)
I've made a simple button toast the same way (without try/catch) before, and then it worked fine..
What have I done wrong?
If your class is extending with Activity means use like this
Toast.makeText(ClassName.this, "Couldn't launch the market",Toast.LENGTH_LONG).show();
or
Toast.makeText(getApplicationContext(), "Couldn't launch the market",Toast.LENGTH_LONG).show();
If your Class is extending with Fragment means use like this:
Toast.makeText(getActivity(), "Couldn't launch market",Toast.LENGTH_LONG).show();
Your answer:
Toast.makeText(getApplicationContext(), "Couldn't launch the market", Toast.LENGTH_LONG).show();
Try:
Toast.makeText(getApplicationContext(), "Couldn't launch the market", Toast.LEGTH_LONG).show();
Try this...
Uri uri = Uri.parse("market://details?id="
+ getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't launch the market", Toast.LENGTH_LONG)
.show();
}
});
}
Hope this will help you...

Categories

Resources