Запуск службы с сигналом тревоги после закрытия приложения - PullRequest
0 голосов
/ 28 мая 2018

Я делаю простое приложение, которое состоит из службы, которая выдает уведомление несколько раз в день.Я пытаюсь сделать это с сигналом тревоги.Все работает отлично, если я не закрываю приложение.Однако, если я закрываю приложение при срабатывании приемника, я получаю сообщение «приложение перестало работать» или что-то в этом роде.

Я бродил, если это так, потому что служба не может работать без активности приложения иличто-то?Есть идеи?

Вот мой код:

Получатель:

public class AlarmReceiver extends BroadcastReceiver {
    public static final int REQUEST_CODE = 12345;
    public static final String ACTION = "com.ddimitrovd.hap4eapp4e.alarm";

    // Triggered by the Alarm periodically (starts the service to run task)
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MainIntentService.class);
        i.putExtra("foo", "bar");
        context.startService(i);
    }
}

Вот услуга:

public class MainIntentService extends IntentService {

    int noteID = 1;
    String chanelID;

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

    @Override
    protected void onHandleIntent(Intent intent) {
        chanelID = getString(R.string.channel_ID);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

        // Do the task here
        createNotificationChannel();
        popNotif();
    }

    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    }

    private void popNotif() {
        // Create an explicit intent for an Activity in your app
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, chanelID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("My notification")
                .setContentText("Hello World!")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                // Set the intent that will fire when the user taps the notification
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        notificationManager.notify(noteID, mBuilder.build());
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(chanelID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

Я уверен, чтоТревога вызывает приемник.

Спасибо!

1 Ответ

0 голосов
/ 28 мая 2018

Я думаю, что нашел проблему.Я считаю, что мой IntentService не может выполняться комплексно, потому что процесс BroadcastReceiver убит, прежде чем он сможет это сделать.Подробнее здесь .Я просто вставил свое уведомление в получатель, но я думаю, что лучшим решением было бы запустить другой поток или поставить его асинхронным.

...