2012-03-27 81 views
1

我遇到了我的應用的音樂播放問題。我在一個可以在整個應用程序中播放音樂的服務類中設置媒體播放器。但是,我遇到的問題是將屏幕從「選項」頁面再次更改爲主頁。Android:保存音樂狀態(初學者)

在選項類中,我有一個單擊的ToggleButton,它可以在單擊時打開和關閉音樂,並且我使用布爾值來確定ToggleButton是否自動開啓和關閉,具體取決於音樂是否正在播放。

但是,當用戶點擊後退按鈕或保存按鈕(將它們發送回主頁時),即使音樂被選中爲「關閉」,音樂也會重新開始播放。

有人對我有什麼建議嗎?

服務類:

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) { 

    return null; 
} 


@Override 
public void onDestroy() { 

    super.onDestroy(); 
    if(mp!=null) { 
     mp.stop(); 
     mp.release(); 

    } 
    mp=null; 
} 

}

選項類別:

public class OptionsActivity extends Activity { 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 

     if (keyCode == KeyEvent.KEYCODE_BACK) { 
      Intent i = new Intent(OptionsActivity.this, MainActivity.class); 
      startActivity(i); 
      return true; 
     } 

     return super.onKeyDown(keyCode, event); 
    } 

    private boolean isMyServiceRunning(String serviceCanonicalClassName) { 
     ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
     for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
      if (serviceCanonicalClassName.equals(service.service.getClassName())) { 
       return true; 
      } 
     } 
     return false; 
    } 

    Intent i; // Handles MyMusicService.java 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.options); 



     final TextView tSound = (TextView) findViewById(R.id.textView2); 

     final Button saveBtn = (Button) findViewById(R.id.optSaveBtn); 
     final Button tblBtn = (Button) findViewById(R.id.tableBtn); 

     i=new Intent(this, MyMusicService.class); 

     final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref); 


     boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName()); 


     soundOption.setChecked(musicPlays); 


     if(musicPlays==true){ 

      tSound.setText("On"); 
     } 

     if(musicPlays==false) { 

      tSound.setText("Off"); 
     } 


     soundOption.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 

       // Perform action on clicks to control sound being on and off. 
       if(soundOption.isChecked()) { 

        Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show(); 
        startService(i); 
        Intent i = new Intent(OptionsActivity.this, OptionsActivity.class); 
        startActivity(i); 

       } 

       else { 

        if(stopService(i)==true){ 

         soundOption.setChecked(false); 
         stopService(i); 
         Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show(); 
         Intent i = new Intent(OptionsActivity.this, OptionsActivity.class); 
         startActivity(i); 

        } 
       } 
      } 

     }); 



     tblBtn.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 

       Intent tblView = new Intent(OptionsActivity.this, SQLView.class); 
       startActivity(tblView); 

      } 
     }); 



     saveBtn.setOnClickListener(new View.OnClickListener(){ 

      public void onClick(View v) { 

       Intent homePage = new Intent(OptionsActivity.this, MainActivity.class); 

       switch (v.getId()){ 

       case R.id.optSaveBtn: //Determine what will happen when the user presses the "Submit button". 
        boolean optionsWork = true; 
        try{ 

         String sound = tSound.getText().toString(); 

         optionsDB entry = new optionsDB(OptionsActivity.this); //Creating a new instance of MasterMind game 
         entry.open(); 
         entry.createOptionEntry(sound); //Passing both strings 
         entry.close(); 

        }catch (Exception e){ //Creating an error message if for some reason the app cannot transfer data to the Database. 

         Toast.makeText(OptionsActivity.this, "Error", Toast.LENGTH_SHORT).show(); 
        } 

        finally { //Creating an AlertDialog box when the user presses the Submit button. 

         if (optionsWork){ 

          Toast.makeText(OptionsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show(); 

         } 

        } 

        break; 

       } 

       startActivity(homePage); 
      } 
     }); 
    } 
} 

最後,家居類:

public class MainActivity extends Activity {  

Intent i; 

private boolean isMyServiceRunning(String serviceCanonicalClassName) { 
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
     if (serviceCanonicalClassName.equals(service.service.getClassName())) { 
      return true; 
     } 
    } 
    return false; 
} 


public void checkSound(){ 

boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName()); 

    if(musicPlays==true){ 

     //Do nothing 
    } 
    else { 

     stopService(i); 

    } 

} 

protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    //setting the layout 

    //Start Networking 
    //Intent net = new Intent(this, Networking.class); 
    //startService(net); 

    //Auto starts playing music on app launch. 
    i = new Intent(this,MyMusicService.class); 
    startService(i); 
    checkSound(); 


    final ImageView findGame = (ImageView) findViewById(R.id.btnFindGame); 
    final ImageView profile = (ImageView) findViewById(R.id.btnProfile); 
    final ImageView instructions = (ImageView) findViewById(R.id.btnInstructions); 
    final ImageView options = (ImageView) findViewById(R.id.btnOptions); 

    findGame.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainActivity.this, DrawActivity.class); 
      startActivity(intent); 
     } 
    }); 

    profile.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainActivity.this, WaitingActivity.class); 
      startActivity(intent); 
     } 
    }); 

    instructions.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainActivity.this, InstructionsActivity.class); 
      startActivity(intent); 
     } 
    }); 

    options.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainActivity.this, OptionsActivity.class); 
      startActivity(intent); 
     } 
    }); 

} 

//On app close, music stops playing. 
@Override 
protected void onDestroy() { 
    if (this.isFinishing()){ 
     super.onDestroy(); 
     stopService(i); 
     //finish(); 
    } 
} 

}

任何幫助將是非常讚賞,謝謝。

回答

2

當您創建主屏幕時,您也將再次啓動該服務。在您啓動媒體播放器的服務的'onStartCommand'中。這意味着,每次訪問主頁時,媒體播放器都會重新開始播放。

我建議不要把mp.start();放在'onStartCommand'中,而是放在它自己的函數中。然後在撥打startService(i);之後,您可以使用bindService()綁定到該服務,然後在您擁有的服務句柄上調用play()等函數。

當然,如果您要暫停歌曲而不是停止,您需要保存歌曲的位置,然後使用seekTo()在重新啓動服務時將歌曲移到正確的位置。

我建議你通過Android服務頁面herehere

+0

您好,謝謝爲了您的評論。 我不認爲你可以告訴我一個這樣的例子嗎?我一直在努力嘗試,並遇到一些問題。要麼它沒有播放或代碼中的錯誤。 – 2012-03-27 16:17:28

0

我認爲ü必須放置在啓動服務的一些支票上創建方法,你的家班讀書,

check if(your service is running) 
     { 
      if(mp is playing) 
      { 
       //do nothing 
      } 
     } 
    else 
     { 
     startservice(); 
     }