Background service for android oreo - java

How to continue background service in android Oreo without showing notification dot? i continues my background service using notification but i don't want to show notification for running service.

If you would have read the Android Oreo 8.0 Documentation properly somewhere in here, you might not have posted this question here.
Step 1: Make sure you start a service as a foreground Service as given in below code
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), GpsServices.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BluetoothService.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BackgroundApiService.class));
Step 2: Use notification to show that your service is running. Add below line of code in onCreate method of Service.
#Override
public void onCreate() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, notification);
}
...
}
Step 3: Remove the notification when the service is stopped or destroyed.
#Override
public void onDestroy() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true); //true will remove notification
}
...
}
One problem with this solution is that it will keep showing the notification until your Service is running on all devices running on Android Oreo 8.0.
I'm sure that this solution will work even when the app is in the background or in kill state.
IMPORTANT NOTE: SHOWING A NOTIFICATION FOR RUNNING A SERVICE IN BACKGROUND (APP IN BACKGROUND OR KILLED STATE) IS MANDATORY IN ANDROID OREO 8.0. YOU CANNOT RUN AWAY WITH IT. SO IT IS RECOMMENDED THAT YOU MAKE NECESSARY CHANGES IN YOUR APP TO MAKE IT WORK PROPERLY AS PER THE BEST PRACTICES FOLLOWED OR ASKED BY ANDROID.
I hope this might help to solve your problem.

This isn't possible in this API version (26) and higher. Android OS automatically close your service if you run it without showing a notification to the user.
If you are targeting API >= 26 the system will impose a restriction on your service to run in background unless your activity in foreground. As soon as your activity goes to background, the service will be terminates when system finds it running in background (See Background service limitations).
By using startForegroundService() method you grant that permission to run the service in background even when the activity isn't running.
Must also once the service has been created, the service must call its startForeground() method within five seconds.

This code worked for me. First you make sure :
1- Define the service in Manifest
2- Define the permission in Manifest
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3- Make sure you have started the service before.
Your service should have a notification. You should be careful that
your notification must have a ChannelID !
this page can help you:
How to create a Custom Notification Layout in android?
Android how to show notification on screen
Now paste the following code into your service
#Override
public void onCreate() {
super.onCreate();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(" your Notification ID ", notification);
}
} catch (Exception e) {
Log.e(" Error --->> ", e.getMessage());
}
}
after that add this code:
#Override
public ComponentName startForegroundService(Intent service) {
return super.startForegroundService(service);
}
and this:
#Override
public void onDestroy() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
}
}

Related

StartActivity method from background

The problem seems to be known, but I could not find the right solution.
I will describe the scenario:
There is an application making requests to the API. In some FirstActivity, a request is made to the API, upon positive result of which startActivity () is called in SecondActivity. The problem is that if, while sending the request, the application is minimized to the background (that is, startActivity () will be called in the background), then:
If android version> = 29 then startActivity () basically won't work. The one following startActivity () finish () will work and upon restarting the application will restart (which is logical)
If the android version is < 29, then startActivity () will fire and bring this SecondActivity to the foreground.
Based on this, the question is. How can I force the application, regardless of version, to transition between activities and not bring them to the front?
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
finish();
As per documentation
Android 10 (API level 29) and higher place restrictions on when apps
can start activities when the app is running in the background.
Workaround : In specific situations, your app might need to get the user's attention urgently, such as an ongoing alarm or incoming call. You might have previously configured your app for this purpose by launching an activity while your app was in the background.
To provide similar behavior on a device running Android 10 (API level 29) or higher, complete the steps described in this guide.
you can show a high-priority notification with a full-screen intent.
More Details
Updated answer for new requirement: For your comment
(Well, please tell me how to make startActivity () in the background start the activity also in the background, and not raise the application from the background)
you can add a LifecycleObserver that will be notified when the LifecycleOwner changes state.
Inside your activity api response callback use the following condition
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
// Activity is in resumed state, Open new activity immediately
} else {
// else add a LifecycleObserver that will be notified when the LifecycleOwner changes state
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
// remove observer immediately so that it will not get triggered all the time
lifecycle.removeObserver(this)
// Activity is in start state again, Open new activity here
}
})
}

How to restart app and clear all data with Button [duplicate]

My current Android Application needs to call
ActivityManager.clearApplicationUserData()
to simulate the user clearing App storage
Which works fine.
A side effect of calling clearApplicationUserData() is that the App is (understandably) closed.
Which gives a poor user experience.
I am having difficulty in restarting my Application once I have called clearApplicationUserData().
I have tried using startActivity, Alarm Manager with Pending Intent, Foreground/Background service.
Nothing works.
Is it impossible to restart an Android App having called clearApplicationUserData()?
(1st answer: this answer only works on limited situations. it's not a complete answer)
public boolean clearApplicationUserData ()
Description
Return: true if the application successfully requested that the application's data be erased; false otherwise.
As the reference website stated, we have a returnee before the application is being closed. so, we are going to use this returnee in order to restart the app.
if(ActivityManager.clearApplicationUserData)
{
doRestart = true;
}
when Activity onDestroy() and onStop() are called restart app.
#Override
protected void onDestroy() {
super.onDestroy();
if(doRestart){
Intent intent = new Intent(this, Activity.class);
this.startActivity(intent);
}
}
#Override
protected void onStop() {
super.onStop();
if(doRestart){
Intent intent = new Intent(this, Activity.class);
this.startActivity(intent);
}
}
We put restart action in both onDestroy() and onStop() in order to make sure the app will be restarted again.
And also, I think it's a good idea to force stop activity before OS stops it.
if(ActivityManager.clearApplicationUserData)
{
doRestart = true;
finish(); <= i mean this
}
it's because it makes sure that onDestroy() and onStop() will be invoked.
My suggestion might sound trivial but, have you consider not calling ActivityManager.clearApplicationUserData()?
Here what the docs says about this method:
Permits an application to erase its own data from disk. This is
equivalent to the user choosing to clear the app's data from within
the device settings UI. It erases all dynamic data associated with the
app -- its private data and data in its private area on external
storage -- but does not remove the installed application itself, nor
any OBB files.
So in order to mimic this behavior you just need to clear you internal and external storage directories. No permissions are needed to access any of those.
(2nd answer: I need much more contribution on it)
After 8 hours of researching in Android OS and Android Developers Website in order to find a solution to restart activity when clearApplicationUserData is invoked. Finally, I would be able to find a nice/hacking solution.
This solution looks like Zidane dribble :)
Let's introduce the solution. at first, clearApplicationUserData clears all the clues of the application when is invoked like tasks, notifications, alarms and etc. therefore, explicit Activity calling is impossible.
implicit way is the only possible way of calling activity.
After a couple of tests I found that application manifest registered intent-filters wouldn't be removed and they are able to listen for incoming system broadcasts.
Approximately, 98% of system broadcasts wouldn't be received by cleared application and that 2% remained might not be broadcasted very soon.
so what to do? hmmm? come on man I must find a solution ...
bingo, ** I must trigger something in order to system broadcast it** <= looks hacking :)
so I decide to choose WIFI_STATE_CHANGED because
Easy Access permission
System Broadcasts it on delay <= this makes sure that the app is closed
before broadcast
manifest.xml
<receiver
android:name=".PackageDataClearedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="100">
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ActivityManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatButton btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
#Override
public void run() {
am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
if (am != null) {
ExecutorService pool = Executors.newFixedThreadPool(2);
final Collection<Future> futures = new HashSet<Future>();
futures.add(pool.submit(new Runnable() {
#Override
public void run() {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
am.clearApplicationUserData();
}
}));
for (Future future : futures) {
future.isDone();
}
}
}
}).start();
}
});
}
}
demo
keep in mind, it's just A minimum viable product that needs to be developed more in order to make it work perfectly.
Clearing the app data on the device through the API clearApplicationUserData() resets the app as if it were just installed. As you have found, any alarms and broadcasts registered with your app are also cleared. The most efficient way to keep your app in the foreground would be to clear the data yourself, as others have pointed out, rather than using the API. Here is an example: https://stackoverflow.com/a/9073473/949224
However, if you are determined to use the API (which does guarantee all data is cleared) and the app is force-stopped, I have a suggestion:
Create a small companion app that can be launched just prior to you clearing your app data. The companion app simply re-launches your app, possibly after a short time-out.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("example.com.testrelaunchapp");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} else {
Log.w( TAG, "Unable to resolve launch activity of relauncher companion app");
}
((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE))
.clearApplicationUserData();
The companion app itself needs to close afterwards, and ideally should be hidden from the Activity Stack etc..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent launchIntent = getPackageManager().getLaunchIntentForPackage("example.com.yourmainapp");
if (launchIntent != null) {
Handler handler = new Handler(getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.i( TAG, "About to act on launchIntent");
launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(launchIntent);
finish();
System.exit(0);
}
}, 1000);
}
}
I have seen this work with Android 6.0, but no guarantees it would be versatile and work across the board. There would be more to do to make the companion app UI-less if desired and to be hidden from the phone's launcher. You would also probably want to bundle the APK as a file within your own app and install it upon first run, which would need the user to enable installation from "Unknown sources" (non-Play store). It can be done through intents to the right System settings, if needed, but users would need a good explanation why this is needed.
So, as I was saying, the simpler approach is to clear the data and app permissions yourself.

Background Service for update location in background

it kills background service, to solve your issue you should use foreground service.
my background sticky service is kill on oreo and heigher devices any solution for getting location on background service when Activity is on backound
It's because of Android Oreo behaviour changes for background execution. Suggested alternatives are
1) Foreground service.
Use this if you are ok displaying notification to the user when you are trying to retrieve the location using Location API. This would be reliable and is suggested in the documentation.
Sample app from the documentation :
LocationUpdatesForegroundService project on GitHub
An example of an app that allows the app to continue a user-initiated
action without requesting all-the-time access to background location.
References
https://developer.android.com/training/location/receive-location-updates
2) Work Manager
This approach would be less reliable as you will not be able to control when exactly this would be called but can be used if you don't want to show notification to the user at all.
You would not be able to run background services long running in Oreo as there are behavior changes, now Oreo to optimize system memory, battery etc, it kills background service, to solve your issue you should use foreground service.
Have a look at Background execution limits https://developer.android.com/about/versions/oreo/android-8.0-changes
A suggestion from me, if you can use FCM then go for it, because apps like WeChat, Facebook uses it, to deliver notifications and they don't face any problem.
Alternate solution which I have opted without FCM due to client requirement to run service that updates location in background. Here are steps below:-
You need to start your background service with showing notification in Oreo and above.
Them after that you need to keep in mind that after some time phone enters into Doze mode so you have to tackle that also
In Addition, Battery optimization must be disabled for the application too.
In Some custom ROM you need to manage the Auto-start permission to restart your service if the service is killed by the android.
And the most important part is, if the service is killed by the android system then send a Broadcast Message to the Broadcast receiver to restart your service one again
Hope you will do some more R&D work.
I have shared my experience and the process by which i have done the same to run the service in the background.
you must show notification for ForegroundService
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and add permission
<uses-permissionandroid:name=”android.permission.FOREGROUND_SERVICE” />

Android service background Android Oreo

in my Android project i've created an custom clock widget with a service which contains an instance of Broadcast Reciever and an intent filter. The Broadcast Reciever provides the update of the widget every time arrives the ACTION_TIME_TICK. This is working perfectly when set targetSdkVersion to 25, in gradle. But if i target to sdk 27, the service stops after few minutes. I've read the documentation about background executions limit in Android O, but i can't find any approach that is useful for my project. Do you have any suggestion?
There are a couple of things you can try which, when used in concert, should be able to cut through all of the idle/standby/doze modes (irrespective of OS version).
Use a WakefulBroadcastReceiver instead of an ordinary BroadcastReceiver. Make sure you include the WAKE_LOCK permission to use it correctly.
Use the setExactAndAllowWhileIdle() method (on API 23 & above) to schedule the Intent for the receiver:
if (Build.VERSION.SDK_INT < 23) {
if (Build.VERSION.SDK_INT >= 19) {
setExact(...);
}
else {
set(...);
}
}
else {
setExactAndAllowWhileIdle(...);
}

How to keep service running in background when app is closed but stop/disable it when the app is in foreground?

I am having difficulties trying to handle service behaviour in such case.
Basically I have a service running on a separate process that needs to issue httprequests every certain time whenever the app is closed, then write something into preferences or throw a notification.
The logic works fine. The problem I'm having is that I cannot find a way to properly stop/disable that service whenever the app is running, aswell as start it again when the app is being finished or put into background.
I've tried stopping it at #onResume()/#onStart() callbacks of my activities aswell as starting it at #onStop()/#onDestroy() but behaviour doesnt run as expected in any case...
I'll paste here some code snippets of what i've tried so far:
I start/stop services using:
stopService(new Intent(this,NotificationService.class));
startService(new Intent(this, NotificationService.class));
Random activity from my app (all implement this in their callbacks):
#Override
protected void onResume() {
if (Utility.isMyServiceRunning(this)){
Utility.serviceClose(this);
}
super.onResume();
}
#Override
protected void onStop() {
if (!Utility.isMyServiceRunning(this)){
startService(new Intent(this, NotificationService.class));
}
super.onStop();
}
This somehow doesnt work or brings unexpected behaviour since the app moves from many activities, and service ends up being alive when the app is running or stopped when the app is in background/finished.
I've also tried to toggle on/off service logic on service timertask every cicle by asking:
#Override
public void run() {
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for(int i = 0; i < procInfos.size(); i++){
if(procInfos.get(i).processName.equals("com.example.myapp")) {
return;
}
}
//service http request logic here
}
But that doesnt work either because process "com.example.myapp" never gets killed (and of course I cannot/want to force finish that), so it never issues any httprequest.
Any Ideas on how to implement this? Any help would be very welcome.
Thanks in advance.
How about binding to your service and then communicating directly with it? Implement a simple on/off boolean, expose a getter/setter on the binding, and then make sure the service checks the boolean before it does any work. That way you can disable it while the app is running without having to actually start/stop the service repeatedly.
http://developer.android.com/guide/components/bound-services.html
Solved with better handling of onStop() onResume() callbacks.

Categories

Resources