我想按小时在后台调用一项服务。
第一个问题是警报管理器工作不顺利。计时器很糟糕,有时早有时晚。
第二个问题是, RemoteServiceException : Context.startForegroundService() 然后没有调用 Service.startForeground() ,我不明白为什么我会得到这个异常
主要活动
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);
}
}
报警接收器
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);
}
}
}
呼叫服务
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"/>
抱歉我的英语很糟糕。感谢您的任何帮助或建议。
我不知道我该如何做不同的事情。我只是定期调用服务