在Android中停止服务

时间:2012-02-19 22:59:20

标签: android android-service

我有一个问题,似乎我无法停止主要活动开始的服务!

服务:

public class Player extends Service {

    @Override
    public void onCreate() { 
        Toast toast = Toast.makeText(this, "Buffering...Please wait!", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        String url = "...";
        final MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(url);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        toast.show();
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();

            }
        });




    }       
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onDestroy() {
    Toast toast2 = Toast.makeText(this, "Service stoped!", Toast.LENGTH_SHORT);
    toast2.setGravity(Gravity.CENTER, 0, 0);
    toast2.show();
    }

活动:

public class LoungeRadioActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       final Toast toast = Toast.makeText(this, "Tryng to stop service!", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);


        Button on = (Button) findViewById(R.id.button1);
        on.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
            startService(new Intent(LoungeRadioActivity.this, Player.class));

            }
        });
        Button off = (Button) findViewById(R.id.button2);
        off.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
            toast.show();
            stopService(new Intent(LoungeRadioActivity.this, Player.class));    

            }
        });

    }  
 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflate = getMenuInflater();
    inflate.inflate(R.menu.menu, menu );

    return true;
}
 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.item1)
        startActivity(new Intent(this, About.class));
    else {
        stopService(new Intent(LoungeRadioActivity.this, Player.class));
        finish();
    }

    return true;
}

}

1 个答案:

答案 0 :(得分:0)

尝试使用bindService并告诉服务停止那里的音乐。

另外,不要忘记调用unbindService