简体   繁体   中英

How to replace sendStickyBroadcast in Android?

As you know, sendStickyBroadcast method is now deprecated . How to replace it?

Of course I can use sendBroadcast but then it will be not sticky.

You could use an event bus, the following are some of the most used libraries. - https://github.com/greenrobot/EventBus - http://square.github.io/otto/ - https://blog.kaush.co/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/ (how to use Rx as an event bus)

Another approach would be to create a class that listens to the broadcast and then stores the last state that it retrieved. In my opinion, this approach would not be ideal though.

Maybe one can use a JobScheduler to
schedule a periodic job,
which will send broadcasts.

The "keep alive" service, which will send periodoc broadcasts.

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;


import static my.UtilsLocation.PACKAGE_NAME;

/**
 * JobService to be scheduled by the JobScheduler.
 * start another service
 */
public class KeepAliveBroadcastJobService extends JobService {

    public static final String INTENT_ACTION_KEEP_ALIVE = PACKAGE_NAME + ".action.KEEPALIVE";

    @Override
    public boolean onStartJob(JobParameters params) {
        // send recurring broadcast
        final Intent intent = new Intent(getApplicationContext());
        intent.setAction(INTENT_ACTION_KEEP_ALIVE);
        sendBroadcast(intent);
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }

}

A util, to periodically schedule the keep alive job.

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;

import java.util.concurrent.atomic.AtomicBoolean;

public class UtilsKeepAlive {

    private static final String TAG = UtilsKeepAlive.class.toString();

    private static AtomicBoolean isKeepAliveOn = new AtomicBoolean(false);

    private static final int INTERVAL_MILLIS = 600000; // 10 min
    private static final int FLEX_MILLIS = 60000; // 1 min

    public static void enableKeepAlive(Context context) {
        // if already on
        if (isKeepAliveOn.get()) return;

        Log.i(TAG, "Keep alive job scheduled");

        ComponentName serviceComponent = new ComponentName(context, KeepAliveBroadcastJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); //Require any network
        builder.setRequiresCharging(false);
        builder.setPeriodic(INTERVAL_MILLIS, FLEX_MILLIS);

        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());

        //we have scheduled the keep alive
        isKeepAliveOn.set(true);
    }
}

The periodic "keep alive" job - can be eg scheduled in a broadcast, on BOOT_COMPLETED.

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "BroadCastReceiver got the location.");

    final String action = intent.getAction();

    switch (action) {
        case INTENT_ACTION_BOOT_COMPLETED:
            Log.i(TAG, "Received a BootCompleted");
            UtilsKeepAlive.enableKeepAlive(context);
            break;

I have used this tutorial explaining the JobScheduler: https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html

This is Google's explanation to why Sticky Broadcasts was deprecated.

Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM