我正在尝试使用AlarmManager每15分钟运行一次服务,如果按下停止按钮我试图取消警报并将其重置60分钟。
如果按下按钮,它似乎不会等待15分钟或60分钟。上次我按下停止按钮时,服务再次运行前等待了大约1分钟。
一般来说我是AlarmManager和android dev的新手,有人可以告诉我哪里出错了?
主要课程
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);
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
registerReceiver(uiUpdated, new IntentFilter("LOCATION_UPDATED"));
final Intent myIntent = new Intent(this, MyService.class);
final PendingIntent pintent = PendingIntent.getService(this, 0, myIntent, 0);
final AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
15*60*1000, pintent);
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) {
Log.d(TAG, "onTouchListener");
if(mediaPlayer.isPlaying())
{
//stop or pause your media player mediaPlayer.stop(); or mediaPlayer.pause();
mediaPlayer.pause();
mediaPlayer.seekTo(0);
stopService(myIntent);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
60*60*1000, pintent);
}
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.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);
}
}
MyService类
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(0);
}
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.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;
}
}
服务启动和停止的Logcat
11-07 16:21:45.469 1268-1268/com.jtechltd.networktraffic D/MyService﹕ onCreate
11-07 16:21:45.529 1268-1268/com.jtechltd.networktraffic D/MyService﹕ onStart
11-07 16:21:49.709 1268-1268/com.jtechltd.networktraffic D/MainScreen﹕ onTouchListener
11-07 16:21:49.799 1268-1268/com.jtechltd.networktraffic D/MainScreen﹕ onTouchListener
11-07 16:21:50.009 1268-1268/com.jtechltd.networktraffic D/dalvikvm﹕ GC_FOR_ALLOC freed 219K, 7% free 4418K/4704K, paused 50ms, total 62ms
11-07 16:21:50.089 1268-1268/com.jtechltd.networktraffic D/MyService﹕ onDestroy
11-07 16:22:45.499 1268-1268/com.jtechltd.networktraffic D/MyService﹕ onCreate
11-07 16:22:45.559 1268-1268/com.jtechltd.networktraffic D/MyService﹕ onStart
答案 0 :(得分:1)
setInexactRepeating / setRepeating方法的第二个参数(triggerAtMillis)是警报首先触发的时间。在此之前警报不会触发。当你将它设置为cal.getTimeInMillis()时,你将它设置为在同一时刻触发。
将其设置为(cal.getTimeInMillis()+ 15 * 60 * 1000)和(cal.getTimeInMillis()+ 60 * 60 * 1000)而不是cal .getTimeInMillis()并再试一次。
triggerAtMillis = cal.getTimeInMillis()+ intervalMillis
并且还使用setInexactRepeating而不是setRepeating。阅读文档以获取更多相关信息。