user3098412
user3098412

Reputation: 1

My service does not stop

i am using a service to run my server but when i call stopservice(). It does not do anything just restarts the service.Any help will be appriciated.and please tell me how to remove the notification of service when the service stops. this is my service code:

{New Code}

public class ServerService extends Service {
    private boolean isRunning = false;
    String port;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
          port = "10000";

        run(port);

        return (START_NOT_STICKY);
    }

    @Override
    public void onDestroy() {
        if (isRunning) {

            isRunning = false;
            stopForeground(true);
        }   }

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

    @SuppressWarnings("deprecation")
    private void run(String port) {
        if (!isRunning) {

            isRunning = true;

            Notification note = new Notification(R.drawable.ic_launcher,
                    "Server is successfully running",
                    System.currentTimeMillis());
            Intent i = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://localhost:" + port));


            PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

            note.setLatestEventInfo(this, "Ws Server", "Open http://localhost:"
                    + port, pi);

            startForeground(1337,note);
        }
    }



        }

Upvotes: 0

Views: 63

Answers (2)

venciallee
venciallee

Reputation: 775

if you don't want it restart,

return START_NOT_STICKY;

finally

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
      port = "10000";
   if(null != intent) {
       String action = intent.getAction();
       if(null != action && action.equals(STOPFOREGROUND)) {
           stopForeground(true);
       }
   }
   run(port);

   return (START_NOT_STICKY);
}

Intent m = new Intent (MainActivity.this,ServerService.class);
m.setAction(STOPFOREGROUND);
MainActivity.this.stopService(m);
Intent m1 = new Intent (MainActivity.this,ServerService.class);
MainActivity.this.stopService(m1);

Upvotes: 0

kalyan pvs
kalyan pvs

Reputation: 14590

If you want to stop the Service in the Service class itself then call

stopSelf() in the service class

or if you want to stop it from other Activity or class change this two lines like this..

Intent m = new Intent (MainActivity.this,ServerService.class);
m.stopService();

into

Intent m = new Intent (MainActivity.this,ServerService.class);
context.stopService(m);

Upvotes: 1

Related Questions