user2368731
user2368731

Reputation: 1

Service is running after app is stop

I am trying to run a service, whem i stop my app that service still run means it's continuing its task. What is the way to stop service when we stop our app? Plese help me how can i stop this service. One more thing is also there if i use intent in this class to move back to that class from where service is calling i moved back but when i press back button on emulator to go back then it display that service screen also.

I am showing the code of service class

public class SetMovableBG_Inbuilt_SetImage extends Service
{
    Timer mytimer;
    int interval = 2000;
    int interval1 = 4000;
    Drawable drawable;
    WallpaperManager wpm;
    int prev = 0;
    int numImage;
    private ArrayList<Integer> imgId;

    @Override
    public void onCreate()
    {
        super.onCreate();
        mytimer = new Timer();
        wpm = WallpaperManager.getInstance(this);
    }

    // here i am geting intent from the class from where i am calling this class.
    //everything  works fine but service not stops even after stop the app
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        imgId = intent.getIntegerArrayListExtra("ImgId");
        numImage = imgId.size();
        mytimer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                if ( prev >= numImage )
                {
                    prev = 0;
                }
                try
                {
                    wpm.setResource(imgId.get(prev));
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                }
                prev++;
            }
        }, interval, interval1);
        return super.onStartCommand(intent, flags, startId);
    }

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

Upvotes: 0

Views: 939

Answers (1)

stinepike
stinepike

Reputation: 54732

you can use Service.stopService method to stop the service from other component like activities. You can use Service.stopSelf method to stop the service from the service itself. according to doc

A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. So, the service must stop itself by calling stopSelf() or another component can stop it by calling stopService().

To know more about Services see here

Upvotes: 2

Related Questions