Как создать сервис Forground Никогда не останавливаться, когда приложение неактивно - PullRequest
0 голосов
/ 08 июня 2018

Я создал одно приложение, в котором я хочу запустить службу. Первый раз откройте приложение. Когда приложение находится на переднем плане Каждые 5 или 10 минут Локальное уведомление получено. Но уведомление получено только тогда, когда приложение активно или Недавнее приложение. Когда удаляются последниеПриложение не получает уведомление. Я хотел, чтобы эта служба продолжала работать на устройстве.

Пример кода созданной службы и запуска служб: Запустите службу:

    Intent i=new Intent(MainActivity.this,MyService.class);       
    startService(i);

Служба:

    public class MyService extends Service {
    final static String TAG = MyService.class.getName();
    ReceiverCall receiverCall;


    private static final int NOTIFICATION_ID = 1;

    MyService (){
        super();
        }
    class Mythread implements Runnable {
        int service_id;

        Mythread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {
            int i = 0;
            synchronized (this) {
               // while (i < 10) {
                    try {
                        wait(2500);
                        i++;
                        processStartNotification(String.valueOf(i));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
               // }
            }
        }
    }

    @Override
    public void onCreate() {
         receiverCall= new ReceiverCall();
            super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        super.onDestroy();
        Toast.makeText(getApplicationContext(), "Service Task destroyed", Toast.LENGTH_LONG).show();


        Intent myIntent = new Intent(getApplicationContext(), MyService.class);
        startService(myIntent);



    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent myIntent = new Intent(getApplicationContext(), MyService.class);
        startService(myIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

      Thread thread = new Thread(new Mythread(startId));
        thread.start();

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private void processStartNotification(String s) {
        // Do something. For example, fetch fresh data from backend to create a rich notification?

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("Scheduled Notification")
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.colorAccent))
                .setContentText(" Notification Service"+s)
                .setSmallIcon(R.drawable.ic_launcher_background);
        builder.setDeleteIntent(receiverCall.getDeleteIntent(this));
        final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());

    }
    }

BroadcastReceiver Class :

    public class ReceiverCall extends BroadcastReceiver {
    private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
    private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
    private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stops", "Ohhhhhhh");
        context.startService(new Intent(context, MyService.class));
    }
    public static PendingIntent getDeleteIntent(Context context) {
        Intent intent = new Intent(context, ReceiverCall.class);
        intent.setAction(ACTION_DELETE_NOTIFICATION);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    }   

Декларация манифеста:

      <service
            android:name=".MyService"
            android:exported="true"
            android:stopWithTask="false"></service>

         <receiver android:name=".ReceiverCall">
            <intent-filter>
                <action android:name="com.servicesex" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

Можно ли запускать этот сервис всегда, как в случае паузы приложения и всего остального.Через некоторое время мое приложение переходит в режим паузы, а службы также приостанавливаются или останавливаются.Так как я могу запустить этот сервис в фоновом режиме и всегда.

Ответы [ 2 ]

0 голосов
/ 08 июня 2018

Вы можете использовать Alarm Manager, чтобы запланировать будущую задачу на определенное время и установить ее снова при запуске. Пример использования или новый API WorkManager , который может помочь запустить задачу, даже если приложение было убито.

Но я думаю, что это плохая практика, чтобы поддерживать службу, когда вашприложение удаляется из системной задачи, поскольку служба продолжает потреблять память и электроэнергию.Лучше следуйте этому Руководству

0 голосов
/ 08 июня 2018
public class MyService extends Service {
static final int NOTIFICATION_ID = 100;

public static boolean isServiceRunning = false;

@Override
public void onCreate() {
    super.onCreate();
    startServiceWithNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
        startServiceWithNotification();
    }
    else stopMyService();
    return START_STICKY;
}

// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
    isServiceRunning = false;
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Used only in case of bound services.
    return null;
}


void startServiceWithNotification() {
    if (isServiceRunning) return;
    isServiceRunning = true;

    Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
    notificationIntent.setAction(C.ACTION_MAIN);  // A string containing the action name
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setTicker(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.my_string))
            .setSmallIcon(R.drawable.my_icon)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(contentPendingIntent)
            .setOngoing(true)
//                .setDeleteIntent(contentPendingIntent)  // if needed
            .build();
    notification.flags = notification.flags | Notification.FLAG_NO_CLEAR;     // NO_CLEAR makes the notification stay when the user performs a "delete all" command
    startForeground(NOTIFICATION_ID, notification);
}

void stopMyService() {
    stopForeground(true);
    stopSelf();
    isServiceRunning = false;
}
}

C = - это строки, которые должны начинаться с имени пакета

...