Search code examples
androidandroid-intentservicetimealarmmanager

Android - How to start and stop my service on specifed time?


I'm new to Android and I'm trying to make a simple app with a service, and I have some problems when I try to start my service. I'm using a built-in Android TimePicker for starting and ending time.

//Getting start time from timePicker
Time startTime = new Time(startTimePicker.getCurrentHour(), startTimePicker.getCurrentMinute(), 0);
// Creating intent
Intent intent = new Intent(ThisClass.this, ServiceClass.class);
// Setting pendingIntent for alarmManager
PendingIntent pendingIntent = PendingIntent.getService(ThisClass.this, 0, intent, 0);
// Creating new AlarmManager
AlarmManager startAlarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
startAlarm.set(AlarmManager.RTC, startTime.getTime(), pendingIntent);

The error is given in the last line: "Unable to start service Intent ( flg=0x4 cmp=com.example.mainActivity/. ServiceClass (has extras) ); not found". I don't know if this is important, but the Intent has a bundle with two arrays in it, though I didn't copy that part of the code.


Solution

  • This error probably occurs because you didn't declare your service class in the manifest. Make sure it is declared correctly (Here for example it's not declared in the application tag, so it causes this error)