I have an game application that users play between devices. I have added a Service that intermittently checks if a remote player has made a move and then notifies the local user that it’s now his or her turn. I use this code in the games’s main activity to fire off a the service based on the user’s preferences for “intermittent”
GAME
if (Settings.AlarmInterval != 0) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, (int)( Settings.AlarmInterval/1000/60));
Intent myIntent = new Intent(mCtx, WakeCheck.class);
pendingIntent = PendingIntent.getService(mCtx, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)mCtx.getSystemService(mCtx.ALARM_SERVICE);
alarmManager.cancel(pendingIntent); // cancel any previous alarms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), Settings.AlarmInterval, pendingIntent);
}
This works just fine. However, even if the local user is currently playing
the game the service wakes up and checks to see if a move has been played. I’d like for
the user to be notified only when the game is NOT currently being played.
How can I detect within my WakeCheck service, that the game is on and running and there’s no need to check remote plays?
SERVICE
public class WakeCheck extends Service {
private triDbAdapter mDbHelper;
private static final int CHALLENGE = -2;
@Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mDbHelper.close();
//Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Cursor c;
triDbAdapter mDbHelper = new triDbAdapter(this.getApplicationContext());
mDbHelper.open();
ServerCommunication sComm = new ServerCommunication(this.getApplicationContext());
c = mDbHelper.fetchAllGames();
Log.d("WAKE","Checking Game Status");
<snip>
}
Somebody presented this idea at Google I/O this year… When your gaming activity goes to foreground (onResume() for example), you set a boolean value in SharedPreferences to true to indicate that the user is playing. The WakeCheck will read this value and if it is true, it will not have to check remote plays. When the gaming activity goes to background (e.g., onPause()), it sets the value to false to communicate to WakeCheck that it needs to check the remote plays.