Service not running after app killed on Android 8 Oreo [duplicate] - android

This question already has answers here:
Background service for android oreo
(3 answers)
Closed 3 years ago.
i have a service for connecting my socket to server and i want restart this service when my app kill.
restarting service works fine on android 5 but not working on Oreo.
i tried so many ways to do this like : boardCastReceivers and changing manifest setting for service but not working
my codes:
in manifest
<service
android:name="com.jeen.jeen.service.ChatService"
android:enabled="true" >
</service>
<receiver
android:name="com.jeen.jeen.service.ChatReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
>
</receiver>
in MainActivity:
#Override
protected void onDestroy() {
stopService(mServiceIntent);
Log.i("MAINACT", "onDestroy!");
super.onDestroy();
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}
ChatService chatService;
Intent mServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chatService = new ChatService(MainActivity.this);
mServiceIntent = new Intent(MainActivity.this, chatService.getClass());
if (!isMyServiceRunning(chatService.getClass())) {
startService(mServiceIntent);
}
setContentView(R.layout.activity_main);
}
receiver class:
public class ChatReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(ChatReceiver.class.getSimpleName(), "Service fucked up");
context.startService(new Intent(context, ChatService.class));
}
}
and service class:
public class ChatService extends Service{
public static Socket socket;
#Override
public void onCreate() {
super.onCreate();
Log.e("onCreate", "onCreate");
try {
socket = IO.socket("http://192.168.174.1:8000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
// Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
}
public ChatService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public ChatService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
onTaskRemoved(intent);
}
super.onStartCommand(intent, flags, startId);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
if (!socket.connected()) {
socket.connect();
}
}
});
}
},
0,
5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Log.i("EXIT", "ondestroy!");
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent restartServiceIntent = new Intent(getApplicationContext(), ChatService.class);
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 4000,
restartServicePendingIntent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
is anyway to do this?

If you are using vivo/honor/oppo etc , your services will get killed as soon as your app is closed.

Related

how to run a service which receives broadcast on Oreo?

so i am trying to create a battery statistics android app but neither i'm able to receive broadcast using broadcastmanager cos its not available for android oreo and nor my service is running on background for more than a few minutes.
my question is how do i receive battery broadcasts like plug,unplug,level..... in background on android oreo api 26+
i run the service from the activity on destroy
/////my service code/////
public class bservice extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter ifl = new IntentFilter();
registerReceiver(bcr,new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_POWER_CONNECTED));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(bcr,ifl);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(10000);
update();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Log.d("msg","running in background 1");
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver bcr = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
update();
Log.d("msg","running in background 2");
}
};
#Override
public void onDestroy() {
super.onDestroy();
//unregisterReceiver(bcr);
Log.d("msg","service destroyed");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this,bservice.class));
Log.d("msg","serv restarted");
}
}
void update()
{.......... my updating code
updaten(pct,cc,isCharging,isCharging);
}
Notification notification;
NotificationManager notificationManager;
void updaten(float pct,float cc,boolean a,boolean ot)
{.........my notification update code
notificationManager.notify(id, notification);
}
}
}
Use JobIntentService instead of Service and then register broadcast receiver dynamically from service.
https://developer.android.com/reference/android/support/v4/app/JobIntentService.html

starting BroadcastReceiver from Service when app destroy?

i have a probleme with BroadcastReceiver & Service in my application
.......
i have an
* activity ( MainActivity )
* service ( NotifyService )
* Receiver ( NotifyBroadcast )
service start from activity and then the receiver start from service
everything is good when my app was open , but when i clear it (destroyed) ,receiver stop doing its job ( just a toast message )
here is my code :
MainActivity ..
if( !NotifyService.ServiceIsRun){
NotifyService.ServiceIsRun=true;
startService(new Intent(this, NotifyService.class));
}
NotifyService ..
public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
if(ServiceIsRun){
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.e("broadService", "hello from Service"+i +"new :"+lastnew +"article :"+lastarticle);
i++;
Intent intent = new Intent( "com.latestBabiaNews" );
sendBroadcast(intent);
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
20000);
}
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
NotifyBroadcast ..
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
}
And in my Manifest ..
<service android:name=".NotifyService"></service>
<receiver android:name=".NotifyBroadcast">
<intent-filter>
<action android:name="com.latestBabiaNews"></action>
</intent-filter>
</receiver>
..........
finally i can show the Toast message when app was app was opened , but when i clear it i can't show anything !
To prevent service kill use it as foreground service. To perform it as foreground use this (inside Service class):
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
fg();
}
private void fg() {
Intent intent = launchIntent(this);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(getResources().getString(R.string.app_alias))
.setContentText(getResources().getString(R.string.app_alias))
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(someicon);
} else {
mBuilder.setSmallIcon(someicon);
mBuilder.setColor(somecolo);
}
noti = mBuilder.build();
noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
startForeground(_.ID, noti);
}
to stop, this:
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopForeground(true);
}
EDIT
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class MyBroadCast extends WakefulBroadcastReceiver {
public static final String INTENT_FILTER = "ru.ps.vm.BRTattva";
#Override
public void onReceive(Context ctx, Intent intent) {
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
To start use this:
public static void startbyalarm(Context ctx, long nexttime, boolean autoStart, SharedPreferences settings) {
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
Intent intent = new Intent(MyBroadcastReceiver.INTENT_FILTER);
if (autoStart)
intent.putExtra(_.AUTOLOADSERVICE,true);
PendingIntent pi = PendingIntent.getBroadcast(ctx, _.intentalarmindex, intent, PendingIntent.FLAG_CANCEL_CURRENT);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
am.setExactAndAllowWhileIdle(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
}
}
//or use repeating:
//am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}

Android: How to detect a background service when app restarted?

I have an app that creates a never ending background service. The service is started when the app is launched. When the app is killed (e.g. by the user), the service sends a broadcast request that will restart it after it is killed.
The question is: when I restart the app, how can I know if the service is already running?
Naively I had thought that by restarting the service when the app is re-launched it would have stopped the existing service but this does not happen. The following code shows that if I do this, there are two services running at the same time (the printout in the timer moves from every second to every half a second).
Many thanks
public class MainActivity extends AppCompatActivity {
static Intent mServiceIntent;
private SensorService mSensorService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx=this;
setContentView(R.layout.activity_main);
mSensorService= new SensorService(getCtx());
mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
startService(mServiceIntent);
}
Context ctx;
public Context getCtx() {
return ctx;
}
#Override
protected void onDestroy() {
stopService(mServiceIntent);
Log.i("MAINACT", "onDestroy!");
super.onDestroy();
}
}
public class SensorService extends Service {
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to check if the service is there in 25s
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to check in x seconds if the sensorsService is active. If not it will start the service
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
long time= System.currentTimeMillis();
Log.i("in timer", "in timer ++ "+(time-oldTime)+" ++ "+ (counter++));
oldTime= time;
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
stoptimertask();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, SensorService.class));;
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
And then use
isMyServiceRunning(MyService.class)
Credit

CountDownTimer inside Service stopped after application killed - Android

I'm new to services and BroadcastReceiver so maybe this question is newbie, but I didn't found the solution for my question after a long search on the web.
I need to run a CountDownTimer inside service, so the time keep moving even the application was finished.
In my code I based on THIS EXAMPLE.
My code works fine, but after the application is finished the CountDownTimer stopped(The service doesn't destroyed, just the timer).
I tried to implement it in different ways, but nothing works for me.
This is the part of my code that relevant:
AlarmReciver:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, BackgroundService.class);
Bundle bundle = intent.getExtras();
background.putExtra("time", bundle.getInt("time"));
context.startService(background);
}
}
BackgroundService :
public class BackgroundService extends Service {
private final static String TAG = "BroadcastService";
private CountDownTimer cdt = null;
private Bundle bundle;
private boolean isRunning;
private Context context;
private int timeInMili;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.context = this;
this.isRunning = false;
}
#Override
public void onDestroy() {
//cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
bundle = intent.getExtras();
timeInMili = bundle.getInt("time");
if(!this.isRunning) {
this.isRunning = true;
}
cdt = new CountDownTimer(timeInMili, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
stopSelf();
}
};
cdt.start();
return START_STICKY;
}
}
MainActivity (extends FragmentActivity):
public void StartBackgroundAlarm(int timeInMili)
{
Intent alarm = new Intent(this, AlarmReceiver.class);
alarm.putExtra("time", timeInMili);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pendingIntent);
}
MANIFEST :
<service android:enabled="true" android:name= "com.MES.yo.servicemanager.BackgroundService" />
<receiver android:name="com.MES.yo.servicemanager.AlarmReceiver"></receiver>

Not receiving CountDownTimer callbacks in Service

I have a Bound service which collects locations for 3 minutes every 15 minutes. I start a CountDownTimer once the Service is connected in onServiceConnected of ServiceConnection.
I receive all the Timer callbacks (onFinish) (onTick) perfectly as far the Activity which bindService is visible.
When Device is locked I do not receive any updates from the timer.
MyLocationService
public class MyLocationService extends Service implements MyTimerListener{
private IBinder mBinder = new MyLocationBinder();
public void onCreate() {
locationManager = new MyLocationManager(this);
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyLocationBinder extends Binder
{
public MyLocationService getService()
{
return MyLocationService.this;
}
}
public void startFetchingLocations()
{
if(locationManager != null){
locationManager.startFetchingLocations();
if(publishPeriodCountDownTimer != null) {
publishPeriodCountDownTimer.cancel();
publishPeriodCountDownTimer = null;
}
publishPeriodCountDownTimer = new MyCountTimer(gpsPublishPeriod * 60 * 1000, 1000, MyLocationService.this);
publishPeriodCountDownTimer.start();
}
}
#Override
public void onTimeFinished() {
//Start fetching locations
locationManager.startFetchingLocations(); //Start 3 min CountdownTimer
}
#Override
public void onTick() {
}
public void onAllLocationsRecieved(ArrayList<Location> locations)
{
//Do stuff on Locations
locationManager.stopFetchingGPS(); //Stops 3 min countdownTimer
}
}
MyActivty
public class MyActivity
{
#Override
protected void onStart() {
super.onStart();
btnStop.setVisibility(View.VISIBLE);
MyNoificationManager.cancelAllNotifications();
if (!isLocationServiceBound) {
Intent locServiceIntent = new Intent(this, MyLocationService.class);
bindService(locServiceIntent, locationServiceConnection, Context.BIND_AUTO_CREATE);
}
}
private ServiceConnection locationServiceConnection = new ServiceConnection(){
#Override
public void onServiceDisconnected(ComponentName name) {
isLocationServiceBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyLocationBinder locationBinder = (MyLocationBinder) service;
locationService = locationBinder.getService();
isLocationServiceBound = true;
locationService.startFetchingLocations();
}
};
}
It works as expected when the Activity is visible. The timer doesn't provide any onTick() or onTimeFinished() callbacks when the device is locked.
What could be the problem here ?
The CountDownTimer will not work when the phone goes to sleep mode. This is by design and it's to save battery life.
Alternately you can use android.app.AlarmManager instead to achieve your goal. Following is the sample code how to do that. Set the alaram like below
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyLocationService.class);
intent.putExtra("need_to_fetch_loc", true);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, gpsPublishPeriod * 60 * 1000, alarmIntent);
Add the following method to your MyLocationService class
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(locationManager!= null && intent.getBooleanExtra("need_to_fetch_loc", false))
{
locationManager.startFetchingLocations();
}
return super.onStartCommand(intent, flags, startId);
}

Categories

Resources