I want to call a service in background by the hour.
first problem is alarm manager is not working smoothly. Timer is terrible, sometimes early sometimes later.
second problem is, RemoteServiceException : Context.startForegroundService() did not then call Service.startForeground() , I cant understand why I get this exception
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60 * 60 * 1000L, pendingIntent);
}
}
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onReceive(Context context, Intent intent) {
Intent downloadService = new Intent(context, CallService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(downloadService);
} else {
context.startService(downloadService);
}
}
}
CallService
public class CallService extends IntentService {
public CallService() {
super("");
}
public CallService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent workIntent) {
Log.d("Now : ", Calendar.getInstance().getTime().toString());
}
}
Manifest
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name=".AlarmReceiver"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".CallService"
android:exported="false"/>
Sorry for my terrible english. Thanks for any help or suggestion. I dont know how can I do different way. I just only call a service periodically