保存音乐状态

时间:2012-03-27 13:08:33

标签: android service state media

我的应用音乐播放存在问题。我在一个服务类中设置了媒体播放器,它可以在整个应用程序中播放音乐。但是,我遇到的问题是将屏幕从“选项”页面再次更改为主页时。

在选项类中,我有一个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 个答案:

答案 0 :(得分:2)

当您创建主屏幕时,您也将再次启动该服务。在服务的“onStartCommand”中,您正在启动媒体播放器。这意味着每次进入主页时,媒体播放器都会重新开始播放。

我建议不要将mp.start();放在'onStartCommand'中,而是放在自己的函数中。然后在调用startService(i);后,您可以使用bindService()绑定到服务,然后在您拥有的服务句柄上调用play()等函数。

当然,如果您暂停播放歌曲而不是停止播放,则需要保存歌曲的位置,然后在重新启动服务时使用seekTo()将歌曲移动到正确的位置。

我建议您阅读Android服务页面herehere

答案 1 :(得分:0)

我认为你必须在你的家庭班上使用create method

检查启动服务
    check if(your service is running)
       {
          if(mp is playing)
             {
                //do nothing
             }
       }
    else
       {
         startservice();
       }