@romatregub

Как написать Service, который продолжит работать после закрытия приложения?

Третий день пытаюсь написать службу, которая будет работать после закрытия приложения.
Я написал службу, которая каждую секунду выводит новые оповещения, но при закрытии приложения она перестает выводит оповещения.
Перепробовал уже кучу вариантов.
Вот код службы, но при закрытии приложения она перестает выдавать оповещения.(использование foreground не выход!) Немного лишнего кода, так как создал с помощью android studio.

public class MyNotificationService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "com.example.eqvol.eqvola.Services.action.FOO";
private static final String ACTION_BAZ = "com.example.eqvol.eqvola.Services.action.BAZ";

// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.example.eqvol.eqvola.Services.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.example.eqvol.eqvola.Services.extra.PARAM2";

private static int NOTIFICATION_ID;


public MyNotificationService() {
    super("MyNotificationService");
}


/**
 * Starts this service to perform action Foo with the given parameters. If
 * the service is already performing a task this action will be queued.
 *
 * @see IntentService
 */
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
    Intent intent = new Intent(context, MyNotificationService.class);
    intent.setAction(ACTION_FOO);
    intent.putExtra(EXTRA_PARAM1, param1);
    intent.putExtra(EXTRA_PARAM2, param2);
    context.startService(intent);
    NOTIFICATION_ID = 0;
}

/**
 * Starts this service to perform action Baz with the given parameters. If
 * the service is already performing a task this action will be queued.
 *
 * @see IntentService
 */
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
    Intent intent = new Intent(context, MyNotificationService.class);
    intent.setAction(ACTION_BAZ);
    intent.putExtra(EXTRA_PARAM1, param1);
    intent.putExtra(EXTRA_PARAM2, param2);
    context.startService(intent);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_FOO.equals(action)) {
            final String param1 = intent.getStringExtra(EXTRA_PARAM1);
            final String param2 = intent.getStringExtra(EXTRA_PARAM2);
            handleActionFoo(param1, param2);
        } else if (ACTION_BAZ.equals(action)) {
            final String param1 = intent.getStringExtra(EXTRA_PARAM1);
            final String param2 = intent.getStringExtra(EXTRA_PARAM2);
            handleActionBaz(param1, param2);
        }
    }
}

/**
 * Handle action Foo in the provided background thread with the provided
 * parameters.
 */
private void handleActionFoo(String param1, String param2) {
    // TODO: Handle action Foo

    int i = 0;
    while(true) {

        i++;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendNotification("notification: " + i);
    }
}

/**
 * Handle action Baz in the provided background thread with the provided
 * parameters.
 */
private void handleActionBaz(String param1, String param2) {
    // TODO: Handle action Baz
    throw new UnsupportedOperationException("Not yet implemented");
}

private void sendNotification(String title) {

    Intent intent = new Intent(this, MenuActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            intent, 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentTitle(title)
                    .setStyle(new NotificationCompat.BigTextStyle())
                    .setSmallIcon(R.drawable.ic_menu_share);
    mBuilder.setContentIntent(contentIntent);
    NotificationManager mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    NOTIFICATION_ID++;
}

BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        Log.i("------------------", "my boot receiver startet");
        MyNotificationService.startActionFoo(arg0, null, null);
    }
};

@Override
public void onDestroy() {
    super.onDestroy();

    //Removing any notifications
    this.unregisterReceiver(this.mBatteryInfoReceiver);

    //Disabling service
    stopSelf();
}
  • Вопрос задан
  • 1709 просмотров
Пригласить эксперта
Ответы на вопрос 2
@romatregub Автор вопроса
Я давно разобрался как это работает, может кому поможет.
В общем в основном проблема была в том, что я обращался к статик переменным, которые были в моем приложении.
Частично решил проблему передавая значение в Intent.
Ответ написан
AlexanderYudakov
@AlexanderYudakov
C#, 1С, Android, TypeScript
https://developer.android.com/guide/components/ser...

The IntentService class does the following:
...
Stops the service after all of the start requests are handled, so you never have to call stopSelf().
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы