steveliles / foredroid Goto Github PK
View Code? Open in Web Editor NEWUtility for detecting and notifying when your Android app goes background / becomes foreground
License: Other
Utility for detecting and notifying when your Android app goes background / becomes foreground
License: Other
the old code when it going to "it.remove();",there is a exception ,"java.lang.UnsupportedOperationException" .
The CopyOnWriteArrayList doc describe is “Iterators returned by this list and its sub lists cannot modify the
This is my solution:
private List<WeakReference> listeners = new ArrayList<>();
Please check this issues ,thank you very much for offering so good tool.
When closing an interstital ad from admob the Foreground instance became background instead foreground.
It resolves changing the call onActivityResumed to:
@OverRide
public void onActivityResumed(Activity activity) {
current = activity;
}
Best regards and good job!
Alex.
Do you plan to add a license to your repo? Is it free for all? Non-commercial? What do you think of Apache 2?
public class ApplicationListener implements Application.ActivityLifecycleCallbacks {
private int foregroundCount = 0;
@Override
public void onActivityStarted(Activity activity) {
if (foregroundCount <= 0) {
// TODO becomes foreground
}
foregroundCount++;
}
@Override
public void onActivityStopped(Activity activity) {
foregroundCount--;
if (foregroundCount <= 0) {
// TODO goes background
}
}
/*
* The following callbacks, we do not need
*/
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
That is.
If ActivityA go to ActivityB,the callbacks is :
A.onPause()
B.onStart()
B.onResume()
A.onStop()
If ActivityB return ActivityA, the callbacks is:
B.onPause()
A.onStart()
A.onResume()
B.onStop()
So, set a counter to statistics onStart() and onStop() callbacks. if the counter is > 0, Application is in foreground, opposite in background.
When I request permission, App became Background.
package com.sjl.foreground.demo;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.sjl.foreground.Foreground;
import java.util.ArrayList;
import java.util.List;
public abstract class DemoActivity extends ActionBarActivity implements Foreground.Listener {
private Foreground.Binding listenerBinding;
protected abstract void startAnotherActivity();
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startAnotherActivity();
//composeEmail(new String[]{"asdasd"},"asdas");
ActivityCompat.requestPermissions(DemoActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
}
});
listenerBinding = Foreground.get(getApplication()).addListener(this);
}
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
private boolean checkAndRequestPermissions() {
int permissionSendMessage = ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
// not strictly necessary as Foreground only holds a weak reference
// to the listener to defensively prevent leaks, but its always better
// to be explicit and WR's play monkey with the Garbage Collector
listenerBinding.unbind();
}
@Override
public void onBecameForeground() {
Log.d(Foreground.TAG, getClass().getName() + " became foreground");
}
@Override
public void onBecameBackground() {
Log.d(Foreground.TAG, getClass().getName() + " went background");
}
}
Looks like the delayed check in onActivityPaused() is the reason.
Foreground thinks it is the background, altough it is in the foreground.
Thus onBecameForeground() gets called when the started activity has finshed.
Only happens if I put the app in the background two times or more.
the onBecameForeground calls multiple times if you have more than one activity on stack, so if you have three activities on stack, the onBecameForeground calls thrice. how to fix that.
I tried to use the gradle dependency as:
compile 'com.sjl:Foredroid:1.0.1'
This package doesn't exist in jcenter or maven-central.
Per this page:
https://bintray.com/steveliles/maven/Foredroid/1.0.1?versionPath=%2Fsteveliles%2Fmaven%2FForedroid%2F1.0.1
The package that is available is: compile 'Foredroid:Foredroid:unspecified'
Can you publish 1.0.2 version that fixes these problems? Thanks.
everything works fine until you open a dialog, when the dialog is showing the status of activity change to "background" , when the dialog is closed don't update the status . . .
In the weak references to call backs, when iterating over the CopyOnWriteArrayList and the weak reference is pointing to a null, remove() is called on the iterator, which is not allowed and throws an illegal operation exception, which is buried and the item is never removed. Removal has to happen after iteration is complete.
I would like to have a callback when app is destroyed. Is it possible?
Implemented same as in sample app.
onBecameForeground called
onBecameBackground never called.
At the time of going background listeners becomes empty (due to weak reference) and thus hasn't been called
@steveliles Can you add a license to your project please?
Hi @steveliles,
thank you for this helpful class. But i get the error:
"Cannot resolve method: removeListener(com.sjl.foreground.Foreground.Listener)"
Can fix this please?
Thank you
Hi there.
I got a memory leak ( from Canary Leak ) coming from Foreground.current
I'm only doing this Foreground.get(application).addListener(foregroundListener)
in onCreate and unbinding in onDestroy.
Any ideas?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.