我的服务不会停止

时间:2013-12-13 07:26:30

标签: android

我正在使用服务来运行我的服务器,但是当我调用stopservice()时。它只是重新启动服务没有做任何事情。任何帮助都会被appriciated。请告诉我如何在服务停止时删除服务通知。 这是我的服务代码:

{新密码}

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);
        }
    }



        }

2 个答案:

答案 0 :(得分:1)

如果您想停止Service班级中的Service,请致电

服务类

中的

stopSelf()

或者如果你想阻止它从其他Activity或类改变这两行这样的话......

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

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

答案 1 :(得分:0)

如果您不想重新启动,

return START_NOT_STICKY;

最后

@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);