I'm dealing with a random problem which related to camera usage. Before I call camera intent - I generate UUID to store file with this name. I store this UUID in private variable like so:
private String requestedFileName;
When camera done - I'm processing this file, looks something like this:
public void onPictureTaken(int index)
{
//First of all - remember picture in database for reference.
FileData.InsertFile(mContext, UUID.fromString(requestedFileName));
//Reduce taken picture if needed, otherwise let it be original.
if (Preferences.getImageSize(mContext) > 0)
{
Imaging.scaleImageFile(mContext, requestedFileName, Preferences.getImageSize(mContext));
}
I see users report issue exception that boils down to requestedFileName == null when onPictureTaken called
Caused by: java.lang.NullPointerException
at java.util.UUID.fromString(UUID.java:210)
at com.idatt.views.FourImagesView.onPictureTaken(FourImagesView.java:151)
at com.idatt.views.TrailerUnitView.onPictureTaken(TrailerUnitView.java:233)
Everything works good on my phone (Nexus S) and in emulator. But users report this exception and I'm not sure why this is happening..
I've seen this happen on the Nexus phones, and some others. If you use DDMS to watch what is going on, I bet you'll see that your process is actually being terminated and then restarted. Thus your local state is being lost. You need to persist it, since Android can basically kill your process and restart it whenever it wants if you switch to a new task (and most of the camera capture intents set the NEWTASK flag).
If your class is an Activity you can use onSaveInstanceState() to store your filename, then read it back out of the Bundle you get in onCreate().
If you are not an Activity you can use the SharedPreferences store as a temporary place to save the filename:
private static void saveTempFileName(Context context, String filename) {
SharedPreferences settings = context.getSharedPreferences("whatever", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("com.yourstuff.whatever", filename);
editor.commit();
}
As #jeffamaphone noted you are probably having issues with app configuration changes. Application configuration change happens when something happens that affects the runtime environment of your app. Most notably this are: orientation change or keyboard hide/show.
Try this: start your app, invoke the Camera app (via your app action), change orientation, return to your app (via appropriate action). Does this sequence produce the error? Then you have issues with configuration change - when orientation changes usually (depending on your app settings) Android system restarts (kills and creates new instance) your Activity, which probably creates all new Views (without UUID set).
See handling configuration changes.
Related
On our application there's a service that is normally started during Application.OnCreate (directly calling context.startService) and also later on via AlarmManager (refactor is in progress to migrate some of its work to JobScheduler).
Our application also have a BroadcastReceiver that gets launched with its direct intent.
Given the new limitations in Android Oreo (https://developer.android.com/about/versions/oreo/android-8.0-changes.html) we're having an issue as follows:
app/process is in background/dead
BroadcastReceiver gets fired by the OS
Application.onCreate() executes before the BroadcastReceiver
Application.onCreate() code tries to run the Service
this leads to crash with "IllegalStateException: Not allowed to start service Intent".
I'm aware of the new recommended ways of launching a Service as answered by CommonsWare here https://stackoverflow.com/a/44505719/906362, but for this specific case, I simply want to have if(process in foreground) { startService }. I'm currently using the following method and it seems to work:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean isProcessInForeground_V21(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = am.getAppTasks();
return tasks.size() > 0;
}
But I can't find the exact checks Android Oreo is doing (I got as far as here https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/ContextImpl.java on the startServiceCommon method, but from there requireForeground flag seems to go to some native implementation)
So my question:
For the specific purpose of Android Oreo new limitations, how to check if my process is foreground before calling startService?
To continue your investigation: (TL;DR: see between horizontal lines at the bottom)
Disclaimer, I don't know too much about Android, I just like digging in the source code.
Note: you can also navigate the code in Android Studio if you jump to file instead of class:
or searching for text in Project and Libraries.
IActivityManager is defined by AIDL, that's why there are no sources for it:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/app/IActivityManager.aidl#145
Based on how AIDL needs to be implemented I found that ActivityManagerService extends IActivityManager.Stub (God bless Google indexing).
Note I also found this, which might be an interesting read if you're really interested how things work internally.
https://programmer.group/android-9.0-source-app-startup-process.html
ActivityManagerService sources reveal that in Oreo startService is forwarded to ActiveServices which is located in the same package.
Assuming we're looking for an exception like this:
java.lang.IllegalStateException: Not allowed to start service Intent {...}: app is in background uid UidRecord{af72e61 u0a229 CAC bg:+3m52s273ms idle procs:1 seq(0,0,0)}
we have to continue down the rabbit hole: requireForeground gets assigned to fgRequired parameter and the message is here. The condition to allow this depends on the start mode returned by ActivityManagerService.getAppStartModeLocked(packageTargetSdk = 26 or greater, disabledOnly = false, forcedStandby = false).
There are 4 start modes:
APP_START_MODE_NORMAL (needs to be different than this, i.e. !=)
APP_START_MODE_DELAYED (this is ok, i.e. return null)
APP_START_MODE_DELAYED_RIGID
APP_START_MODE_DISABLED
Ephemeral apps will immediately return APP_START_MODE_DISABLED, but assuming this is a normal app, we end up in appServicesRestrictedInBackgroundLocked.
Note: this is where some of the whitelist mentioned in https://stackoverflow.com/a/46445436/253468 is decided.
Since all branches but last return APP_START_MODE_NORMAL, this redirects to appRestrictedInBackgroundLocked where we find our most likely suspect:
int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
// Apps that target O+ are always subject to background check
if (packageTargetSdk >= Build.VERSION_CODES.O) {
return ActivityManager.APP_START_MODE_DELAYED_RIGID;
}
So the reason for denial is simply targeting O. I think the final answer to your question of how the OS decides if your app is foreground or background is this condition in getAppStartModeLocked
UidRecord uidRec = mActiveUids.get(uid);
if (uidRec == null || alwaysRestrict || uidRec.idle) {
My guess is that a missing record means it's not running (but then how is it starting a service?!), and idle means it's backgrounded. Notice that in my exception message the UidRecord is saying that it's idle and has been backgrounded for 3m52s.
I peeked into your getAppTasks and it's based on TaskRecord.effectiveUid, so I'm guessing that's quite close to listing UidRecords for your app.
Not sure if this helps, but I'll post it anyway, so if anyone wants to investigate more, they have more info.
I'm writing a simple app to send public photos from Dropbox public folder to Chromecast.
Instead of CastCompanion library I decided to write my own stuff to understand better the API.
According to Google Guidelines:
if the sender application becomes disconnected from the media route, such as when the user or the operating system kills the application without the user first disconnecting from the Cast device, then the application must restore the session with the receiver when the sender application starts again.
It seems to me that the same solution should apply to Activity recreation upon orientation change since it recreates the Activity from scratch.
My first question: Is my assumption correct? Both scenarios, orientation change and system kill, may use the same solution?
Given this assumption I wrote some code to restore session upon Activity restoration.
I'm considering the orientation change scenario, when Activity is recreated from scratch and I am supposed to restore route Id, Session Id and try to reconnect (I'm storing and retrieving both values from shared preferences).
I've been testing with and it's working fine.
That's what I do (based on Google Sender Guidelines code):
After discovering the ongoing Route Id and find the cast device I call this method:
private void connectToDevice(CastDevice castDevice) {
Log.d(TAG, "connecting to " + castDevice);
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
.builder(castDevice, new CastListener());
Log.d(TAG, "apiClient is null ? " + (apiClient == null));
apiClient = new GoogleApiClient.Builder(this)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Log.d(TAG, "apiClient connected? " + apiClient.isConnected());
Log.d(TAG, "apiClient connecting? " + apiClient.isConnecting());
apiClient.connect();
}
private class CastListener extends Cast.Listener {
#Override
public void onApplicationStatusChanged() {
if (apiClient != null) {
Log.d(TAG, "callback => " + this);
}
}
#Override
public void onVolumeChanged() {
}
#Override
public void onApplicationDisconnected(int errorCode) {
teardown();
}
}
After this method I call Cast.CastApi.joinApplication if I recognize a reconnection.
But once reconnected to Chromecast the log of onApplicationStatusChanged prints one different instance for every phone's rotation. E.g: if I rotate phone 3 times the log prints 3 times with 3 different pointer addresses. That makes me believe it is internally holding all callbacks instances.
How am I supposed to handle this situation since the Activity is being recreated and I need to create another instance of GoogleApiClient keeping the session?
Full source:
https://github.com/ivan-aguirre/chromecast_samples/blob/master/DropboxCast/app/src/main/java/com/dropboxcast/dropboxcast/MainActivity.java
IMHO, I believe the proper way (or at least a better way) to approach this is one of the following:
if you have only one activity and that is all you care about, then use a fragment that persists across configuration changes and put the stuff that you want to persist seamlessly, there. This way, rotation of the phone is not going to cause any disruption in your cast related stuff.
if you have more than a single activity, think about creating an object that lasts across all your activities and put the cast stuff there and then ask that object for the instance of CastApi whenever needed, etc.
In your case, do you really get disconnected when you rotate the phone? Since you are setting up a whole new connection, you might want to disconnect yourself first when configuration changes (assuming you don't want to go with my earlier proposed (1) or (2)).
I want to check if my app is running on a background mode.
The problem is that i have many activities(list activities, map activities etc.). Initially I have tried in the life cycle's resume and pause(or the onUserLeaveHint) methods to set a static boolean as true or false and work with this way. But this obviously can't work because when I move from one activity to another, the previous one get paused.
Also, I've read here on stackoverflow that the getRunningTasks() should be used only for debugging purposes. I did a huge research but I can't find a solution. All I want to do is to be able to detect if a the app is running on a background. Can anyone propose me a way, or express any thought on how can I do that?
You can try the same mechanism (a boolean attribute) but on application side rather than activity side. Create a class which extends Application, declare it in the manifest file under <application android:name=YourClassApp>.
EDIT: I assume you know that activities aren't intended for background processing, if not you should take a look at the Services.
I don't know if this will help but you can use
getApplicaton().registerActivityLifecycleCallbacks(yourClass);
To get a birds eye view of how your activities are displayed in the FG. (For older s/w you can use this)
If your Application has a Service you could have a static get/set which accesses a static variable. Do not do this in Activities though, it causes mem leaks.
But realistically speaking there is no tidy way of tracking if your application is running or not.
I had the same problemen when overwriting the Firebase push messaging default behavior (show notifications only when in the background) I checked how Firebase did this by looking in the .class file com.google.firebase.messaging.zzb:53 (firebase-messaging:19.0.1) which appears to us getRunningAppProcesses. Mind you FireBase is created by Google them self. So I'm assuming it's pretty save to use. Cleaned up version:
List<ActivityManager.RunningAppProcessInfo> runningApps;
boolean isInForeground =false;
if ((runningApps = ((ActivityManager)this.getApplication().getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses()) != null) {
Iterator runningApp = runningApps.iterator();
int myPid = Process.myPid();
while(runningApp.hasNext()) {
ActivityManager.RunningAppProcessInfo processInfo;
if ((processInfo = (ActivityManager.RunningAppProcessInfo)runningApp.next()).pid == myPid) {
isInForeground = processInfo.importance == 100;
break;
}
}
}
My code listens to the DCIM folder, using a FileObserver.
All Android versions I used, except 4.1.1, sent only 1 event - when the video was finished taken.
I think it's the correct behavior - write continually and close when finished.
In 4.1.1 (Galaxy Nexus and Nexus S) though, the event FileObserver.CLOSE_WRITE is sent
twice - when the video starts and when it ends.
Also the same for photos - the event is sent twice - though it's not that critical.
The problem is that I can't distinguish between the start event and end event of a video.
I could try and check the size of the file, but because the event may have been delayed (slow/busy device), the size may be quite big.
Any idea why was the behavior changed? Do you know where is the camera's app source code? I can try and look at the history to understand that.
As I wrote in one of my comments, the difference between 4.1 and previous Android versions is that in 4.1.1, the file is written and closed twice. Once when an empty video file is created. Then the video is written into a tmp file. Then the rename/copy of the tmp file is the second write_close event.
In previous versions there's not tmp file - only the original - thus only one close_write event.
Please comment if you think it's a bug. I'm not sure.
I have myself an app which monitors the DCIM/Camera directory through a FileObserver. What I noticed, and could be of help to you, is that the first operation is a CLOSE_WRITE, however the final operation is a MOVED_TO from the .tmp to the real file, which means you can recognize when the video is (really) ready.
My real code is more complex due to the requirements of my app, but the general idea is something like this:
/* My FileObserver implementation field */
private HashSet<String> jbCache = new HashSet(...)
...
protected void onEvent(int event, String path) {
boolean isJellyBean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLYBEAN;
if ((event & FileObserver.CLOSE_WRITE) > 0) {
if (isJellyBean) {
jbCache.add(path);
} else {
performYourWork(path);
}
} else if ((event & FileObserver.MOVED_TO) > 0 && isJellyBean && jbCache.contains(path)) {
performYourWork(path);
jbCache.remove(path);
}
}
You have to listen to both CLOSE_WRITE and MOVED_TO when you register the events you want to catch, obviously.
Although I starred your bug, I doubt Google will ever acknowledge it, as it looks like there could be some (disagreeable) reasoning behind the change. The Camera app is mostly a no-standard crap anyway (e.g.: fake DCIM standard compliance)
My requirement is, First time application is installed in the Android phone, Need to get the licence code from particular shop/organization. I have created generation key using phone model number.nOW THE PROBLEM IS If its first only need to show license screen otherwise go to first screen. How we can identify the particular app is installed already or not . / from the registry ? In here registry is available.
I couldn't explore my very deeply or clearly. Sorry for that.
Please help me.
Thanks in advance...
You could always set a bool value in the android.content.SharedPreferences, then in the first oncreate() check to see whether that bool value is false.
If it is push the license screen intent and perform a check for application, if its there update the preference to true. So on next start it will skip over it, where you can load your main screen.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
boolean enteredDetails = settings.getBoolean("FirstTime", false);
if(enteredDetails){
setContentView(R.layout.main); //loads the main screen
}
else{
startActivityForResult(new Intent(this, License.class), GET_DETAILS);
}
}
You can simply use Context.openFileInput() / Context.openFileOutput() to store a piece of information that will tell your app whether the license screen was already shown. This way you can use something like this in your main Activity's onCreate():
if (nothingWrittenInAFileCalled(FILE_NAME)) { // using Context.openFileInput()
showLicense();
writeAFileCalled(FILE_NAME); // using Context.openFileOutput()
}
If this is not satisfactory, this is also something you can check on license server side. If you send the license server a hash of the IMEI, as an example, your license server will be able to determine whether the app was already installed or not. In that case, prefer a non reversible hash: this is to avoid sending/storing the IMEI as one can see this piece of information as private data.