SafetyNet.listHarmfulApps() does not run on emulator - android

While I have seen multiple posts and blogs that it doesn't work on the emulator, I've also seen blogs stating that we can do testing on emulators which are equipped with Google Play Services. We have such emulators and I've setup one such emulator ('Play Store enabled emulators)'). Is that the correct assumption? Can I test SafetyNet API integration with such an emulator?
It runs Android 8.1.
My code is as follows (ignore silly mistakes, the code compiles in my laptop. I've just edited some parts to maintain my company's confidentiality).
In this code, the following logs print into my logcat:- About to get harmful apps and Enabled app verification. But no other log statement from this class prints. Does anyone know why?
package some.kindof.package;
import android.content.Context;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNetClient;
import com.google.android.gms.safetynet.SafetyNetStatusCodes;
import com.google.android.gms.safetynet.SafetyNetApi.HarmfulAppsResponse;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.safetynet.HarmfulAppsData;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HarmfulAppsDetector {
private static final Logger LOGGER = LoggerFactory.getLogger(HarmfulAppsDetector.class);
private HarmfulAppsResponseParser parser;
public boolean checkHarmfulApps(final SafetyNetClient safetyNetClient) throws Exception {
try {
LOGGER.info("About to get harmful apps"); //This prints
try {
safetyNetClient.enableVerifyApps();
} catch (Throwable e) {
LOGGER.error("Could not enable app verification");
System.exit(0); //Assume app will exit
}
LOGGER.info("Enabled app verification"); //This prints
//Check that verify apps is enabled
try {
safetyNetClient
.isVerifyAppsEnabled()
.addOnCompleteListener(new OnCompleteListener<SafetyNetApi.VerifyAppsUserResponse>() {
#Override
public void onComplete(Task<SafetyNetApi.VerifyAppsUserResponse> task) {
LOGGER.info("Verified that app verification is enabled or not? See right below:-");
LOGGER.info("See this:- " + task.getResult().isVerifyAppsEnabled());
}
});
} catch (Throwable e) {
LOGGER.error("Error checking whether app verification is enabled", e);
}
//List harmful apps using Google's SafetyNet APIs
safetyNetClient
.listHarmfulApps()
.addOnCompleteListener(new OnCompleteListener<HarmfulAppsResponse>() {
#Override
public void onComplete(Task<HarmfulAppsResponse> harmfulAppsResponseTask) {
LOGGER.info("Task is over.");
if (harmfulAppsResponseTask.isSuccessful()) {
LOGGER.info("Was able to hit Google and get response.");
HarmfulAppsResponse result = harmfulAppsResponseTask.getResult();
LOGGER.info("Response is:- " + result);
boolean harmfulAppsExist = parser.doHarmfulAppsExist(result);
if(harmfulAppsExist) {
//Blah do something here
}
} else {
LOGGER.error("An error occurred. " +
"Call isVerifyAppsEnabled() to ensure " +
"that the user has consented.");
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
LOGGER.error("Task exception", e);
}
});
//Calling listHarmfulApps is now over
return true; //Just for testing, have to parse output and return that when the code actually works
} catch (Throwable e) {
LOGGER.error("Error occurred using Google for verifying harmful apps", e);
throw e;
}
}
}
Why do the async parts of the code, calls to isVerifyAppsEnabled() and listHarmfulApps(), not seem to even execute?

Related

Android App Keep On Crashing In API_Lev 23 [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
I am new to android dev
I have made as simple app in android (for api_version greater than 23) which fetches the name of all running apps. But the app doesn't work properly. When I click the button the functionality registered in "onClickListner" is not working.
package com.sakthi.appban;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayAllApps();
}
});
}
private void displayAllApps(){
PackageManager pm = getPackageManager();
List<ApplicationInfo> installedApplications = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo application : installedApplications){
Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "Task Ended", Toast.LENGTH_SHORT).show();
}
Hope I will get help
Thanks in advance
I think you might have seen these message in logs if you run this code you will get this error when you click on the button
Error:
java.lang.IllegalStateException: You must either set a text or a view
Here application.name may get null for some of the apps. This may cause IllegalStateException because you are passing null to a Toast.
To fix this simply add an if condition to null check like this:
if(application.name != null) {
Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
}
Then it should work.
Update:
You can remove this code from your code which causing ANR:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
The problem is that I am trying to loop in the UI thread.
So the UI thread cannot handle the UI operation..
and my program crashed.More info here

How do I get the status from the Task<Void> returned by ConnectionsClient methods?

I am using the ConnectionsClient API, including startAdvertising(), which returns a Task<Void>. The javadoc for startAdvertising() includes this statement:
Possible result status codes include:
STATUS_OK if advertising started successfully.
STATUS_ALREADY_ADVERTISING if the app is already advertising.
STATUS_OUT_OF_ORDER_API_CALL if the app is currently connected to remote endpoints; call stopAllEndpoints() first.
How do I get these status values after calling startAdvertising()?
I know that the Task API enables me to create an OnSuccessListener and OnFailureListener, but I want to be able to distinguish among different failure cases (specifically, STATUS_ALREADY_ADVERTISING is a benign failure). Because the type is Task<Void>, calling getResult() when it is passed to the onSuccess() method doesn't provide useful information.
All status codes are in ConnectionsStatusCodes class. In startAdvertising method, the third param is a ConnectionLifecycleCallback, you can use it to receives these status codes. For example:
final Activity activity = this;
final ConnectionLifecycleCallback callback = new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(String endpointId, ConnectionInfo connectionInfo) {
}
#Override
public void onConnectionResult(String endpointId, ConnectionResolution resolution) {
int statusCode = resolution.getStatus().getStatusCode();
switch (statusCode) {
case ConnectionsStatusCodes.STATUS_OK:
break;
case ConnectionsStatusCodes.STATUS_ALREADY_ADVERTISING:
break;
case ConnectionsStatusCodes.STATUS_OUT_OF_ORDER_API_CALL:
break;
}
}
#Override
public void onDisconnected(String endpointId) {
}
};
Nearby.getConnectionsClient(activity).startAdvertising("name", "serviceId", callback, new AdvertisingOptions.Builder().build());
Here's a helper method for converting a Task into a status code. This example method is blocking but it would look similar for when asynchronous. The try/catch maps directly to OnSuccessListener/OnFailureListener.
import static com.google.android.gms.common.api.CommonStatusCodes.ERROR;
import static com.google.android.gms.common.api.CommonStatusCodes.SUCCESS;
import android.support.annotation.CheckResult;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.concurrent.ExecutionException;
#CheckResult
public static int waitForTask(String methodName, Task<?> task) {
try {
Tasks.await(task);
return SUCCESS;
} catch (InterruptedException | ExecutionException e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
Exception taskException = task.getException();
if (taskException instanceof ApiException) {
return ((ApiException) taskException).getStatusCode();
}
return ERROR;
}
}

Importing a module into Android Studio

Just starting in Android dev, I would like to use Android Websockets code in my new project in Android Studio.
OS X 10.8.x, AS 0.4.0
I followed: How to import eclipse library project from github to android studio project?
Everything worked great until I tried to actually code. I pasted in (from the example):
List<BasicNameValuePair> extraHeaders = Arrays.asList(
new BasicNameValuePair("Cookie", "session=abcd")
);
WebSocketClient client = new WebSocketClient(URI.create("wss://irccloud.com"), new WebSocketClient.Listener() {
#Override
public void onConnect() {
Log.d(TAG, "Connected!");
}
#Override
public void onMessage(String message) {
Log.d(TAG, String.format("Got string message! %s", message));
}
#Override
public void onMessage(byte[] data) {
Log.d(TAG, String.format("Got binary message! %s", toHexString(data)));
}
#Override
public void onDisconnect(int code, String reason) {
Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
}
#Override
public void onError(Exception error) {
Log.e(TAG, "Error!", error);
}
}, extraHeaders);
client.connect();
// Later…
client.send("hello!");
client.send(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF });
client.disconnect();
When I build/run the project, I get:
error: cannot find symbol class WebSocketClient
I think my question is: What is the import statement I should use?
How would I go about adding/using this code?
You ran into a bug that was fixed in Android Studio 0.4.3. I recommend you upgrade.
The auto importer was broken. Once I restarted Android Studio it showed I should put:
import com.codebutler.android_websockets.WebSocketClient;
As my import. Now I have a NullPointerException for a particular piece of code, but that's a different problem.

Can not use MediaRecorder on Android Emulator. Is the storage location wrong?

I'm trying to record sound using Android Emulator. I know that this question is popular over the internet, I checked many posts, it seems that only one person succeded: Can the Android emulator record and play back audio using pc hardware?. (it think he used
File fTmFile; insteadof String fTmpFile;
which i also tried). And following Philip's advice and the official site tutorial http://developer.android.com/guide/topics/media/audio-capture.html and also other resources, I'm still not able to record. My application throws exception at line:
fMediaRecorder.prepare();
more exactley, this is what I first get:
W/System.err(1042): java.io.FileNotFoundException: /mnt/sdcard/audiorecordtest.3gp (Permission denied)
which makes me think is something wrong with the storage location, because even I added 'SD Card Support' property for the emulator with size 256 MiB, I'm not able to acces it, furthermore I can see in the emulator the message: "Your phone does not have a SD Card inserted" when I go to Music.
I added both audio record and external storage permissions, in AndroidManifest.xml and both audio (record+playback) hardware settings to the emulator 2.3.3 on Win 7. Is anything wrong within my app, the way I storage the file or something else? Please, if anybody has any idea feel free to share, it will be appreciated.
Here is the full source code:
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class RecordSoundActivity extends Activity {
private MediaRecorder fMediaRecorder = null;
private Button btnrecord;
private Button btnstop;
String fTmpFile;
public RecordSoundActivity() {
fTmpFile = Environment.getExternalStorageDirectory().getPath();
fTmpFile += "/audiorecordtest.3gp";
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnrecord = (Button) findViewById(R.id.button1);
btnstop = (Button) findViewById(R.id.button2);
btnrecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(RecordSoundActivity.this, "Recording...", Toast.LENGTH_LONG).show();
Recording();
}
});
btnstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fMediaRecorder.stop();
fMediaRecorder.release();
}
});
}
public void Recording() {
fMediaRecorder = new MediaRecorder();
fMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
fMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
fMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
fMediaRecorder.setAudioChannels(1);
fMediaRecorder.setAudioSamplingRate(8000);
fMediaRecorder.setOutputFile(fTmpFile);
try {
fMediaRecorder.prepare();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
fMediaRecorder.start();
} catch (IllegalStateException e) {
// TODO: handle exception
e.printStackTrace();
}
//fMediaRecorder.stop();
//fMediaRecorder.release();
}
}
Try and see if it works for Android 4.0. I know I had some issues with the camera in the emulator, in lower version (Lower than 4.0) it just wouldn't recognize my laptop webcam. But when I tried it on 4.0, when the AVD was loading a popup message came and asked me if I want to connect the webcam to the AVD, and once I agreed it worked.
Another poster in SO asked this question too, about the camera, and changing the AVD version to 4.0 did help him.
Maybe its the same for audio recording too, as both are external hardware for the typical PC.

Activity terminating abruptly without any exception

I have an Activity that sometimes terminates abruptly but without any exception being reported or logged. The Activity just ends suddenly and the app returns to the previous Activity in the stack.
I'm using ACRA (http://code.google.com/p/acra/) to capture and report errors, and it works well for all other errors in the app, but in this one case it does not detect any exception having been thrown. Nor is anything reported in Logcat.
It always happens at the same "place" in the app, when the user takes a certain action, but it is very intermittent and I've yet to make it happen while attached with the debugger.
Are there any other options (besides ACRA and Logcat) for determining what is happening to the Activity? Or is this something in the world of Android Activities that is "known?"
If it matters, this Activity is doing Bitmap manipulation and saving; I've had to take steps to avoid potential out of memory errors; but I was getting ACRA reports of OOM exceptions when they did occur, so I don't think this is due to OOME.
At the point where it seems to fail, the Activity creates an AsyncTask and executes it. Here's the code for the AsyncTask (ActivityAsyncTask is a really simple super class; EditPhotoEctivity is the one that is dying without an exception, sometime during the creation or execution of this task):
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.view.View;
public class CompositeAndSavePictureTask extends ActivityAsyncTask<File, Void, Uri>
implements MediaScannerConnectionClient {
public static final String FILE_EXTENSION = ".jpg";
private static final int COMPRESSION_QUALITY = 100;
private File file;
private Uri mSavedImageUri;
private MediaScannerConnection mMediaScannerConnection;
public CompositeAndSavePictureTask(EditPhotoActivity owningActivity) {
super(owningActivity);
mMediaScannerConnection = new MediaScannerConnection(owningActivity, this);
}
#Override
protected EditPhotoActivity getOwner() {
return (EditPhotoActivity) super.getOwner();
}
#Override
protected void onPreExecute() {
getOwner().toggleControlsVisibility(false);
}
#Override
protected Uri doInBackground(File... params) {
file = params[0];
Bitmap picture = null;
View mainContentView = getMainContentView();
try {
picture = captureBitmap(mainContentView);
saveBitmap(picture);
} catch (Exception ex) {
LogUtils.logError(this, "Could not save photo", ex);
setError(ex);
return null;
} finally {
cleanUpCapture(mainContentView, picture);
}
try {
mMediaScannerConnection.connect();
synchronized (mMediaScannerConnection) {
mMediaScannerConnection.wait();
}
} catch (InterruptedException ex) {
LogUtils.logInfo(this, "MediaScannerConnection was interrupted during scan.");
setError(ex);
}
return mSavedImageUri;
}
protected Bitmap captureBitmap(View mainContentView) throws Exception {
mainContentView.setDrawingCacheEnabled(true);
return mainContentView.getDrawingCache();
}
protected void cleanUpCapture(View mainContentView, Bitmap capturedBitmap) {
mainContentView.setDrawingCacheEnabled(false);
if (capturedBitmap != null) {
capturedBitmap.recycle();
}
}
protected void saveBitmap(Bitmap bitmap) throws IOException {
BufferedOutputStream outStream = null;
try {
outStream = new BufferedOutputStream(FileUtils.openOutputStream(file));
bitmap.compress(CompressFormat.JPEG, COMPRESSION_QUALITY, outStream);
} finally {
try {
if (outStream != null) {
outStream.close();
}
} catch (IOException ex) {
LogUtils.logError(this, "Could not close output stream", ex);
}
}
}
#Override
protected void onPostExecute(Uri savedFileURI) {
getOwner().toggleControlsVisibility(true);
getOwner().onSaveResult(savedFileURI);
}
public void onMediaScannerConnected() {
mMediaScannerConnection.scanFile(file.getPath(), null /* mimeType */);
}
public void onScanCompleted(String path, Uri uri) {
mMediaScannerConnection.disconnect();
mSavedImageUri = uri;
synchronized (mMediaScannerConnection) {
mMediaScannerConnection.notify();
}
}
}
See also view.getDrawingCache() only works once, which has some relation but is a slightly different scenario.
Any and all ideas are welcomed.
I had a similar problem before. I was trying to open a file for reading, but instead of typing the complete address which was "/sdcard/something.txt", I gave it the wrong path (just "something.txt") without the sdcard part. After a lot of pain I have discovered that if you want the program to open something that is not really there, the activity just ends whitout any notice (to to console, to logcat etc. ). As it won't send back an error, it won't go on the "catch" branch.
So, I would suggest checking the file opperations.
Disclaimer: I know for sure that this causes this kind of behavior when trying to open the wrong path using the ndk and native code, but I suppose it would be the same if you do this mistake from in java code.
Please forgive the newbie comment, but if it's terminating without a Exception, you may be catching it somewhere and the program is continuing on it's merry way, but in an invalid state.

Categories

Resources