user1118764
user1118764

Reputation: 9835

Accessing a variable of a Service

I have an Android Activity called Main that calls a Service called MainService as follows:

Intent intent = new Intent(this, MainService.class);
if(MainService.getInstance() == null){
  Log.d(TAG, "Calling MainService");
  startService(intent);
}

MainService maintains a variable during its lifetime that I wish to access in Main later on. How do I do this?

Thanks.

Upvotes: 3

Views: 6706

Answers (2)

Alex Shutov
Alex Shutov

Reputation: 3282

Yes, you can access variables inside service, but for that you have to bind to this service first. After that, use accessors for getting or setting variables or call any other method of the service. See https://developer.android.com/guide/components/bound-services.html

Upvotes: 3

Jagjit Singh
Jagjit Singh

Reputation: 1969

You can bind the service and can have the service instance forever. Below sample code will help you:-
Service Class

public class MusicService extends Service {

    MyBinder binder=new MyBinder();
    MusicService services;
    static  Context context;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context=getApplicationContext();

        MediaPlayer mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.yaar);
        mPlayer.start();
    }

    public class MyBinder extends Binder
    {
        public MusicService getServiceSystem()
        {
            return MusicService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

Activity

public class MainActivity extends AppCompatActivity {

    MusicService services;

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

        ServiceConnection connection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
              MusicService.MyBinder binderr=(MusicService.MyBinder)service;
                services=binderr.getServiceSystem();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        Intent intent= new Intent(this, MusicService.class);
        startService(intent);
    }

}

You can then use service anywhere you need in activity. Hope it helps.

Upvotes: 5

Related Questions