I wanted to make an app that would do something upon receiving broadcast for wifi state changes. How to edit this code in such way that the service also receives broadcasts after clearing the recent task ? Please help.thanks
Here is the code below :
public class IntentService extends Service {
SharedPreferences sharedPreferences;
SimpleDateFormat simpleDateFormat;
BroadcastReceiver broadcastReceiver= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int wifiStateExtra=intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
sharedPreferences.edit().putString(simpleDateFormat.format(new Date())," :"+ wifiStateExtra).apply();
Log.d("Wifi State", " :"+wifiStateExtra +" i :" +i);
}
};
private int i;
public IntentService() {
super();
}
@Override
public void onCreate() {
super.onCreate();
sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Toast.makeText(getApplicationContext(), "onTaskRemoved called", Toast.LENGTH_LONG).show();
startService(rootIntent);
super.onTaskRemoved(rootIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
In Short :
Is the one line answer to your question. You can try creating issue on https://issuetracker.google.com/
and you will get above as answer.
Bit longer answer :
Years by years
Googlehas restricted so many capabilities of developers, under the issue of battery performance. In short No apps in background will be getting any any any broadcasts in short. And if you clears your app from recents, its gone out of execution forever, until end user opens the app again.This is not just for broadcasts but also for background
work/tasks/jobs/alarms/ anything.. For these try using workmanager / tasks of your own / job schedular / alarm manager everything fails.Why it all fails :
Workmanageris the latest library and as per google it is intended to deliver work at any cost as per system decides whenever it will be good to execute, in order to save battery. And as previous alarmmanager and others has a lot of problems in delivering tasks to be done.Workmanager Which also fails as it has many bugs.. and is under development.
Yes it does only on emulators, in market 98 % are chinese ROMS modified android devices which never run your processes.
unregisterreceiver on destroy.Use
Firebaseas framework and let google handle it. It notifies such states for sure like facebook, whatsapp, tiktok, twitter and all others use this as backend and even if removed from recents..!!