My class MyService :

 public class MyService extends Service { IBinder mBinder; public static boolean status = true; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { someTask(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.e("MY_SERVICE", "onDestroy()"); new CheckThread().stop(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return mBinder; } public void someTask() { new CheckThread().start(); } public class CheckThread implements Runnable { Thread th; @Override public void run() { main(); } public void start() { th = new Thread(this); th.setPriority(Thread.NORM_PRIORITY); Log.e("CheckThread", "start()"); th.start(); } public synchronized void stop() { th = null; status = false; Log.e("CheckThread", "stop()"); notify(); } public void main() { while (status) { if ( ! status) stop(); boolean connect = Vars.connect; if ( ! connect) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setClass(MyService.this, Disconnect.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); status = false; stop(); } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } 

The Disconnect class is launched when the Socket connection is closed (the class does not inherit the Activity , functions with the UI are not available).

  new Thread(new Runnable() { public void run() { String str = ""; try { while ((str = in.readLine()) != null) { } } catch (IOException e) { } Vars.connect = false; } }).start(); 

Is it possible to somehow make it so that when you open the Disconnect class in MyService another active Activity closed so that only Disconnect active?

I did not find answers on how to close another Activity from the class inheriting from the Service .

    1 answer 1

    Only the Activity itself can complete itself (it can also be terminated by the OS).

    From the Service you must send an Activity signal to complete, upon receipt of which it will call finish() . This can be done in one of the ways described in this answer.

    I personally recommend LocalBroadcastManager .