Question

I'm having to move my MediaPlayer outside of the MainActivity and into a Service.

My code currently has all of the buttons hosted within the MainActivity however when the button is pressed, an ID (resId) is assigned to it so that I can use general MediaPlayer code to play any button that is pressed.

For example:

public void onClick(View v) {
    int resId;
    switch (v.getId()) {
    case R.id.button_1:
        resId = R.raw.birdsong;
        break;
    case R.id.button_2:
        resId = R.raw.brown_noise;
        break;
    case R.id.button_3:
        resId = R.raw.car_journey;
        break;
    case R.id.button_4:
        resId = R.raw.crackling_fire;
        break;
    case R.id.button_5:
        resId = R.raw.electrifying_thunderstorms;
        break;
    case R.id.button_6:
        resId = R.raw.fan;
        break;
    case R.id.button_7:
        resId = R.raw.jungle_river;
        break;
    case R.id.button_8:
        resId = R.raw.pig_frogs;
        break;
    case R.id.button_9:
        resId = R.raw.pink_noise;
        break;
    case R.id.button_10:
        resId = R.raw.predawn;
        break;
    case R.id.button_11:
        resId = R.raw.rain;
        break;
    case R.id.button_12:
        resId = R.raw.shower;
        break;
    case R.id.button_13:
        resId = R.raw.snoring;
        break;
    case R.id.button_14:
        resId = R.raw.whale_song;
        break;
    case R.id.button_15:
        resId = R.raw.white_noise;
        break;
    default:
        resId = R.raw.birdsong;
        break;
    }
    // Release any resources from previous MediaPlayer
    if (mp != null) {
        mp.release();
    }
    // Create a new MediaPlayer to play this sound
    mp = MediaPlayer.create(this, resId);
    mp.setLooping(true);    
    mp.start();

How would I be able move the code to a service, but still have the buttons on the MainActivity? The service will not recognise the resId associated with the button as all of the code will be in MainActivity and so will not play the correct sound.

No correct solution

OTHER TIPS

You could write a ContentProvider and send your own custom names/identifiers to the service for it to access the resources of the activity's app through the ContentProvider using the supplied name. Read up on them here: http://developer.android.com/guide/topics/providers/content-providers.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top