How to use threads and services. Android

2019-08-17 04:12发布

问题:

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 background, while my UI takes me to "actthree" and I can do whatever I want there while the code in "acttwo" keeps executing(I'll be doing uploading to a server in "acttwo" that is why I want it to keep running in the background).

if(v.getId() == R.id.button1){

//Start "acttwo" in background on another thread.

Intent i= new Intent(actone.this, actthree.class);
            startActivity(i);
}

How do I do that? Do I use a service? If yes, then what's the procedure? How to do that? I'm a newbie at Android. Please help. Thanks!

回答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:

public class BoundService extends Service {
    private final BackgroundBinder _binder = new BackgroundBinder();

    //Binding to the Application context means that it will be destroyed (unbound) with the app
    public 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 Thread

    public class BackgroundBinder extends Binder {
        public BoundService getService() {
            return BoundService.this;
        }
    }
}

Then from your actone (I'm assuming Activity)

public class actone extends Activity {
    ...

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...

        Intent intent = new Intent(this, BoundService.class);
        bindService(intent, _serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection _serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BoundService.BackgroundBinder binder = (BoundService.BackgroundBinder)service;
            _boundService = binder.getService();
            _isBound = true;

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

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            _isBound = false;
        }
    };
}

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



回答2:

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