Я хочу, чтобы моя служба работала даже после завершения приложения. Он продолжал поддерживать работу и не перезапускался. Я знаю, что это может быть достигнуто во многих приложениях при загрузке файла, служба продолжает работать бесперебойно все, я хочу, чтобы достичь того же кодаЗагрузите файл в службу (Android)
Sample, чтобы понять, о чем идет речь
public class CacheFile extends Service {
Context context;
NotificationManager mNotificationManager;
int id = 100;
@Override
public void onCreate() {
context = this;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
toDownLoad();
return super.onStartCommand(intent, flags, startId);
}
public void toDownLoad() {
final NotificationCompat.Builder mBuilder;
Intent deleteIntent = new Intent(this, ClickNotification.class);
PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_menu_upload)
.setContentTitle("Uploading Media...")
.setTicker("Starting uploads")
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Пауза", pendingIntentCancel)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Отмена", pendingIntentCancel);
Intent notificationIntent = new Intent(this, MyActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setProgress(id, 0, true);
new Thread(
new Runnable() {
@Override
public void run() {
int incr;
for (incr = 0; incr <= 100; incr+=5) {
mBuilder.setProgress(100, incr, false);
mNotificationManager.notify(id, mBuilder.build());
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) { }
}
mBuilder.setContentText("Download complete")
.addAction(0, null, null)
.addAction(0, null, null)
.setProgress(0, 0, false);
mNotificationManager.notify(id, mBuilder.build());
}
}
).start();
mNotificationManager.notify(id, mBuilder.build());
}
@Override
public void onDestroy() {
mNotificationManager.cancelAll();
super.onDestroy();
}
}
Нет, он перезапускается. Если эта услуга используется как аудиоплеер, то после закрытия приложения служба перезапустится, и будет видно, что песня начала воспроизводиться снова, во многих приложениях музыка продолжает воспроизводиться. –
. Здесь цитата из официального doc: «Существует две причины, по которым служба может запускаться системой. Если кто-то вызывает Context.startService(), тогда система будет извлекать сервис (создавая его и вызывая его метод onCreate(), если это необходимо), а затем вызывает его onStartCommand (Intent, int, int) с аргументами, предоставленными клиентом. Служба в этот момент продолжит работу до вызова Context.stopService() или stopSelf(). " – issathink