Android: Will AlarmManager gets killed after shutdown - android

I am wondering will the alarm that I have set get destroyed after i shutting down the device or will it save the state of the schedule and broadcast straightaway when the user turning back on the device as long as the scheduled time is before the current time.

When device get rebooted alarm manager get destroyed.you need to re register the alarm manager after boot complete
add this permission in your manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and broadcast
<receiver
android:name="your package name.MyBroadcast "
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
create a broadcast receiver
public class MyBroadcast extends BroadcastReceiver {
private static final String LOG_TAG = "MyBroadcast ";
public MyBroadcast () {
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
// Register your alarm manager here
break;
default:
break;
}
}
}
}

Android: Will AlarmManager gets killed after shutdown ?
Ans: YES
will it save the state of the schedule and broadcast straightaway when the user turning back on the device as long as the scheduled time is before the current time ?
Ans: NO
Resolution: Re-Register AlarmManager on BOOT_COMPLETED broadcast

It willl be destroyed after shutdown. Your should implement a RECEIVE_BOOT_COMPLETED broadcast receiver. In this way you will when device is shutdown and in your receiver set your AlarmManager again.

Related

Broadcast not triggered when process is created

I have a broadcast which monitors for unlock event for the phone. But when the app's process is killed and no longer in memory, Unlocking the phone does not trigger the Receiver, instead I can see in the Android studio, that new process is created for that app.
If lock and unlock it again, then as the process is already running, I can see the BroadcastReceiver is triggered.
<receiver
android:name=".UserPresentBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
Broadcast Receiver:
public class UserPresentBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = UserPresentBroadcastReceiver.class.getSimpleName();
#Override
public void onReceive(Context arg0, Intent intent) {
Log.d(TAG, "onReceive: Unlock Boradcast received");
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Toast.makeText(arg0, "You just unlocked the device", Toast.LENGTH_LONG).show();
}
}
}
I am unable to understand this behavior. Is this the default behavior?
You have to register and unregister this broadcast receiver in Activity(or Service for listening in background all the time).
Manifest entry won't work.

Android IntentService runs only ONCE after phone is restarted. Why?

Background and issue
I have checked dozens of tutorial, examples and questions here on stackoverflow which are related to the issue that services don't get registered after the phone is switched off.
My issue is almost similar with a little difference: I use an IntentService (I need to collect data from an external database and show it as a notification) and the service runs without any problem every 30 seconds until I switch the phone off.
The interesting part
Here comes the weird behaviour! I turn my phone back and the IntentService is registered ONLY ONCE. After booting up, I get my notification (in the example i use only logs for the sake of simplicity) only once, then never again.
part of Activity code (where I can set the service)
private void setRecurringAlarm(Context context) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, BackgroundDataServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 30*1000, pending);
}
IntentService
public class BackgroundDataService extends IntentService {
....
#Override
protected void onHandleIntent(Intent intent) {
Log.i("BACKGROUNDDATASERVICE STATUS", "running");
}
}
BroadcastReceiver
public class BackgroundDataServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, BackgroundDataService.class);
context.startService(dailyUpdater);
}
}
Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
...
<service android:name="com.example.blgui3.BackgroundDataService" >
</service>
<receiver android:name="com.example.blgui3.BackgroundDataServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
...
</application>
As far as I know if my service needs to do background tasks e.g. fetch data from external database with AsyncTask then it is recommended to use IntentService. Even if I launch the app after the boot, the service still runs only once, so it simply does not register the BOOT_COMPLETE action. After struggling for hours with this I have absolutely no clue where I go wrong.
The service is started after boot with BOOT_COMPLETED but that does not start any activity and it seems it is only activity that sets the alarm.

part-1 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart

Status:--- I equally accept Karakuri's and Sharad Mhaske's answer, but since Sharad Mhaske answer after the start of bounty, the bounty should go to him.
Part-2 made: part-2 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart
In stack overflow, only one answer may be accepted. I see both answers as acceptable but one has to be chosen (I chosed at random).
Viewers are invited to up/down vote answers/question to appreciate the effort!. I upvoted Karakuri's answer to compensate reputation.
Scenario:---
I want to make the user click a start/stop button and start/stop a service from UI activity. I have made the UI so dont care about that. But Just the logic of the Button click event.
Do not want the service to be bound to the UI activity. If activity closes, the service should keep running.
Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)
Unless the stop button is clicked by my apps UI, do not want it to be stopped (or should restart itself) Even if android reclaim memory. I and the user of the phone, both are/will be aware of it. The service is most of importance. Even at sleep.
details= my app do some operations, sleep for user provided time (15 minuts usually), wakes and perform operations again. this never ends)
If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?
When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.
QUESTION:---
Primary Question:
Just can't get an optimal strategy for the scenario... and also stuck on small bits of code, which one to use and how.
Gathered bits and pieces from stackoverflow.com questions, developer.android.com and some google results but cannot implement in integration.
Please read out the Requests Section.
Secondary Question:
The comments in my code are those small questions.
Research and Code:---
Strategy:
want this to happen every time the user opens the UI.
//Start Button:-----
//check if ForGroundService is running or not. if not running, make var/settings/etc "serviceStatus" as false
<-------(how and where to stare this and below stated boolean?)
//start ForGroundService
<-------(how?)
//make "SericeStatus" as true
//check if "ServiceStartOnBoot" is false
//Put ForGroundService to start on boot -------(to make it start when ever the phone reboots/restarts)
<-------(how?)
//make "ServiceStartOnBoot" as true
// the boolean can also be used to check the service status.
//Stop Button:------
//makes SericeStatus and ServiceStartOnBoot as false
//stops service and deletes the on boot entry/strategy
Activity UI class that starts/stops the service:
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//some button here to start / stop and their onClick Listners
Intent mySericeIntent = new Intent(this, TheService.class);
}
private void startMyForGroundService(){
startService(mySericeIntent);
}
private void stopMyForGroundSerice(){
stopService(mySericeIntent);
/////// is this a better approach?. stopService(new Intent(this, TheService.class));
/////// or making Intent mySericeIntent = new Intent(this, TheService.class);
/////// and making start and stop methods use the same?
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
The Service class:
public class TheService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1, new Notification());
////// will do all my stuff here on in the method onStart() or onCreat()?
return START_STICKY; ///// which return is better to keep the service running untill explicitly killed. contrary to system kill.
///// http://developer.android.com/reference/android/app/Service.html#START_FLAG_REDELIVERY
//notes:-// if you implement onStartCommand() to schedule work to be done asynchronously or in another thread,
//then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it
}
#Override
public void onDestroy() {
stop();
}
public void stop(){
//if running
// stop
// make vars as false
// do some stopping stuff
stopForeground(true);
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
The Menifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myapp.SettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
</application>
</manifest>
References:---
Android - implementing startForeground for a service? pointing answer 1, example code.
Trying to start a service on boot on Android
Android: Start Service on boot?
http://developer.android.com/guide/components/services.html
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/training/run-background-service/create-service.html not preffered by me.
http://developer.android.com/guide/components/processes-and-threads.html my starting point of research
Requests:---
I think this question is a normal practice for most people who are dealing with services.
In that vision, please only answer if you have experience in the scenario and can comprehensively explain the aspects and strategy with maximum sample code as a complete version so it would be a help to the community as well.
Vote up and down (with responsibility) to the answers as it matters to me who shared their views, time and experience and helped me and the community.
Que:Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)
Answer:you need to start service with using START_STICKY Intent flag.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Que:If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?
Answer:you need to register alarmmanager within service for the time after to some task.
//register alarm manager within service.
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);
//now have a broadcastreceiver to receive this intent.
class Alarmreceiver extends Broadcastreceiver
{
//u can to task in onreceive method of receiver.
}
//register this class in manifest for alarm receiver action.
Que:When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.
Answer:use broadcast reciver to listen for onboot completed intent.
public class StartAtBootServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
try {
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(), LicensingService.class.getName());
ComponentName service = context.startService(new Intent().setComponent(comp));
if (null == service){
// something really wrong here
//Log.Write("Could not start service " + comp.toString(),Log._LogLevel.NORAML);
}
}
else {
//Log.Write("Received unexpected intent " + intent.toString(),Log._LogLevel.NORAML);
}
} catch (Exception e) {
//Log.Write("Unexpected error occured in Licensing Server:" + e.toString(),Log._LogLevel.NORAML);
}
}
}
//need to register this receiver for Action_BOOTCOMPLETED intent in manifest.xml file
Hope this helps you clear out things :)
If you start a service with startService(), it will keep running even when the Activity closes. It will only be stopped when you call stopService(), or if it ever calls stopSelf() (or if the system kills your process to reclaim memory).
To start the service on boot, make a BroadcastReceiver that just starts the service:
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
Then add these to your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application ... >
<receiver android:name="MyReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Notice that the receiver is not enabled at first. When the user starts your service, use PackageManager to enable the receiver. When the user stops your service, use PackageManager to disable the receiver. In your Activity:
PackageManager pm = getPackageManager();
ComponentName receiver = new ComponentName(this, MyReceiver.class);
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Use same method with PackageManager.COMPONENT_ENABLED_STATE_DISABLED to disable it.
I have made something like this myself but I learned a lot while developing it and discovered it is not completely necesary to have the service running all day draining your battery. what I made is the following:
Implement a Service that reacts to events. In my particular I wanted to automate my Wifi and mobile data connection. so i react to events like wifi connecting and disconnecting, screen turning on and off, etc. So this service executes what ever needs to be executed responding to this event and then stops, scheduling any further actions with the AlarmManager if so needed.
now, this events can by timers like you said yourself every 15 minutes it does something and sleeps, that sounds to me that you really dont want the service running 24/7 but just executing something every 15 minutes. that is perfectly achievable with the AlarmManager without keeping your service running forever.
I recommend implementing this service deriving from commonsware's WakefulIntentService.
This class already handles the wakeLock for you so that you can exceute code even if phone is asleep. it will simply wakeup execute and go back to sleep.
Now. About your question regarding the activity starting and stoping the service. you can implement in the button that it starts or cancels the AlarmManager alarm. Also you can use the sharedPreferences to store a simple boolean that tells you if it is enabled or not so the next time your service runs it can read the value and know if it should continue or stop.
If you implement it as a event-reactive service as i said, your button can even react to broadcast intents so that your activity doesn't even have to call the service directly just broadcast an intent and the service can pick it like other events. use a BroadcastReceiver for this.
I'll try to give examples but be wary that what you're asking is a lot of code to put it in one place...
BootReceiver:
public class BootReceiver extends BroadcastReceiver
{
private static final String TAG = BootReceiver.class.getSimpleName();
#Override
public void onReceive(final Context context, final Intent intent)
{
final Intent in = new Intent(context, ActionHandlerService.class);
in.setAction(Actions.BOOT_RECEIVER_ACTION); //start the service with a flag telling the event that triggered
Log.i(TAG, "Boot completed. Starting service.");
WakedIntentService.sendWakefulWork(context, in);
}
}
Service:
public class ActionHandlerService extends WakedIntentService
{
private enum Action
{
WIFI_PULSE_ON, WIFI_PULSE_OFF, DATA_PULSE_ON, DATA_PULSE_OFF, SCREEN_ON, SCREEN_OFF, WIFI_CONNECTS, WIFI_DISCONNECTS, WIFI_CONNECT_TIMEOUT, WIFI_RECONNECT_TIMEOUT, START_UP, BOOT_UP
}
public ActionHandlerService()
{
super(ActionHandlerService.class.getName());
}
#Override
public void run(final Intent intent)
{
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettingsContainer.enabled = mSettings.getBoolean(getString(R.string.EnabledParameter), false);
if (intent != null)
{
final String action = intent.getAction();
if (action != null)
{
Log.i(TAG, "received action: " + action);
if (action.compareTo(Constants.Actions.SOME_EVENT) == 0)
{
//Do what ever you want
}
else
{
Log.w(TAG, "Unexpected action received: " + action);
}
}
else
{
Log.w(TAG, "Received null action!");
}
}
else
{
Log.w(TAG, "Received null intent!");
}
}
}
And your Manifest could go something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.yourcompany.yourapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="false"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourcompany.yourapp.activities.HomeActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.yourcompany.yourapp.services.ActionHandlerService" />
<receiver android:name="com.yourcompany.yourapp.receivers.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
</application>
</manifest>

Broadcast Receiver within a Service

I am trying to start up a BroadcastReceiver within a Service. What I am trying to do is have a background running service going that collects incoming text messages, and logs incoming phone calls. I figured the best way to go about this is to have a service running that incorporates a broadcast receiver that can catalog either.
How do i go about doing this? I already have my service up and running.
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.
Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().
Eg:
public class FooReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}

Android BroadcastReceiver on startup - keep running when Activity is in Background

I'm monitoring incoming SMSs.
My app is working perfectly with a BroadcastReceiver. However it is working from an Activity and would like to keep the BroadcastReceiver running all the time (and not just when my Activity is running).
How can I achieve this? I've looked through the lifecycle of the BroadcastReceiver but all that is mentioned in the documentation is that the lifecycle is limited to the onReceive method, not the lifecycle of keeping the BroadcastReceiver checking for incoming SMS.
How can I make this persistent?
Thanks
You need to define a receiver in manifest with action name android.intent.action.BOOT_COMPLETED.
<!-- Start the Service if applicable on boot -->
<receiver android:name="com.prac.test.ServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Make sure also to include the completed boot permission.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Use Service for this to make anything persist. And use receivers to receive Boot Up events to restart the service again if system boots..
Code for Starting Service on boot up. Make Service do your work of checking sms or whatever you want. You need to do your work in MyPersistingService define it your self.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent("com.prac.test.MyPersistingService");
i.setClass(context, MyPersistingService.class);
context.startService(i);
}
}
Service or Boot Completed is not mandatory
In fact, you don't need to implement a Service or register to android.intent.action.BOOT_COMPLETED
Some examples shows how to register/unregister a BroadcastReceiver when activity is created and destroyed. However, this is useful for intents that you expect only when app is opened (for internal communication between Service/Activity for example).
However, in case of a SMS, you want to listen to the intent all the time (and not only when you app is opened).
There's another way
You can create a class which extends BroadcastReceiver and register to desired intents via AndroidManifest.xml. This way, the BroadcastReceiver will be indepedent from your Activity (and will not depend from Activity's Life Cycle)
This way, your BroadcastReceiver will be notified automatically by Android as soon as an SMS arrive even if your app is closed.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest>
...
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application>
....
<receiver android:name=".MyCustomBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
MyCustomBroadcastReceiver.java
public class MyCustomBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent != null) {
String action = intent.getAction();
if(action != null) {
if(action.equals("android.provider.Telephony.SMS_RECEIVED")) {
// DO YOUR STUFF
} else if (action.equals("ANOTHER ACTION")) {
// DO ANOTHER STUFF
}
}
}
}
}
Notes
You can add others intent-filters to AndroidManifest and handle all of them in same BroadcastReceiver.
Start a Service only if you will perform a long task. You just need to display a notification or update some database, just use the code above.
Add Broadcast Reciever in manifest:
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
Create Class BootReciever.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
// +++ Do Operation Here +++
}
}
}
Beside #Javanator answer I would like to include a case for Android version of (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) In my case this is working for Android SDK 29 (10)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context,FloatingWindow.class));
} else {
context.startService(new Intent(context, FloatingWindow.class));
}
use this code and also mention the broadcast in Manifest also:
public class BootService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
Toast.makeText(context, "Boot Completed", Toast.LENGTH_SHORT).show();
//write code here
}
}
}
I just want to mention that in case of some Chinese phone brands (e.g. MI), you need to go to Settings and give autostart permission to your app.
Otherwise the battery optimisation feature will kill your service in background and broadcast receiver will not work.
So you can redirect your user to Settings and ask them to give that permission.

Categories

Resources