我的 IntentService 有问题。我需要我的服务在后台每 1 分钟访问一次网站中的 JSON 文件,而不打开应用程序(发出通知,我在 JSON 中收到)。它会这样做,但在 3-4 分钟后,它会抛出“ java.net.SocketTimeoutException: connect timed out ”错误,我仍然可以将域解析为 IP 地址,但我无法连接到网站,并且手机仍然有移动连接。所有网站都会发生同样的事情。
我的意图服务:
public class BackgroundService extends IntentService {
Runnable runnable = () -> new bgJob().execute();
Handler handler = new Handler();
DatabaseHandler db = new DatabaseHandler(this);
public BackgroundService() {
super("BackgroundService");
}
@Override
public void onCreate() {
super.onCreate();
runnable.run();
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent){
Log.d("BG_SERVICE","TASK REMOVED!");
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent = PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("BG_SERVICE","TASK DESTROYED!");
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent = PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
}
@Override
protected void onHandleIntent(Intent intent) {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakelockTag");
wakeLock.acquire();
runnable.run();
}
private class bgJob extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url("https://google.com/")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
int webresponse = response.code();
Log.d("Response","CODE: "+webresponse);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
handler.postDelayed(runnable, 60000);
}
}}
我在手机上使用 Android 7.0 并进行移动连接。