Here is my code for starting a service:
I am starting my service in onCreate() of my Activity.
Intent svc=new Intent(BeapSoundActivity.this, BackgroundService.class);
pendingIntent = PendingIntent.getService(BeapSoundActivity.this, 0, svc, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pendingIntent);
I cant able to stop a service by calling
stopService();
Here is my Service class:
public class BackgroundService extends Service{
// private static final String TAG = null;
// MediaPlayer player;
MediaPlayer mMediaPlayer;
String strResponse;
int i=0;
static {
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build());
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
mMediaPlayer = new MediaPlayer();
Log.e("Oncreate","oncreate");
}
public int onStartCommand(Intent intent, int flags, int startId) {
// player.start();
Log.e("Onstartcommand","onstartcommand");
pendingCount();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
// super.onStart(intent,startId);
Log.e("Onstart","onstart");
// pendingCount();
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
this.stopSelf();
}
public void onPause() {
}
#Override
public void onDestroy() {
super.onDestroy();
this.stopSelf();
// player.stop();
// player.release();
}
#Override
public void onLowMemory() {
}
}
public void pendingCount(){
my operations during the service
}
}
}
I have also tried with stopSelf() in my onDestroy(),but it also didnt worked for me.
Please suggest how can I solve this issue?
you've to call stopService() from another activity. Or you can call stopSelf() in the service (not in onDestroy()) when the required work finishes.
What I can see that your stopservice() is working fine to stop the service but anonymous class or what ever you are using inside pendingCount() is still working even though service is destroyed..
So do some thing like this
Rise a flag in ondestroy() and check this inside pendingCount() looping part and if this flag is high destroy this task also. For more accurate answer add complete pendingCount()
code
You can check my answer that I have posted previously and try to implement that. Hope it works for you.
Try using this code it may help you.
stopService(new Intent(MainActivity.this,BackgroundService.class));
Related
So I have code that I want called when my application is closed. Not just when it is sent to the background or the surface is destroyed. How do I do this? Is there a method that I can override in a SurfaceView or Activity class?
New Edit - current BackgroundService class:
public class BackgroundService extends Service {
private String savedString;
public void onCreate() {
System.out.println("Service created");
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("start command: ");
savedString = intent.getStringExtra("myString);
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent intent) {
return null;
}
public void onTaskRemoved(Intent rootIntent) {
System.out.println("the saved string was: " + savedString);
super.onTaskRemoved(rootIntent);
}
public void onDestroy() {
System.out.println("destroyed service");
super.onDestroy();
}
}
Where I then have this in my other class:
Intent serviceIntent = new Intent(activity.getApplicationContext(), BackgroundService.class);
serviceIntent.putExtra("myString", "this is my saved string");
activity.startService(serviceIntent);
you need to add a background service
public class BackgroundServices extends Service
{
#Override
public void onCreate() {
Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
then in your activity. where you want to trigger this service
use
startService(new Intent(getBaseContext(), BackgroundServices.class));
in your case it will be call on onDestory function of that activity
Yes when the process is terminated
That is not possible in general. Nothing in your app is called when the process is terminated.
For example when you open the running apps screen, and swipe away the app to stop it from running
That is a task removal. It may result in your process being terminated, and there are many ways in which your process can be terminated that has nothing to do with task removal.
To detect task removal, override onTaskRemoved() in a Service.
Run a service in background continuously. For example, a service has to be kicked off which will display a toast message 20 seconds once even if the app is closed.
public class AppService extends IntentService {
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public AppService() {
super("AppService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
Toast.makeText(getApplicationContext(), "hai", Toast.LENGTH_SHORT).show();
SystemClock.sleep(20000);
}
}
Below code works for me...
public class AppService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
Accepted answer will not work on from Android 8.0 (API level 26), see the android's background limitations here
Modification in Accepted Answer:
1: You have to invoke the service's startForeground() method within 5 seconds after starting the service. To do this, you can call startForeground() in onCreate() method of service.
public class AppService extends Service {
....
#Override
public void onCreate() {
startForeground(9999, Notification())
}
....
}
2: You must call startForegroundService() instead of startService() by checking API level from where you want to start the service.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
This code work for me..
public class ServiceClass extends Service {
public static final int notify = 300000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Log.d("service is ","Destroyed");
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("service is ","running");
}
});
}
}
}
In your manifest, where you declare your service, add:
android:process=":processname"
This lets the service run on a separate process and thus it will not be killed with the app.
You can then chose if you want to use foreground. It will show a persistent notification, but reduces the likelihood if the service being killed.
Further, if you want to create a continuously running service, use Service, NOT IntentService. IntentService stops when it is finished doing its action.
I am calling service from the application class, If I close the app or remove from currently running apps, then the service will destroy automatically,I didn't written any code in on Destroy() method
to call service here is code :
Intent syncIntent = new Intent(this, ScanBLE_Service.class);
this.startService(syncIntent);
here is the code of service class
public class ScanBLE_Service extends IntentService {
public ScanBLE_Service() {
super(ScanBLE_Service.class.getName());
// TODO Auto-generated constructor stub
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
demo();
}}
private void demo() {
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Demoooo", Toast.LENGTH_SHORT).show();
demo();
}
}, 5000
);
}
You should use Service, not IntentService. Extend the Service class and override onStartCommand method, then do the calculations in this method
To run your service even after the application is destroyed you need to do the following.
extend your service with Service classs
return START_STICKY in onStartCommand()
override onTaskRemoved(refer the following example code).
public class MyIntentService extends Service
{
Timer mTimer;
#Override
public void onCreate()
{
super.onCreate();
mTimer = new Timer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mTimer.schedule(mTimerTask, 1000, 5000);
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
TimerTask mTimerTask = new TimerTask()
{
#Override
public void run()
{
System.out.println("timer task run");
}
};
#Override
public void onTaskRemoved(Intent rootIntent)
{
System.out.println("onTaskRemoved");
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
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() + 1000, restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
Yes, the service will be closed if application is closed. One situation, when the service will not be closed in to have a constant Notification on notifications screen.
More here
The normal behavior is that the service will keep running even if the application is closed, because it's separated from the application and runs in background, unless you call stopSelf() or stopService(x,x) it should keep running..
PS: there's another type of service which is IntentService (extends IntentService rather then Service) and this will stop automatically once the code in onHandleIntent() is executed..
For a demo I print a Toast after Evert 10 sec. using Service class.
It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.
But I want to that toast either I'll kill the App or back press Here is code snippet :
ServiceDemo.java
public class ServiceDemo extends Activity {
private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {
#Override
public void run() {
as();
myHandler.postDelayed(this, 10000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
myHandler.postDelayed(drawRunnable, 10000);
startService(new Intent(this, MyService.class));
}
public void as(){
startService(new Intent(this, MyService.class));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Service.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}
Edit 1
moveTaskToBack(true);
I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, Service not responding
I think you need to override onStartCommand instead of onStart()
like:
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
i think AlarmManager is what you want.
You have to user AlarmManager, here's an example : Alarm Manager Example
Your task will be executed even if the application is terminated.
But if the application is killed by the user, the Alarm will be canceled. See this discussion How to create a persistent AlarmManager
I am building an android app and when it is running I need to make a call to the my web server at each minute if the user is connected to a certain network.
I plan to use a service to make that call but how do I call it at each minute?.
I think i need to use alaarm manager but where do I initalize it? in my start activity? I only need to execute the service when my app is running.
Thanks for your help.
If you want to call server only if app is running then no need to use alarm manager. there are other options like
CoundDownTimer
Thread
I prefer CoundownTimer in that scenario and you can use like this
CountDownTimer countDownTimer = new CountDownTimer(1000000, 60 * 1000) {
#Override
public void onTick(long millisUntilFinished) {
// Do something on a tick.
}
#Override
public void onFinish() {
// Do something, maybe?
this.start();
}
};
countDownTimer.start();
Try this ::
You can call this timer in your activity where you want it
private Timer autoUpdate;
#Override
public void onResume() {
super.onResume();
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//call your service from here
}
});
}
}, 0, 60000);//set time interval according to your requirement
}
Feel free to ask if you have any query :)
in Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestAlarmMessageReceiver almesr = new TestAlarmMessageReceiver(this, time);
}
BroadcastReceiver:
public class TestAlarmMessageReceiver extends BroadcastReceiver {
public TestAlarmMessageReceiver() {
}
public TestAlarmMessageReceiver(Context context, int timeout) { //timeout in seconds
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, TestAlarmMessageReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
timeout*60*1000, pendingIntent);
}
#Override
public void onReceive(Context arg0, Intent arg1) {
arg0.startService(new Intent(arg0, TestMessageService.class));
}
}
Service:
public class TestMessageService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
messageUpdateTask();
return super.onStartCommand(intent, flags, startId);
}
private void messageUpdateTask(){
GetMessagesUpdateAsyncTak getMessUpd = new GetMessagesUpdateAsyncTak();
getMessUpd.execute(this);
}
}
Call your web server using AsynTask http://developer.android.com/reference/android/os/AsyncTask.html
In onPost method in AsynTask class wait for one minute and call AsynTask.
You can call AsynTask by using below code :
BLSyncingProcedure objSyncingProcedure=new BLSyncingProcedure();
objSyncingProcedure.execute(HomeScreen.this);
BLSyncingProcedure is your AsynTask class name.