我有一个声音文件在服务上循环运行。
启动服务的活动也有一个按钮。当我按下按钮时,我希望服务中的声音文件停止播放,即终止服务。到目前为止,当我调用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();
}
}