public class IamService extends Service { public final static String EXTRA_TYPE = "type"; public final static String EXTRA_UID = "uid"; public final static int GET_TAXI = 98; public final static int GET_PASSENGER = 99; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getExtras() != null) { int type = intent.getExtras().getInt(EXTRA_TYPE); Log.i("TAG", "type is " + type); } return Service.START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } }
โค้ดภายใน Activity
public void startGetData(int type) { Calendar cal = Calendar.getInstance(); service = new Intent(this, TaxiMateService.class); service.putExtra(TaxiMateService.EXTRA_TYPE, type); intent = PendingIntent.getService(this, 0, service, PendingIntent.FLAG_UPDATE_CURRENT); // PendingIntent.FLAG_UPDATE_CURRENT) คือ ให้ update extra ทุกครั้งที่เรียก Service alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5 * 1000, intent); } public void stopGetData() { if (alarm != null) { alarm.cancel(intent); } } public void stopService() { if (service != null) { stopService(service); } }