Skip to content Skip to sidebar Skip to footer

How To Use Threads And Services. Android

I have three classes. 'actone', 'acttwo' and 'actthree'. I have a button in 'actone'. When I click that button, I want to be able to run 'acttwo' on a different thread in the backg

Solution 1:

There are two ways to do this, use a Singleton or use a Service (as you mentioned). Personally I don't like the singleton patterns very much and a service follows the Android patter much better. You will want to use a bound Service which is bound to your Applications context (actone.getActivityContext()). I have written a similar answer to this question however you will want to do something like:

publicclassBoundServiceextendsService {
    privatefinalBackgroundBinder_binder=newBackgroundBinder();

    //Binding to the Application context means that it will be destroyed (unbound) with the apppublic IBinder onBind(Intent intent) {
        return _binder;
    }

    //TODO: create your methods that you need here (or link actTwo)// Making sure to call it on a separate thread with AsyncTask or ThreadpublicclassBackgroundBinderextendsBinder {
        public BoundService getService() {
            return BoundService.this;
        }
    }
}

Then from your actone (I'm assuming Activity)

publicclassactoneextendsActivity {
    ...

    publicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...

        Intentintent=newIntent(this, BoundService.class);
        bindService(intent, _serviceConnection, Context.BIND_AUTO_CREATE);
    }

    privateServiceConnection_serviceConnection=newServiceConnection() {
        @OverridepublicvoidonServiceConnected(ComponentName className, IBinder service) {
            BoundService.BackgroundBinderbinder= (BoundService.BackgroundBinder)service;
            _boundService = binder.getService();
            _isBound = true;

            //Any other setup you want to call. ex.//_boundService.methodName();
        }

        @OverridepublicvoidonServiceDisconnected(ComponentName arg0) {
            _isBound = false;
        }
    };
}

Then from ActOne and ActThree (Activities?) you can get the bound service and call methods from actTwo.

Solution 2:

You can use a AsyncTask for that. Services are not really useful (much more to code).

Post a Comment for "How To Use Threads And Services. Android"