Phonegap navigator.notification.alert не работает - программирование
Подтвердить что ты не робот

Phonegap navigator.notification.alert не работает

Название самоочевидно, я не понимаю, почему именно.

Источники: WWW/index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>PhoneGap</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
        </div>
        <script type="text/javascript" src="phonegap.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
        <script type="text/javascript">
            app.initialize();
        </script>
    </body>
</html>

index.js:

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);

        navigator.notification.alert('PhoneGap Alert', null, 'Title', 'Button');
    }
};

config.xml в android/res/xml:

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.helloCordova" version="2.0.0" xmlns="http://www.w3.org/ns/widgets">
    <name>Hello Cordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="#" onclick="location.href='http://cordova.io'; return false;">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <feature name="App">
        <param name="android-package" value="org.apache.cordova.App" />
    </feature>
    <feature name="Notification">
        <param name="android-package" value="org.apache.cordova.Notification" />
    </feature>
    <access origin="http://127.0.0.1*" />
    <preference name="useBrowserHistory" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="permissions" value="none" />
    <preference name="orientation" value="default" />
    <preference name="target-device" value="universal" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="ios-statusbarstyle" value="black-opaque" />
    <preference name="detect-data-types" value="true" />
    <preference name="show-splash-screen-spinner" value="true" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="android-minSdkVersion" value="8" />
    <preference name="android-installLocation" value="auto" />
</widget>

и androidmanifest.xml:

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="1.0.0" android:windowSoftInputMode="adjustPan" package="com.acs.acs_mobile" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <application android:debuggable="true" android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/app_name" android:name="main" android:theme="@android:style/Theme.Black.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
</manifest>

Я пытаюсь понять, почему в последние часы он не работает без везения. Я реалвилле, новичок в телефоне, поэтому, пожалуйста, если я что-то упустил, дайте мне знать...

PS. Phonegap -version: 3.0.0-0.14.3, устройство sdk 8, AVD sdk 8 (оба результата)

Обновить после переноса кода внутри try catch. Я получил это сообщение об ошибке:

result of expression 'navigator.notification' undefined is not an object

AS, упомянутый в Пример приложения PhoneGap для Android, не работает и navigator.notification. * failed "navigator.notification [ undefined] не является объектом"

Причина такова: Likely the name of phonegap*js or cordova*js in your index.html does not match the file name in the assets/www directory., но у меня есть только phonegap.js и cordova.js на платформах /android/assets/www, и я включаю то же имя... Все еще не могу понять это...

UPDATE

Если я делаю удаленную сборку, приложение работает нормально с локальной сборкой, это не так, но я установил плагины, как указано для версии 3

4b9b3361

Ответ 1

Я построил ваш проект, используя Cordova CLI 3.0.9, используя инструменты командной строки и следующие документы, перечисленные здесь (http://cordova.apache.org/docs/en/edge/cordova_notification_notification.md.html#Notification). Я использовал ваш код HTML и JS, и диалоговое окно появилось просто отлично.

При просмотре других файлов я заметил разницу в config.xml; my config.xml выглядит следующим образом:

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.helloCordova" version="2.0.0" xmlns="http://www.w3.org/ns/widgets">
    <name>Hello Cordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <feature name="App">
        <param name="android-package" value="org.apache.cordova.App" />
    </feature>
    <feature name="Vibration">
        <param name="android-package" value="org.apache.cordova.vibration.Vibration" />
    </feature>
    <feature name="Notification">
        <param name="android-package" value="org.apache.cordova.dialogs.Notification" />
    </feature>
    <access origin="*" />
    <preference name="useBrowserHistory" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
</widget>

Обратите внимание, что у моей есть org.apache.cordova.dialogs.Notification. По какой-то причине у вас отсутствует пространство имен dialogs. Это специально? Если вы добавите пространство имен "dialogs", это сработает? Как насчет того, пересобираете ли вы последнюю версию CLI?

Ответ 2

Все, что вам нужно сделать, это добавить эту функцию в свой проект... Встаньте в папку проекта phonegap (а не в папку с платформой), например: cd MobileAplications/MyPhoneGapExample затем добавьте плагин (я установил кордову вместо телефонного разговора, поэтому я предположил, что если вы установили телефонную запик, вам нужно использовать команду "phonegap" ): плагин cordova добавляет org.apache.cordova.dialogs

Я надеюсь, что это сработает для вас!

PD: Если кто-то не знает, в чем разница между папкой платформы и папкой проекта, вот документ, который может показать разницу: http://docs.phonegap.com/en/3.2.0/guide_cli_index.md.html#The%20Command-Line%20Interface

Ответ 3

Я использую visual studio 2015, и я решил эту проблему, добавив плагин Notification.

Дважды щелкните свой файл config.xml в своем проекте и выберите Плагин уведомлений и установите.

введите описание изображения здесь

Ответ 4

попробуйте добавить эту функцию в файл config.xml

 <feature name="Notification">
  <param name="wp-package" value="Notification"/>
</feature>

... и хороший совет скопировать файл config.xml в ваш каталог www.

Ответ 5

Вы увидите только работу с эмулятором orroid или устройством, в рябке не работает.

    var app = {
    // Application Constructor
    initialize: function() {        
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        //this.receivedEvent('deviceready');
            console.log(navigator.notification);

            navigator.notification.alert(
                    'You are the winner!',  // message
                    alertDismissed,         // callback
                    'Game Over',            // title
                    'Done'                  // buttonName
                );
            //navigator.notification.beep(2);
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};app.initialize();

Ответ 6

Приложение Reinstal APK на устройстве. Только когда система установлена, система соглашается с разрешениями. Только перестройка не работает. После переустановки разрешения отображаются на экране и активны.