2

i have a simple service need to run in background.below is the code for the service.i want to run the code in onStartCommand repeatedly simply for test purpose i displayed toast.but Toast also calling only once

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;




/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class WiFiCheck extends Service {




    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.


        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();


        return super.onStartCommand(intent, flags, startId);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

but onStartCommand is calling only once getting toast only once.

i used

return START_STICKY;

starting service as below

        startService(new Intent(this, WiFiCheck.class));

but still no use.any help

Gaju Kollur
  • 2,046
  • 5
  • 23
  • 47

3 Answers3

1

Toast will be twice and more called if you start again service

e.g.

startService(new Intent(this, WiFiCheck.class));
startService(new Intent(this, WiFiCheck.class));

new Intent is an intent which is in onStartCommand(Intent intent

Vlad
  • 7,997
  • 3
  • 56
  • 43
  • why to start twice ..services meant for contentious operations..want to start it once need to get toast again and again until i stop the service – Gaju Kollur Apr 20 '18 at 12:05
  • 1
    `services meant for contentious operations` only of it is *foreground*. try out such way and make toast in a loop e.g. – Vlad Apr 20 '18 at 12:31
1

Short answer

Call StartService as much times as you want the toast to show up.

About returning START_STICKY(Why doesn't returning START_STICKY show your toast twice?)

Returning START_STICKY at the end of onStartCommand() method lets your service start again(onStartCommand() is called again) when your service is KILLED(by some reasons like system resource depletion). So there is no relevence between return START_STICKY; and your goal.

Solution to reach your goal

Like the Kalyzunyu's answer, just call StartService() twice to show your toast twice. It does not instantiate your Service twice, but calls your onStartService() twice. So be free to call it again.

Refer here.

Or if you want to show the toast every 10 seconds until it is stopped try this.

public class WiFiCheck extends Service
{

    private Thread thread;




    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        startForeground(1, new Notification());
        thread=new Thread(new Runnable(){

                @Override
                public void run()
                {
                    // TODO: Implement this method
                    while(true)
                    {
                        Toast.makeText(WiFiCheck.this, "Service Started", Toast.LENGTH_LONG).show();
                        try
                        {
                            Thread.sleep((long)10000);
                        }
                        catch (InterruptedException e)
                        {}
                    }


                }
            });
            thread.start();
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();


        return super.onStartCommand(intent, flags, startId);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy()
    {
        // TODO: Implement this method
        thread.stop();
        super.onDestroy();
    }

}

This code below is equivalant to above.

In Activity

    new Thread(new Runnable()
        {
             @Override
             public void run()
             {
                   while(!isInterrupted()){
startService(new Intent(MainActivity.this, WiFiCheck.class)); 
                       Thread.sleep(10000L);  
                   }
             }
        }).start();

Equivalent code #2:

public class WiFiCheck extends IntentService
{
  public WiFiCheck() {
     super("WiFiCheck");
 }
 @Override
 protected void onHandleIntent(Intent intent)
 {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

 }
@Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Let it continue running until it is stopped.
            startForeground(1, new Notification());
            Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

       super.onStartCommand(intent, flags, startId);
      return START_STICKY;

        }
 }

To add words, starting a service does not mean it is repeatedly called by the system, but rather it can live longer without UI. Actually its context is continued until you manually call stopSelf() or any component calls stopService() on your service.

KYHSGeekCode
  • 1,068
  • 2
  • 12
  • 30
  • Could you please post some comment here about why this was downvoted? I don't want to make the mistake again and want to improve my post. If it is an exact duplicate of @V.Kalyuzhnyu's answer, (I am so sorry V.Kalyuzhnyu!) I would rather suggest edit to him. Or if my answer is totally wrong what point(If both answers are wrong, sorry moderators, I just upvoted V.Kalyuzhnyu's and can't undo it, though it seems that only mine is wrong)? – KYHSGeekCode Apr 20 '18 at 09:22
  • @GajuKollur Nope.. I meant that you should call StartService twice, but returning Start_sticky is irrelevant. – KYHSGeekCode Apr 20 '18 at 12:31
  • @GajuKollur For example, any time you call StartService() the toast will show up. Also the toast will show up when you force-stop it after your service had returned START_STICKY, because the system will automatically restart your service. – KYHSGeekCode Apr 20 '18 at 12:34
  • @GajuKollur In this case, two conditions call your onStartCommand: 1. Whenever you call startService. 2. You returned START_STICKY in onStartCommand, and your service was crashed or killed -> When thesystem restarts your service. – KYHSGeekCode Apr 20 '18 at 12:39
  • @GajuKollur If you meant you wanted to show toast consistently try my edited answer. – KYHSGeekCode Apr 21 '18 at 00:36
0

YES.., You just have to return START_STICKY as KYHSGeekCode suggested. It was down voted, but it is correct answer. So i up voted it back. Thank you

sandhya sasane
  • 1,334
  • 12
  • 19
  • just take care if you are trying it on android 8.0 or above then use startforeground – sandhya sasane Apr 20 '18 at 11:05
  • even after using START_STICKY onstartCommand calling only once ..i am testing on kitkat – Gaju Kollur Apr 20 '18 at 12:02
  • @GajuKollur Ok I read yours. Bu I think you misunderstood my answer. Returning START_STICK is irrelevant..... – KYHSGeekCode Apr 20 '18 at 15:31
  • @KYHSGeekCode Dear down voter will you please tell me how returning START_STICKY is irrelevant? You are misusing the right of down vote – sandhya sasane Apr 21 '18 at 07:26
  • @KYHSGeekCode, He wants to run onStartCommand repeatedly.., For which START_STICKY is the only way.. I do not see anything wrong in my answer – sandhya sasane Apr 21 '18 at 07:28
  • @KYHSGeekCode, Please suggest any clues if you can over my question here https://stackoverflow.com/questions/49953562/run-service-again-but-once-its-current-execution-is-finished – sandhya sasane Apr 21 '18 at 08:30
  • @GajuKollur, import android.app.IntentService; is you problem. What intentservice required thing doing in your service...?? It must not be there.... – sandhya sasane Apr 21 '18 at 08:36
  • @sandhyasasane To see if I had downvoted, visit here. https://stackoverflow.com/help/privileges/vote-down . Neither did i downvoted nor upvoted. – KYHSGeekCode Apr 21 '18 at 10:03
  • 1
    @sandhyasasane And not "must not", but rather "need not" that import statement. – KYHSGeekCode Apr 21 '18 at 10:04