Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have made your Mediaplayer instance dependent on the Activity. So when Activity gets restarted, onCreate() gets called again and the music restarts. If you want to continue playing music, take the mp out of any Activity instance and put it inside a Service. Then start the Service from your MainActivity and let it play the music unless you stop the Service.</p> <pre><code> public class MainActivity extends ListActivity { /** Called when the activity is first created. */ Intent i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); i=new Intent(this, MyMusicService.class); final ToggleButton togglebutton =(ToggleButton)findViewById(R.id.toggleButton1); togglebutton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks if (togglebutton.isChecked()) { Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_SHORT).show(); startService(i); } else { stopService(i); Toast.makeText(MainActivity.this, "Not checked", Toast.LENGTH_SHORT).show(); } }}); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopService(i); } } </code></pre> <p>The service is this :</p> <pre><code> public class MyMusicService extends Service { MediaPlayer mp; @Override public int onStartCommand(Intent intent, int flags, int startId) { mp = MediaPlayer.create(this, R.raw.song); mp.start(); mp.setLooping(true); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(mp!=null) mp.release(); mp=null; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload