在android中重新启动服务确实会得到我的全局变量
我的应用程序应该检查闹钟启动时是否需要关闭(播放MP3),然后每5分钟检查一次 如果按下停止按钮,则计时器应为1小时,我遇到了一个问题,即在第一次按下按钮后5分钟内,警报会再次响起(因为后台服务已经在等待原来的5分钟计时器)我想解决这个问题的方法是在按下按钮时启动和停止服务,但我仍然得到相同的结果,5分钟后警报会响起,但之后需要等待一个小时 有人能解释一下吗 主要活动在android中重新启动服务确实会得到我的全局变量,android,android-activity,Android,Android Activity,我的应用程序应该检查闹钟启动时是否需要关闭(播放MP3),然后每5分钟检查一次 如果按下停止按钮,则计时器应为1小时,我遇到了一个问题,即在第一次按下按钮后5分钟内,警报会再次响起(因为后台服务已经在等待原来的5分钟计时器)我想解决这个问题的方法是在按下按钮时启动和停止服务,但我仍然得到相同的结果,5分钟后警报会响起,但之后需要等待一个小时 有人能解释一下吗 主要活动 public class MainScreen extends Activity { private Thread thread
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;
}
使用AlarmManager+SharedReferences我对Android开发人员很陌生。我只希望当httpget返回alarm=true时,警报就会响起。使用AlarmManger可以实现这一点吗?我不想为它设定特定的时间。如果httpget post返回的值为真(我需要每15分钟检查一次),则需要更多使用AlarmManager唤醒您的服务以执行某些操作。然后,它可以检查参数并执行任何必要的操作(包括不执行任何操作,设置警报以便稍后再次唤醒自己)。