2016-05-16 122 views
0

我建立了一個小的應用程序基本上振動和播放上勾選複選框的MP3文件,但不知何故,音樂不會取消選中該複選框後停止:Android的媒體播放器並沒有停止對複選框

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE); 
     final CheckBox vibrateBoxStrong = (CheckBox) findViewById(R.id.checkPowerStrong); 

     final Handler handler = new Handler(); 

     final Runnable r = new Runnable() { 
      public void run() { 
       vibrator.vibrate(1000); 
       handler.postDelayed(this, 1000); 
      } 
     }; 

     vibrateBoxStrong.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
       @Override 
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { 
        MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.fansound1); 
        if(vibrateBoxStrong.isChecked()) { 
         handler.postDelayed(r, 100); 
         mediaPlayer.start(); 
        } else { 
         mediaPlayer.stop(); 
         handler.removeCallbacks(r); 
         vibrator.cancel(); 
        } 
       } 
      } 
     ); 
    } 
} 
+1

每次'CheckBox'改變它的選中狀態,您可以創建一個新的'MediaPlayer'實例,所以你打電話'停止()'對錯誤的實例。 –

+0

嗯好吧,我應該如何改變它來調用正確的對象? –

回答

-1

播放MP3

MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.aaanicholas); 

開始

mPlayer.start(); 

停止

mPlayer.stop(); 

在你的情況使用

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE); 
     MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.aaanicholas); 
     Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE); 
     final CheckBox vibrateBoxStrong = (CheckBox) findViewById(R.id.checkPowerStrong); 


     vibrateBoxStrong.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
       @Override 
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { 
        MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.fansound1); 
        if(vibrateBoxStrong.isChecked()) { 
         v.vibrate(1000);   // it will vibrate for 1000 milliseconds 
         mPlayer.start();   
        } else { 
         mPlayer.stop(); 

         vibrator.cancel(); 
        } 
       } 
      } 
     ); 
    } 
} 
+0

???這正是我所做的 –

+0

@AlexOxilg檢查我編輯的答案 –

+0

所以我不需要這個對象'mediaPlayer'? –