Js класс, расширяющийся, возвращается слишком быстро - PullRequest
0 голосов
/ 12 декабря 2018

Я использую javaScript для построения планировщика задач в nativeScript.

, JobSchedualer вызывает JobService, который должен быть выполнен.

, но JobService возвращается слишком быстро.

Вы можете сказать, что я использовал асинхронную функцию nearby(), которая работает нормально, но я не могу обернуть весь сценарий скобками nearby().

, поэтому мне нужен какой-то способ отложить инструкцию возврата, пока у меня не будет всех моихdata.

schedualer.js:

function scheduleJob(context) {

        // Create a component from the JobService that should be triggered
        var component = new android.content.ComponentName(context, com.tns.notifications.MyJobService.class);

        // Set the id of the job to something meaningful for you
        const builder = new android.app.job.JobInfo.Builder(1, component);

        // Optional: Set how often the task should be triggered. The minimum is 15min.
        builder.setPeriodic(15 * 60 * 1000);

        // Optional: Set additional requirements under what conditions your job should be triggered
        // builder.setRequiresCharging(true);
        builder.setOverrideDeadline(0);


        const jobScheduler = context.getSystemService(android.content.Context.JOB_SCHEDULER_SERVICE);
        console.log("Job Scheduled: " + jobScheduler.schedule(builder.build()));

}

module.exports.scheduleJob = scheduleJob;

myJobService.js

android.app.job.JobService.extend("com.tns.notifications.MyJobService", {
    onStartJob: function(params) {  
        console.log("Job execution ...");
        // Do something useful here, fetch data and show notification for example
        var utils = require("utils/utils");
        var context = utils.ad.getApplicationContext();

        var res;
        var geoService = require("./geocalc");
        var PointModell = require("./PointModell")

        nearby();
        async function nearby(){
            res=await geoService.geocalc();
            console.log("res",res); 
        }

            var builder = new android.app.Notification.Builder(context);
            console.log("setting notification head and body")
            builder.setContentTitle("you are in .......")
            .setAutoCancel(true)
            .setColor(android.R.color.holo_purple)//getResources().getColor(R.color.colorAccent))
            .setContentText("This notification has been triggered ")
            .setVibrate([100, 200, 100])
            .setSmallIcon(android.R.drawable.btn_star_big_on);



            // will open main NativeScript activity when the notification is pressed
            var mainIntent = new android.content.Intent(context, com.tns.NativeScriptActivity.class); 

            var mNotificationManager = context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

            // The id of the channel.
            const channelId = "my_channel_01";
            // The user-visible name of the channel.
            const name = "Channel name";
            // The user-visible description of the channel.
            const description = "Channel description";
            const importance = android.app.NotificationManager.IMPORTANCE_LOW;
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                console.log("apilevel is good",android.os.Build.VERSION.SDK_INT)
            }
            const mChannel = new android.app.NotificationChannel(channelId, name,importance);


            // const mChannel = new android.app.NotificationChannel(channelId, name,importance);
            // Configure the notification channel.
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            // Sets the notification light color for notifications posted to this
            // channel, if the device supports this feature.
            mChannel.setLightColor(android.graphics.Color.RED);
            mChannel.enableVibration(true);
            mNotificationManager.createNotificationChannel(mChannel);

            builder.setChannelId(channelId);

            mNotificationManager.notify(1, builder.build());

            console.log("returning job ..."); 

            return false
        },

        onStopJob: function() {
            console.log("Stopping job ...");

        }

    });

1 Ответ

0 голосов
/ 12 декабря 2018

Вы не можете отложить возвращаемое значение, даже если вы используете async / await.Я думаю, что вы должны вернуть true и вызвать jobFinished метод, когда вы закончите со всеми вашими данными.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...