1

我正在开发一个使用 Mqtt 的应用程序,并且我正在尝试引入 Jobservice 而不是 Mqtt 服务。可以为 Android Oreo 中长期运行的后台服务执行此操作吗?这是我的代码。

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MqttServiceO extends JobService {
public static final String PUBLISH_TOPIC = "androidkt/topic";
private static final String TAG = "MqttServiceO";
private MqttClientO mqttClient;
private MqttAndroidClient mqttAndroidClient;

//Configuration du Job info builder
public static void schedule(Context context) {
    ComponentName component = new ComponentName(context, MqttServiceO.class);
    JobInfo.Builder builder = new JobInfo.Builder(MqttServiceConstants.JOB_ID, component)
            .setMinimumLatency(MqttServiceConstants.ONE_MIN)
            .setOverrideDeadline(5 * MqttServiceConstants.ONE_MIN);

    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(builder.build());
}


private Handler jobHandler=new Handler(new Handler.Callback(){

    @Override
    public boolean handleMessage(Message msg) {
        String topic = null;
        String m =null;
        setMessageNotification(topic,m);
        jobFinished( (JobParameters) msg.obj, false );
        return true;
    }
});

@Override
public boolean onStartJob(JobParameters params) {
    jobHandler.sendMessage(Message.obtain());
    return false;
}

private void setMessageNotification(@NonNull String topic, @NonNull String msg) {
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                   // .setSmallIcon(R.drawable.ic_message_black_24dp)
                    .setContentTitle(topic)
                    .setContentText(msg);
    Intent resultIntent = new Intent(this, MainActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(100, mBuilder.build());

}

@Override
public boolean onStopJob(JobParameters params) {
    jobHandler.removeMessages( 1 );
    return false;
}
}
4

0 回答 0