2013-09-16 5 views
10

Название самоочевидное, я не понимаю, почему именно.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="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="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 -версия: 3.0.0-0.14.3, устройство 8 SDK, AVD 8 SDK (как тот же результат)

Update после оборачивания кода в попытке поймать меня это сообщение об ошибке:

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

AS упоминается в PhoneGap sample application for android does not work и navigator.notification.* fails "navigator.notification [undefined] is not an object"

причина: 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/активов/WWW и я в том числе с точно таким же названием ... Все еще не могу понять это ...

UPDATE

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

ответ

6

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

При просмотре других файлов я заметил разницу в config.xml; мой 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?

+0

hmm correct, но если я не ошибаюсь, у меня были те, что были вставлены там, и попытались запустить его без везения. Позвольте мне снова проверить, и я дам вам знать. – Syd

+0

Nope не работает локально – Syd

+0

Вы обновили интерфейс Cordova CLI? Если да, добавляет ли значение 'value =" org.apache.cordova.dialogs.Notification "/>' в config.xml? – MBillau

0

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

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

... и хороший совет, чтобы скопировать файл config.xml в каталог WWW.

2

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

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

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

2

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

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

enter image description here

0

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

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(); 
0

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

Смежные вопросы