Android JobScheduler检测到连接状态已更改

时间:2017-08-19 09:31:26

标签: android android-networking android-7.0-nougat android-jobscheduler jobservice

我想检测Android Nougat上已更改的连接状态。我在Android文档中读到了无法接收CONNECTIVITY_ACTION的文档。所以我尝试使用JobScheduler来改变连接状态。我是这样做的。

我像这样创建JobService

public class NetworkStateScheduler extends JobService {
    private Messenger jobServiceMessenger;
    public static final String TAG = "NetworkStateScheduler";

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.d(TAG, "onStartJob");
        sendMessage(jobParameters.getJobId(), NetworkInfo.State.CONNECTED);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.d(TAG, "onStopJob");
        sendMessage(jobParameters.getJobId(), NetworkInfo.State.DISCONNECTED);
        return true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        jobServiceMessenger = intent.getParcelableExtra(MESSENGER_INTENT_KEY);
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(MainActivity.START_SERVICE_FILTER));

        return START_NOT_STICKY;
    }

    private void sendMessage(int messageID, Object params) {
        if (jobServiceMessenger == null) {
            Log.d(TAG, "Service is bound, not started. There's no callback to send a message to.");
            return;
        }

        Message m = Message.obtain();
        m.what = messageID;
        m.obj = params;
        try {
            jobServiceMessenger.send(m);
        } catch (RemoteException e) {
            Log.e(TAG, "Error passing service object back to activity.");
        }
    }
}

我认为看起来很简单,当JobService启动时,我jobServiceMessengerJobService进行通信MainActivity

MainActivity:

public class MainActivity extends AppCompatActivity {
    public static final String MESSENGER_INTENT_KEY = "IncomingMessage";
    public static final String START_SERVICE_FILTER = "start.service";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(NetworkStateScheduler.TAG, "Service started");
                scheduleJob();
            }
        }, new IntentFilter(START_SERVICE_FILTER));
    }

    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent(this, NetworkStateScheduler.class);
        intent.putExtra(MESSENGER_INTENT_KEY, new Messenger(new IncomingMessageHandler()));
        startService(intent);
    }

    @Override
    protected void onStop() {
        stopService(new Intent(this, NetworkStateScheduler.class));
        super.onStop();
    }

    public void scheduleJob() {
        Log.i(NetworkStateScheduler.TAG, "Scheduling job");

        JobScheduler jobScheduler =
                (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.cancelAll();

        JobInfo jobInfo = new JobInfo.Builder(1,
                new ComponentName(this, NetworkStateScheduler.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setBackoffCriteria(0, JobInfo.BACKOFF_POLICY_LINEAR)
                .build();

        jobScheduler.schedule(jobInfo);
    }

    private static class IncomingMessageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            NetworkInfo.State state = (NetworkInfo.State) msg.obj;
            Log.d(NetworkStateScheduler.TAG, "state " + state);
        }
    }
}

在这部分代码中,我添加了简单的广播接收器,以了解JobService何时启动,因为我必须知道运行我的作业并检测连接状态。

现在它以这种方式工作:应用程序启动。服务正在启动并触发了要运行的作业。如果建立了连接,则调用来自onStartJob的{​​{1}}方法。当连接断开时,调用方法JobService。看起来JobService工作正常,因为每当我在设备上连接或断开wifi时,我都会收到来自onStopJobonStartJob的消息。但有时候,在运行应用程序之后,onStopJob启动但没有调用Service中的方法。我不知道为什么。我不明白为什么它能正常工作,有时它不起作用。这不是确定性的。

我该如何解决这个问题? (我添加了对android清单的服务)

0 个答案:

没有答案