我創建了一個後臺服務,它定期打到我的服務器,但不幸的是,後臺服務在一段時間後停止。安卓後臺服務在一段時間後停止
public class LocationService extends Service{
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
new DownloadFilesTask().execute("");
Toast.makeText(getApplicationContext(), "start", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
private class DownloadFilesTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(siteurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Intent myIntent = new Intent(getApplicationContext(), LocationService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager1.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent myIntent = new Intent(getApplicationContext(), LocationService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager1.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
}
使用作業程序器做你經常性的工作或前景的服務 – nomag
我不想前臺服務,我想後臺服務,我發信息給服務器上定期,但1-2小時後我的應用服務停止。請給我的解決方案,以便我的服務沒有停止通過android操作系統 –