NativeScript android NotificationChannel ошибка - PullRequest
0 голосов
/ 10 декабря 2018

У меня есть приложение {N}, которое должно вызывать уведомления.

Я использую уведомлениеChannel, но продолжаю получать ту же ошибку, когда приложение сломано.

"System.err: TypeError: android.NotificationChannel is not a constructor"

мой кодэто:

    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=GeofenceService.mainFunction()
        //     console.log("res",res)
            var builder = new android.app.Notification.Builder(context);
            builder.setContentTitle("Scheduled Notification")
            .setAutoCancel(true)
            .setColor(android.R.color.holo_purple)//getResources().getColor(R.color.colorAccent))
            .setContentText("This notification has been triggered by Notification Service")
            .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;
        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());

        return false;
    },

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

ошибка из этой строки:

const mChannel = new android.app.NotificationChannel(channelId, name,importance);

почему он говорит мне, что NotificationChannel не является конструктором?что я пропустил?

вот где я получил этот код, и он, кажется, работает для других людей.

https://github.com/NativeScript/sample-android-background-services

Редактировать:

Я только что проверил свой уровень API и его 26, так что даже с оператором if перед строкой канала его дробление.

когда я смотрю на папку с моими платформами в android манифесте, я вижу это:

  <uses-sdk
    android:minSdkVersion="17"
    android:targetSdkVersion="25"/>

почему его 25?

1 Ответ

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

android.app.NotificationChannel доступно только для API уровня 26 и выше (Android 8.0 - Oreo).Если вы используете более раннюю версию, она выдаст эту ошибку.

Вы должны проверить версию, прежде чем получить доступ к этим API, что-то вроде

if (android.os.Build.VERSION.SDK_INT >= 26) {
 const mChannel = new android.app.NotificationChannel(channelId, name,importance);
}

Обновление:

Вы должны установить целевой SDK наболее поздняя версия, как минимум 26. Вы не сможете даже загрузить свой APK в Google Play, если вы планируете использовать более низкую версию с августа 2018 года .

...