我的应用程序应该检查警报是否需要在启动时关闭(播放MP3),之后应该每5分钟检查一次。
如果按下停止按钮,计时器应该是1小时,我遇到一个问题,在第一次按下按钮后5分钟内警报会再次响起(因为后台服务已经在等待与原来的5分钟计时器)我认为解决这个问题的方法是按下按钮时启动和停止服务,但我仍然得到相同的结果,5分钟后警报响起,但之后它有一个小时等待。
有人可以对此有所了解吗?
主要活动
public class MainScreen extends Activity {
private Thread thread;
private String CurrentString;
private int MaxCalls;
private int cph;
private int mht;
private String alarm;
private int timer =10000;
private MediaPlayer mediaPlayer;
private TextView MaxCallstxt,MHTtxt,CPHtxt;
private static final String TAG = "MainScreen";
private Date inTime,outTime,inputTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
registerReceiver(uiUpdated, new IntentFilter("LOCATION_UPDATED"));
final Intent myIntent = new Intent(this, MyService.class);
startService(myIntent);
mediaPlayer = MediaPlayer.create(MainScreen.this, R.raw.rescueme);
Button SoundButton = (Button)findViewById(R.id.stopButton);
SoundButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaPlayer.isPlaying())
{
//stop or pause your media player mediaPlayer.stop(); or mediaPlayer.pause();
mediaPlayer.pause();
mediaPlayer.seekTo(0);
Global g = new Global();
g.set_timer(3600000);
stopService(myIntent);
startService(myIntent);
}
return false;
}
});
MaxCallstxt = (TextView) findViewById(R.id.Maxcallstxt);
CPHtxt = (TextView) findViewById(R.id.CPHtxt);
MHTtxt = (TextView) findViewById(R.id.MHTtxt);
};
private BroadcastReceiver uiUpdated= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Long tsLong = System.currentTimeMillis();
Date mToday = new Date();
String ts = tsLong.toString();
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
String curTime = sdf.format(mToday);
try {
inputTime = sdf.parse(curTime);
inTime = sdf.parse("07:00");
outTime = sdf.parse("23:59");
}
catch(Exception e){
Log.e("log_tag", "Error in formatting " + e.toString());
}
String[] separated = intent.getExtras().getString("MaxCalls").split("\\|");
MaxCalls = Integer.parseInt(separated[0].toString()); // MaxCalls
cph = Integer.parseInt(separated[1].toString()); // cph
mht = Integer.parseInt(separated[2].toString()); // mht
alarm = separated[3].toString(); // Alarm = true/False
MaxCallstxt.setText("Max Calls : " + MaxCalls);
MHTtxt.setText("MHT : " + mht);
CPHtxt.setText("CPH : " + cph);
// alarm = "True";
if (alarm.equals("True"))
{
if(mediaPlayer.isPlaying())
{
}
else
{
if((inputTime.after(inTime) && inputTime.before(outTime)) || (MaxCalls == 0 && cph== 0 && mht ==0))
{
mediaPlayer.start();
}
}
}
}
};
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
// } catch (Exception e) {
// Log.d("InputStream", e.getLocalizedMessage());
//} catch (IOException e) {
// Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
return result;
}
// convert inputstream to String
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
后台服务
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
private Thread thread;
private String CurrentString;
private int timer =10000;
private boolean firsttime = true;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.rescueme);
player.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Global g = new Global();
timer=g.get_timer();
firsttime=g.get_firsttime();
if (firsttime == true)
{
g.set_firstime(false);
}else{
Thread.sleep(timer);
}
CurrentString =GET("http://example.com/example.aspx");
Intent i = new Intent("LOCATION_UPDATED");
i.putExtra("MaxCalls",CurrentString);
sendBroadcast(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
//REST OF CODE HERE//
}
}
}).start();
// player.start();
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
// } catch (Exception e) {
// Log.d("InputStream", e.getLocalizedMessage());
//} catch (IOException e) {
// Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
return result;
}
// convert inputstream to String
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
全局
public class Global extends Application
{
static public int timer;
static public boolean firsttime = true;
public int get_timer() {
if (timer==0)
{
timer = 300000;
}
return timer;
}
public void set_timer(int _timer) {
this.timer = _timer;
}
public boolean get_firsttime() {
return firsttime;
}
public void set_firstime(boolean _firsttime) {
this.firsttime = _firsttime;
}