3

I like to exit my application immediately after starting a service.

The code below causes the activity to finish before the service is started. How do I set a listener to prompt me when the service is started?

btn  = (ImageButton) findViewById(R.id.button );
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(new Intent(MainActivity.this, MyService.class));

                //I want to exit the activity here.
                finish(); // this exits the activity before the service is started

            }
        });
Angel Koh
  • 12,479
  • 7
  • 64
  • 91
  • 1
    You can finish Your activity in service class when it is start.... – Arjun saini Aug 20 '16 at 06:23
  • I believe the above should work fine. Lame question - is the service registered in the manifest? – Shaishav Aug 20 '16 at 06:41
  • @Er.Arjunsaini that did the trick! I send a broadcast from the Service to the Activity; and then the activity calls finish() when it receives the broadcast. – Angel Koh Aug 20 '16 at 07:50

3 Answers3

2

The following are the codes I used, based on the proposal by @Er.Arjunsaini

on the ACTIVITY file, I register to listen for an "Exit App" broadcast.

private final BroadcastReceiver exitAppReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //activity exits when "exit app" broadcast received.
        finish();
    }
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //REGISTER TO LISTEN FOR THE BROADCAST
    LocalBroadcastManager.getInstance(this).
            registerReceiver(exitAppReceiver, new IntentFilter(getString(R.string.exit_app)));

    btn = (ImageButton) findViewById(R.id.my_button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) { 
            startService( new Intent(this, MyService.class));

        }
    }); 
}

@Override
public void onDestroy() {

    //UNREGISTER THE RECEIVER
    LocalBroadcastManager.getInstance(this).
            unregisterReceiver(exitFloatingWindowReceiver);
    super.onDestroy();
}

on the SERVICE file, I send an "Exit APP" broadcast.

@Override
public void onCreate() {
    super.onCreate();

    //... do the rest of the Service initializing 

    //CLOSE ACTIVITY
    LocalBroadcastManager.getInstance(this).
            sendBroadcast(new Intent(getString(R.string.exit_app)));
}
Angel Koh
  • 12,479
  • 7
  • 64
  • 91
0

check out ServiceConnection, onServiceConnected may be method you are looking for to call finish()

HERE you have example

Community
  • 1
  • 1
snachmsm
  • 17,866
  • 3
  • 32
  • 74
0

If you use bindService() instead of startService(), you can use the Message based communication system between Activity and Service. This is explained in this reference. At the end of the section there's a link to sample classes:

-MessengerService.java

-MessengerServiceActivities.java

Here an example of an Activity with 2 button, one for starting the Service and one for sending a message to the Service that will resend a message to the Activity to close it.

MainActivity.java

package com.pasquapp.brodcasttest01;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

public final static int WHAT_CLOSE_ACTIVITY=1;

private Button startServiceButton;
private Button closeButton;
private Messenger activityMessenger;
private Messenger serviceMessenger;
private MyServiceConnection serviceConnection;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    activityMessenger =new Messenger(new ActivityHandler());
    initView();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(serviceConnection!=null)
        unbindService(serviceConnection);
}

private void initView(){
    startServiceButton=findViewById(R.id.button_start_service);
    startServiceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startService();
        }
    });
    closeButton=findViewById(R.id.button_close);
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(serviceMessenger!=null){
                Message msg=Message.obtain();
                msg.replyTo=activityMessenger;
                msg.what=MyService.WHAT_CLOSE_ACTIVITY;
                try {
                    serviceMessenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

private class MyServiceConnection implements ServiceConnection{
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        serviceMessenger=new Messenger(iBinder);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        serviceMessenger=null;
    }
}

private void startService(){
    serviceConnection=new MyServiceConnection();
    bindService(new Intent(this,MyService.class),serviceConnection,BIND_AUTO_CREATE);
}

private class ActivityHandler extends Handler{
    @Override
    public void handleMessage(@NonNull Message msg) {
        int what=msg.what;
        switch (what){
            case WHAT_CLOSE_ACTIVITY:
                MainActivity.this.finish();
                break;
                default:
                    super.handleMessage(msg);
        }
    }
}}

MyService.java

package com.pasquapp.brodcasttest01;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import androidx.annotation.NonNull;

public class MyService extends Service {

    public static final int WHAT_CLOSE_ACTIVITY=1;

    private Messenger mMessenger;


    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMessenger=new Messenger(new ServiceHandler());

    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    private class ServiceHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            int what=msg.what;
            switch (what){
                case WHAT_CLOSE_ACTIVITY:
                    Messenger messenger=msg.replyTo;
                    Message closeMsg=Message.obtain();
                    closeMsg.what=MainActivity.WHAT_CLOSE_ACTIVITY;
                    try {
                        messenger.send(closeMsg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }

        }
    }
}