使用循环声音文件终止服务

时间:2013-05-30 00:56:06

标签: android loops audio service intentservice

我在服务的循环中运行了一个声音文件。

启动服务的活动也有一个按钮。当我按下按钮时,我希望服务中的声音文件停止播放,即终止服务。到目前为止,当我致电stopService()服务继续运行时,一直没有成功。

任何想法?感谢。

活动

public class AlarmPage extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm_page);
    TextView timeview = (TextView)findViewById(R.id.timefiled);
    final Button dismissButton =(Button)findViewById(R.id.dismissButton);
    Bundle b = getIntent().getExtras();
    String hrval = b.getString("HR");
    String minval = b.getString("MN");
    timeview.setText(hrval + ":" + minval);

    final Intent alarmring = new Intent(this, alarmringService.class);

    startService(alarmring);
    dismissButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub
            Intent alarmmenu = new Intent(getApplicationContext(),SetAlarmsActivity.class);
            startActivity(alarmmenu);

            System.out.println("Button:" + dismissButton.isPressed());
            stopService(alarmring);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.alarm_page, menu);
    return true;
}
}

服务

public class alarmringService extends IntentService{

public alarmringService(){
    super("alarmringService");
    // TODO Auto-generated constructor stub

}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub


    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.drawable.startrekcommsound);
    mp.setLooping(true);
    try {
        mp.prepare();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    mp.start();
}

}

1 个答案:

答案 0 :(得分:0)

我不明白为什么它不起作用,因为我不是专家,但为了解决你的问题,你可以使用意图。顺便说一下,IntentService在没有更多工作的时候会自行停止!

试试这个:发送给IntentService一个意图,并发出一个命令,说停止自己。 然后在onHandleIntent()中检查这是否是请求,并从stopSelf()内部调用Service

此外,我不知道MediaPlayer是如何工作的,但也许它有自己的主题,你也应该停止这个主题!