简体   繁体   中英

Passing selected item of string array of urls in putExtra intent from activity to service

In my media player app, I am passing selected url to my Service class like this from my list view.

 Resources res = getResources();
 String[] links = res.getStringArray(R.array.links);
 String url = links[position];

 if (playing) {
     Intent i = new Intent(MainActivity.this, MpService.class);
     stopService(i);
 }

 playing = true;

 Intent start = new Intent(MainActivity.this, MpService.class);
 start.putExtra("media", url);
 startService(start);

But at my playpause toogle button i'm restarting the service where i need to keep the same url behind which is selected before. Here is the toogle function:

private void togglePlayPause() {
    if (playing) {
        playing = false;
        nowplaying.setText("Offline");
        mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
        Intent i = new Intent(MainActivity.this, MpService.class);
        stopService(i);
    } else if (!playing){
        playing = true;
        Intent i = new Intent(MainActivity.this, MpService.class);
        i.putExtra("media",//here is what i'm not getting);
        startService(i);
        nowplaying.setText("Now Playing");
        mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);
    }
}

Kindly help in how to achieve this? Its my first app and this is very confusing.

In Activity:

Intent start = new Intent(MainActivity.this, MpService.class);
 start.putExtra("media", url);
 startService(start);

In Service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getExtras() != null){
        String mediaUrl = intent.getStringExtra("media", null);
    }
}

For Passing String array follow this: In Activity:

Intent intent = new Intent(this, ClassB);
String[] myStrings = new String[] {"test1", "test2"};
intent.putExtra("strings", myStrings);
startActivity(intent);

In Service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getStringArrayExtra() != null){
String[] myStrings = intent.getStringArrayExtra("strings");    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM