reorganized trunk directory

This commit is contained in:
jywarren
2010-02-25 16:16:58 -05:00
parent 9f03d0c76f
commit a0c5e9a8c9
3954 changed files with 1 additions and 28919 deletions

View File

@@ -1,256 +0,0 @@
== Welcome to Rails
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
This pattern splits the view (also called the presentation) into "dumb" templates
that are primarily responsible for inserting pre-built data in between HTML tags.
The model contains the "smart" domain objects (such as Account, Product, Person,
Post) that holds all the business logic and knows how to persist themselves to
a database. The controller handles the incoming requests (such as Save New Account,
Update Product, Show Post) by manipulating the model and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
and your application name. Ex: rails myapp
2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
4. Follow the guidelines to start developing your application
== Web Servers
By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise
Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server,
Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures
that you can always get up and running quickly.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
More info at: http://mongrel.rubyforge.org
If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than
Mongrel and WEBrick and also suited for production use, but requires additional
installation and currently only works well on OS X/Unix (Windows users are encouraged
to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from
http://www.lighttpd.net.
And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby
web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not
for production.
But of course its also possible to run Rails on any platform that supports FCGI.
Apache, LiteSpeed, IIS are just a few. For more information on FCGI,
please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI
== Apache .htaccess example
# General Apache options
AddHandler fastcgi-script .fcgi
AddHandler cgi-script .cgi
Options +FollowSymLinks +ExecCGI
# If you don't want Rails to look in certain directories,
# use the following rewrite rules so that Apache won't rewrite certain requests
#
# Example:
# RewriteCond %{REQUEST_URI} ^/notrails.*
# RewriteRule .* - [L]
# Redirect all requests not available on the filesystem to Rails
# By default the cgi dispatcher is used which is very slow
#
# For better performance replace the dispatcher with the fastcgi one
#
# Example:
# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
RewriteEngine On
# If your Rails application is accessed via an Alias directive,
# then you MUST also set the RewriteBase in this htaccess file.
#
# Example:
# Alias /myrailsapp /path/to/myrailsapp/public
# RewriteBase /myrailsapp
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
# In case Rails experiences terminal errors
# Instead of displaying this message you can supply a file here which will be rendered instead
#
# Example:
# ErrorDocument 500 /500.html
ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands running
on the server.log and development.log. Rails will automatically display debugging
and runtime information to these files. Debugging info will also be shown in the
browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code using
the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two online (and free) books will bring you up to speed on the Ruby language
and also on programming in general.
== Debugger
Debugger support is available through the debugger command when you start your Mongrel or
Webrick server with --debugger. This means that you can break out of execution at any point
in the code, investigate and change the model, AND then resume execution!
You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
Example:
class WeblogController < ActionController::Base
def index
@posts = Post.find(:all)
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better is that you can examine how your runtime objects actually work:
>> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you enter "cont"
== Console
You can interact with the domain model by starting the console through <tt>script/console</tt>.
Here you'll have all parts of the application configured, just like it is when the
application is running. You can inspect domain models, change values, and save to the
database. Starting the script without arguments will launch it in the development environment.
Passing an argument will specify a different environment, like <tt>script/console production</tt>.
To reload your controllers and models after launching the console run <tt>reload!</tt>
== dbconsole
You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
You would be connected to the database with the credentials defined in database.yml.
Starting the script without arguments will connect you to the development database. Passing an
argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
Currently works for mysql, postgresql and sqlite.
== Description of Contents
app
Holds all the code that's specific to this particular application.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
automated URL mapping. All controllers should descend from ApplicationController
which itself descends from ActionController::Base.
app/models
Holds models that should be named like post.rb.
Most models will descend from ActiveRecord::Base.
app/views
Holds the template files for the view that should be named like
weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
syntax.
app/views/layouts
Holds the template files for layouts to be used with views. This models the common
header/footer method of wrapping views. In your views, define a layout using the
<tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
call <% yield %> to render the view using this layout.
app/helpers
Holds view helpers that should be named like weblogs_helper.rb. These are generated
for you automatically when using script/generate for controllers. Helpers can be used to
wrap functionality for your views into methods.
config
Configuration files for the Rails environment, the routing map, the database, and other dependencies.
db
Contains the database schema in schema.rb. db/migrate contains all
the sequence of Migrations for your schema.
doc
This directory is where your application documentation will be stored when generated
using <tt>rake doc:app</tt>
lib
Application specific libraries. Basically, any kind of custom code that doesn't
belong under controllers, models, or helpers. This directory is in the load path.
public
The directory available for the web server. Contains subdirectories for images, stylesheets,
and javascripts. Also contains the dispatchers and the default HTML files. This should be
set as the DOCUMENT_ROOT of your web server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the script/generate scripts, template
test files will be generated for you and placed in this directory.
vendor
External libraries that the application depends on. Also includes the plugins subdirectory.
If the app has frozen rails, those gems also go here, under vendor/rails/.
This directory is in the load path.

View File

@@ -1,133 +0,0 @@
SHELL = /bin/sh
CHMOD = chmod
CP = cp
MV = mv
NOOP = $(SHELL) -c true
RM_F = rm -f
RM_RF = rm -rf
TEST_F = test -f
TOUCH = touch
UMASK_NULL = umask 0
DEV_NULL = > /dev/null 2>&1
MKPATH = mkdir -p
CAT = cat
MAKE = make
OPEN = open
ECHO = echo
ECHO_N = echo -n
JAVA = java
DOXYGEN =
IPHONE_DOCSET_TMPDIR = docs/iphone/tmp
all :: iphone blackberry android docs
clean :: clean_docs clean_libs
clean_docs:
-$(RM_RF) docs/javascript
-$(RM_RF) docs/iphone
clean_libs:
-$(RM_RF) lib
iphone/www/phonegap.js: lib/iphone/phonegap-min.js
$(CP) lib/iphone/phonegap-min.js $@
docs :: javascript_docs iphone_docs
iphone_docs:
javascript_docs :: javascripts/acceleration.js javascripts/accelerometer.js javascripts/camera.js javascripts/contact.js javascripts/debugconsole.js javascripts/device.js javascripts/file.js javascripts/geolocation.js javascripts/map.js javascripts/media.js javascripts/notification.js javascripts/orientation.js javascripts/position.js javascripts/sms.js javascripts/telephony.js javascripts/uicontrols.js
$(JAVA) -jar util/jsdoc-toolkit/jsrun.jar util/jsdoc-toolkit/app/run.js -a -d=docs/javascript -t=util/jsdoc-toolkit/templates/jsdoc javascripts/acceleration.js javascripts/accelerometer.js javascripts/camera.js javascripts/contact.js javascripts/debugconsole.js javascripts/device.js javascripts/file.js javascripts/geolocation.js javascripts/map.js javascripts/media.js javascripts/notification.js javascripts/orientation.js javascripts/position.js javascripts/sms.js javascripts/telephony.js javascripts/uicontrols.js
iphone: lib/iphone/phonegap-min.js
lib/iphone/phonegap-min.js: lib/iphone/phonegap.js
$(JAVA) -jar util/yuicompressor-2.4.2.jar --charset UTF-8 -o $@ lib/iphone/phonegap.js
lib/iphone/phonegap.js: javascripts/phonegap.js.base javascripts/acceleration.js javascripts/accelerometer.js javascripts/camera.js javascripts/contact.js javascripts/debugconsole.js javascripts/device.js javascripts/file.js javascripts/geolocation.js javascripts/map.js javascripts/media.js javascripts/notification.js javascripts/orientation.js javascripts/position.js javascripts/sms.js javascripts/telephony.js javascripts/uicontrols.js javascripts/iphone/accelerometer.js javascripts/iphone/bonjour.js javascripts/iphone/contact.js javascripts/iphone/debugconsole.js javascripts/iphone/device.js javascripts/iphone/geolocation.js javascripts/iphone/media.js javascripts/iphone/notification.js javascripts/iphone/phonegap.js javascripts/iphone/uicontrols.js
$(RM_RF) lib/iphone
$(MKPATH) lib/iphone
$(RM_F) $@
$(CAT) javascripts/phonegap.js.base >> $@
$(CAT) javascripts/acceleration.js >> $@
$(CAT) javascripts/accelerometer.js >> $@
$(CAT) javascripts/camera.js >> $@
$(CAT) javascripts/contact.js >> $@
$(CAT) javascripts/debugconsole.js >> $@
$(CAT) javascripts/device.js >> $@
$(CAT) javascripts/file.js >> $@
$(CAT) javascripts/geolocation.js >> $@
$(CAT) javascripts/map.js >> $@
$(CAT) javascripts/media.js >> $@
$(CAT) javascripts/notification.js >> $@
$(CAT) javascripts/orientation.js >> $@
$(CAT) javascripts/position.js >> $@
$(CAT) javascripts/sms.js >> $@
$(CAT) javascripts/telephony.js >> $@
$(CAT) javascripts/uicontrols.js >> $@
$(CAT) javascripts/iphone/accelerometer.js >> $@
$(CAT) javascripts/iphone/bonjour.js >> $@
$(CAT) javascripts/iphone/contact.js >> $@
$(CAT) javascripts/iphone/debugconsole.js >> $@
$(CAT) javascripts/iphone/device.js >> $@
$(CAT) javascripts/iphone/geolocation.js >> $@
$(CAT) javascripts/iphone/media.js >> $@
$(CAT) javascripts/iphone/notification.js >> $@
$(CAT) javascripts/iphone/phonegap.js >> $@
$(CAT) javascripts/iphone/uicontrols.js >> $@
blackberry: lib/blackberry/phonegap-min.js
lib/blackberry/phonegap-min.js: lib/blackberry/phonegap.js
$(JAVA) -jar util/yuicompressor-2.4.2.jar --charset UTF-8 -o $@ lib/blackberry/phonegap.js
lib/blackberry/phonegap.js: javascripts/phonegap.js.base javascripts/acceleration.js javascripts/accelerometer.js javascripts/camera.js javascripts/contact.js javascripts/debugconsole.js javascripts/device.js javascripts/file.js javascripts/geolocation.js javascripts/map.js javascripts/media.js javascripts/notification.js javascripts/orientation.js javascripts/position.js javascripts/sms.js javascripts/telephony.js javascripts/uicontrols.js javascripts/blackberry/file.js javascripts/blackberry/geolocation.js
$(RM_RF) lib/blackberry
$(MKPATH) lib/blackberry
$(RM_F) $@
$(CAT) javascripts/phonegap.js.base >> $@
$(CAT) javascripts/acceleration.js >> $@
$(CAT) javascripts/accelerometer.js >> $@
$(CAT) javascripts/camera.js >> $@
$(CAT) javascripts/contact.js >> $@
$(CAT) javascripts/debugconsole.js >> $@
$(CAT) javascripts/device.js >> $@
$(CAT) javascripts/file.js >> $@
$(CAT) javascripts/geolocation.js >> $@
$(CAT) javascripts/map.js >> $@
$(CAT) javascripts/media.js >> $@
$(CAT) javascripts/notification.js >> $@
$(CAT) javascripts/orientation.js >> $@
$(CAT) javascripts/position.js >> $@
$(CAT) javascripts/sms.js >> $@
$(CAT) javascripts/telephony.js >> $@
$(CAT) javascripts/uicontrols.js >> $@
$(CAT) javascripts/blackberry/file.js >> $@
$(CAT) javascripts/blackberry/geolocation.js >> $@
android: lib/android/phonegap-min.js
lib/android/phonegap-min.js: lib/android/phonegap.js
$(JAVA) -jar util/yuicompressor-2.4.2.jar --charset UTF-8 -o $@ lib/android/phonegap.js
lib/android/phonegap.js: javascripts/phonegap.js.base javascripts/acceleration.js javascripts/accelerometer.js javascripts/camera.js javascripts/contact.js javascripts/debugconsole.js javascripts/device.js javascripts/file.js javascripts/geolocation.js javascripts/map.js javascripts/media.js javascripts/notification.js javascripts/orientation.js javascripts/position.js javascripts/sms.js javascripts/telephony.js javascripts/uicontrols.js javascripts/android/device.js javascripts/android/geolocation.js javascripts/android/notification.js
$(RM_RF) lib/android
$(MKPATH) lib/android
$(RM_F) $@
$(CAT) javascripts/phonegap.js.base >> $@
$(CAT) javascripts/acceleration.js >> $@
$(CAT) javascripts/accelerometer.js >> $@
$(CAT) javascripts/camera.js >> $@
$(CAT) javascripts/contact.js >> $@
$(CAT) javascripts/debugconsole.js >> $@
$(CAT) javascripts/device.js >> $@
$(CAT) javascripts/file.js >> $@
$(CAT) javascripts/geolocation.js >> $@
$(CAT) javascripts/map.js >> $@
$(CAT) javascripts/media.js >> $@
$(CAT) javascripts/notification.js >> $@
$(CAT) javascripts/orientation.js >> $@
$(CAT) javascripts/position.js >> $@
$(CAT) javascripts/sms.js >> $@
$(CAT) javascripts/telephony.js >> $@
$(CAT) javascripts/uicontrols.js >> $@
$(CAT) javascripts/android/device.js >> $@
$(CAT) javascripts/android/geolocation.js >> $@
$(CAT) javascripts/android/notification.js >> $@

View File

@@ -1,111 +0,0 @@
PhoneGap
=============================================================
PhoneGap is a development tool that allows web developers to
take advantage of the core features in the iPhone and Android
SDK using JavaScript.
Get Started
-------------------------------------------------------------
Download the source.
git clone git://github.com/sintaxi/phonegap.git
PhoneGap project is separated into a native project for each
device, javascript files and a rakefile.
phonegap
|- README.md
|- Rakefile
|- android/
|- blackberry/
|- iphone/
`- javascripts/
Each project has a respective README.md file. view that file
for detailed information on how to work with that device. PhoneGap
offers one unified API for accessing core functionality on all
devices. Where possible, phonegap follows the **HTML5 spec**.
API
-------------------------------------------------------------
### Device
Exposes properties of the phone, such as its device ID, model, and OS version number.
### Location
Gain access to the Latitude / Longitude of the device, and depending on the type of device, the course, speed, and altitude.
### Accelerometer
Monitor the accelerometer on the device to detect orientation, shaking and other similar actions.
### Contacts
Query the phone addressbook to read the users contacts.
### Orientation
Read the device layout orientation, e.g. landscape vs portrait.
### Camera
Brings up the camera or photo browser on the phone to allow the user to upload a photo.
### Vibrate
Triggers the vibration alert on the phone, if it is supported.
### Sound
Play sound files (WAV, MP3, etc).
### Telephony
Trigger and activate phone calls.
XUI
-------------------------------------------------------------
You may work with any Javascript framework within a PhoneGap
application. [XUI](http://xuijs.com) is the "officially preferred"
framework of the phonegap core team. XUI is inspired by JQuery,
optimized for web browsers and weighs in at 6.2k (2.4k minified and gziped).
Community
-------------------------------------------------------------
* Website - [phonegap.com](http://phonegap.com)
* Google Group - [groups.google.com/group/phonegap](http://groups.google.com/group/phonegap)
* Wiki - [phonegap.pbwiki.com/](http://phonegap.pbwiki.com/)
* Twitter - [twitter.com/phonegap](http://twitter.com/phonegap)
The MIT License
-------------------------------------------------------------
Copyright (c) 2008, Rob Ellis, Brock Whitten, Brian Leroux, Joe Bowser, Dave Johnson, Nitobi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-------------------------------------------------------------
*phonegap is a [nitobi](http://nitobi.com) sponsored project*

View File

@@ -1,83 +0,0 @@
LIBPATH = File.expand_path(File.dirname(__FILE__)) + File::SEPARATOR
#
# builds and tests
#
desc 'writes lib/phonegap.js and lib/phonegap-min.js and runs docs'
task :default do
build
doc
end
task :doc do
doc
end
def doc
puts 'writing the full interface source for documentation into tmp/phonegap.js'
final = "#{ LIBPATH }tmp#{ File::SEPARATOR }phonegap.js"
js = ""
interfaces_to_build.each do |lib|
js << import("#{ LIBPATH }javascripts#{ File::SEPARATOR }#{ lib }.js")
end
FileUtils.mkdir_p "#{ LIBPATH }tmp"
open(final,'w'){|f| f.puts( js )}
sh "java -jar util#{ File::SEPARATOR }jsdoc-toolkit#{ File::SEPARATOR }jsrun.jar util#{ File::SEPARATOR }jsdoc-toolkit#{ File::SEPARATOR }app#{ File::SEPARATOR }run.js -a -d=javascripts/docs -t=util#{ File::SEPARATOR }jsdoc-toolkit#{ File::SEPARATOR }templates#{ File::SEPARATOR }jsdoc tmp#{ File::SEPARATOR }phonegap.js"
end
def build
puts 'writing the full JS file to lib/phonegap.js'
platforms_to_build.each do |platform|
final = "#{ LIBPATH }lib#{ File::SEPARATOR }#{ platform }#{ File::SEPARATOR }phonegap.js"
js = ""
interfaces_to_build.each do |interface|
js << import("#{ LIBPATH }javascripts#{ File::SEPARATOR }#{ interface }.js")
begin
js << import("#{ LIBPATH }javascripts#{ File::SEPARATOR }#{ platform }#{ File::SEPARATOR }#{ interface }.js")
rescue
end
end
FileUtils.mkdir_p "#{ LIBPATH }lib#{ File::SEPARATOR }#{ platform }"
open(final,'w'){|f| f.puts( js )}
end
min
end
# the sub libraries used by xui
def interfaces_to_build
%w(device acceleration accelerometer media camera contact uicontrols debugconsole file geolocation map notification orientation position sms telephony)
end
# the sub libraries used by xui
def platforms_to_build
%w(android blackberry iphone)
end
# helper for build_sub_libaries
def import(lib)
s = ""
r = ""
open(lib) { |f| s << "\n#{f.read}\n\n" }
s.each_line {|l| r << " #{l}"}
r
end
# creates lib/xui-min.js (tho not obfuscates)
def min
puts 'minifying js'
platforms_to_build.each do |platform|
min_file = "#{ LIBPATH }lib#{ File::SEPARATOR }#{ platform }#{ File::SEPARATOR }phonegap-min.js"
doc_file = "#{ LIBPATH }lib#{ File::SEPARATOR }#{ platform }#{ File::SEPARATOR }phonegap.js"
sh "java -jar #{LIBPATH}#{ File::SEPARATOR }util#{ File::SEPARATOR }yuicompressor-2.4.2.jar --charset UTF-8 -o #{min_file} #{doc_file}"
end
end
# opens up the specs
def spec
puts 'running automated test suite'
#sh "open -a WebKit file://#{ LIBPATH }/spec/index.html"
#sh "open -a '/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app' file://#{ LIBPATH }/spec/index.html"
end

View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -1,33 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PhoneGap</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phonegap.demo" android:versionName="1.0.1" android:versionCode="2">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
<activity android:name=".DroidGap"
android:label="@string/app_name" android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -1,91 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceInfo = function(){
document.getElementById("platform").innerHTML = Device.getPlatform();
document.getElementById("version").innerHTML = Device.getVersion();
document.getElementById("uuid").innerHTML = Device.getUuid();
}
var getLocation = function() {
var suc = function(p){
alert(p.latitude + " " + p.longitude);
};
var fail = function(){};
navigator.geolocation.getCurrentPosition(suc,fail);
}
var beep = function(){
navigator.notification.beep(2);
}
var vibrate = function(){
navigator.notification.vibrate(0);
}
var getContact = function(){
var suc = function(c){ alert("Contact 4: " + c.contacts[3].name); };
var fail = function(){};
navigator.ContactManager.get(suc, fail);
}
var watchAccel = function() {
var suc = function(a){
document.getElementById('x').innerHTML = roundNumber(a.x);
document.getElementById('y').innerHTML = roundNumber(a.y);
document.getElementById('z').innerHTML = roundNumber(a.z);
};
var fail = function(){};
var opt = {};
opt.frequency = 100;
timer = navigator.accelerometer.watchAcceleration(suc,fail,opt);
}
function roundNumber(num) {
var dec = 3;
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
var preventBehavior = function(e) {
e.preventDefault();
};
function init(){
document.addEventListener("touchmove", preventBehavior, false);
deviceInfo();
}
</script>
</head>
<body onload="init();" id="stage" class="theme">
<h1>Welcome to PhoneGap!</h1>
<h2>this file is located at assets/index.html</h2>
<div id="info">
<h4>Platform: <span id="platform">&nbsp;</span></h4>
<h4>Version: <span id="version">&nbsp;</span></h4>
<h4>UUID: <span id="uuid">&nbsp;</span></h4>
</div>
<dl id="accel-data">
<dt>X:</dt><dd id="x">&nbsp;</dd>
<dt>Y:</dt><dd id="y">&nbsp;</dd>
<dt>Z:</dt><dd id="z">&nbsp;</dd>
</dl>
<a href="#" class="btn large" onclick="watchAccel();">Watch Accelerometer</a>
<a href="#" class="btn large" onclick="getLocation();">Get Location</a>
<a href="tel://411" class="btn large">Call 411</a>
<a href="#" class="btn" onclick="beep();">Beep</a>
<a href="#" class="btn" onclick="vibrate();">Vibrate</a>
<!--
<a href="#" class="btn large" onclick="getContact();">Get Fourth Contact</a>
-->
</body>
</html>

View File

@@ -1,95 +0,0 @@
body {
background:#222 none repeat scroll 0 0;
color:#666;
font-family:Helvetica;
font-size:72%;
line-height:1.5em;
margin:0;
border-top:1px solid #393939;
}
#info{
background:#ffa;
border: 1px solid #ffd324;
-webkit-border-radius: 5px;
border-radius: 5px;
clear:both;
margin:15px 6px 0;
width:295px;
padding:4px 0px 2px 10px;
}
#info > h4{
font-size:.95em;
margin:5px 0;
}
#stage.theme{
padding-top:3px;
}
/* Definition List */
#stage.theme > dl{
padding-top:10px;
clear:both;
margin:0;
list-style-type:none;
padding-left:10px;
overflow:auto;
}
#stage.theme > dl > dt{
font-weight:bold;
float:left;
margin-left:5px;
}
#stage.theme > dl > dd{
width:45px;
float:left;
color:#a87;
font-weight:bold;
}
/* Content Styling */
#stage.theme > h1, #stage.theme > h2, #stage.theme > p{
margin:1em 0 .5em 13px;
}
#stage.theme > h1{
color:#eee;
font-size:1.6em;
text-align:center;
margin:0;
margin-top:15px;
padding:0;
}
#stage.theme > h2{
clear:both;
margin:0;
padding:3px;
font-size:1em;
text-align:center;
}
/* Stage Buttons */
#stage.theme a.btn{
border: 1px solid #555;
-webkit-border-radius: 5px;
border-radius: 5px;
text-align:center;
display:block;
float:left;
background:#444;
width:150px;
color:#9ab;
font-size:1.1em;
text-decoration:none;
padding:1.2em 0;
margin:3px 0px 3px 5px;
}
#stage.theme a.btn.large{
width:308px;
padding:1.2em 0;
}

View File

@@ -1,630 +0,0 @@
/**
* This class contains acceleration information
* @constructor
* @param {Number} x The force applied by the device in the x-axis.
* @param {Number} y The force applied by the device in the y-axis.
* @param {Number} z The force applied by the device in the z-axis.
*/
function Acceleration(x, y, z) {
/**
* The force applied by the device in the x-axis.
*/
this.x = x;
/**
* The force applied by the device in the y-axis.
*/
this.y = y;
/**
* The force applied by the device in the z-axis.
*/
this.z = z;
/**
* The time that the acceleration was obtained.
*/
this.timestamp = new Date().getTime();
}
/**
* This class specifies the options for requesting acceleration data.
* @constructor
*/
function AccelerationOptions() {
/**
* The timeout after which if acceleration data cannot be obtained the errorCallback
* is called.
*/
this.timeout = 10000;
}
/**
* This class provides access to device accelerometer data.
* @constructor
*/
function Accelerometer() {
/**
* The last known acceleration.
*/
this.lastAcceleration = null;
}
/**
* Asynchronously aquires the current acceleration.
* @param {Function} successCallback The function to call when the acceleration
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the acceleration data.
* @param {AccelerationOptions} options The options for getting the accelerometer data
* such as timeout.
*/
Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) {
// If the acceleration is available then call success
// If the acceleration is not available then call error
// Created for iPhone, Iphone passes back _accel obj litteral
if (typeof successCallback == "function") {
var accel = new Acceleration(_accel.x,_accel.y,_accel.z);
Accelerometer.lastAcceleration = accel;
successCallback(accel);
}
}
/**
* Asynchronously aquires the acceleration repeatedly at a given interval.
* @param {Function} successCallback The function to call each time the acceleration
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the acceleration data.
* @param {AccelerationOptions} options The options for getting the accelerometer data
* such as timeout.
*/
Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) {
navigator.accelerometer.getCurrentAcceleration(successCallback, errorCallback, options);
// TODO: add the interval id to a list so we can clear all watches
var frequency = (options != undefined)? options.frequency : 10000;
return setInterval(function() {
navigator.accelerometer.getCurrentAcceleration(successCallback, errorCallback, options);
}, frequency);
}
/**
* Clears the specified accelerometer watch.
* @param {String} watchId The ID of the watch returned from #watchAcceleration.
*/
Accelerometer.prototype.clearWatch = function(watchId) {
clearInterval(watchId);
}
if (typeof navigator.accelerometer == "undefined") navigator.accelerometer = new Accelerometer();
/**
* This class provides access to the device media, interfaces to both sound and video
* @constructor
*/
function Media(src) {
this.src = src;
}
Media.prototype.play = function() {
}
Media.prototype.pause = function() {
}
Media.prototype.stop = function() {
}
/**
* This class contains information about any Media errors.
* @constructor
*/
function MediaError() {
this.code = null,
this.message = "";
}
MediaError.MEDIA_ERR_ABORTED = 1;
MediaError.MEDIA_ERR_NETWORK = 2;
MediaError.MEDIA_ERR_DECODE = 3;
MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
//if (typeof navigator.audio == "undefined") navigator.audio = new Media(src);
/**
* This class provides access to the device camera.
* @constructor
*/
function Camera() {
}
/**
*
* @param {Function} successCallback
* @param {Function} errorCallback
* @param {Object} options
*/
Camera.prototype.getPicture = function(successCallback, errorCallback, options) {
}
if (typeof navigator.camera == "undefined") navigator.camera = new Camera();
/**
* This class provides access to the device contacts.
* @constructor
*/
function Contact() {
this.name = "";
this.phone = "";
this.address = "";
}
/**
*
* @param {Object} successCallback
* @param {Object} errorCallback
* @param {Object} options
*/
Contact.prototype.get = function(successCallback, errorCallback, options) {
}
function ContactManager() {
// Dummy object to hold array of contacts
this.contacts = [];
this.timestap = new Date().getTime();
}
ContactManager.prototype.get = function(successCallback, errorCallback, options) {
// Interface
}
if (typeof navigator.ContactManager == "undefined") navigator.ContactManager = new ContactManager();
/**
* This class provides generic read and write access to the mobile device file system.
*/
function File() {
/**
* The data of a file.
*/
this.data = "";
/**
* The name of the file.
*/
this.name = "";
}
/**
* Reads a file from the mobile device. This function is asyncronous.
* @param {String} fileName The name (including the path) to the file on the mobile device.
* The file name will likely be device dependant.
* @param {Function} successCallback The function to call when the file is successfully read.
* @param {Function} errorCallback The function to call when there is an error reading the file from the device.
*/
File.prototype.read = function(fileName, successCallback, errorCallback) {
}
/**
* Writes a file to the mobile device.
* @param {File} file The file to write to the device.
*/
File.prototype.write = function(file) {
}
if (typeof navigator.file == "undefined") navigator.file = new File();
/**
* This class provides access to device GPS data.
* @constructor
*/
function Geolocation() {
/**
* The last known GPS position.
*/
this.lastPosition = null;
}
/**
* Asynchronously aquires the current position.
* @param {Function} successCallback The function to call when the position
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the position data.
* @param {PositionOptions} options The options for getting the position data
* such as timeout.
*/
Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) {
// If the position is available then call success
// If the position is not available then call error
}
/**
* Asynchronously aquires the position repeatedly at a given interval.
* @param {Function} successCallback The function to call each time the position
* data is available
* @param {Function} errorCallback The function to call when there is an error
* getting the position data.
* @param {PositionOptions} options The options for getting the position data
* such as timeout and the frequency of the watch.
*/
Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) {
// Invoke the appropriate callback with a new Position object every time the implementation
// determines that the position of the hosting device has changed.
this.getCurrentPosition(successCallback, errorCallback, options);
var frequency = (options != undefined)? options.frequency : 10000;
var that = this;
return setInterval(function() {
that.getCurrentPosition(successCallback, errorCallback, options);
//navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
}, frequency);
}
/**
* Clears the specified position watch.
* @param {String} watchId The ID of the watch returned from #watchPosition.
*/
Geolocation.prototype.clearWatch = function(watchId) {
clearInterval(watchId);
}
if (typeof navigator.geolocation == "undefined") navigator.geolocation = new Geolocation();
/**
* This class provides access to native mapping applications on the device.
*/
function Map() {
}
/**
* Shows a native map on the device with pins at the given positions.
* @param {Array} positions
*/
Map.prototype.show = function(positions) {
}
if (typeof navigator.map == "undefined") navigator.map = new Map();
/**
* This class provides access to notifications on the device.
*/
function Notification() {
}
/**
* Causes the device to blink a status LED.
* @param {Integer} count The number of blinks.
* @param {String} colour The colour of the light.
*/
Notification.prototype.blink = function(count, colour) {
}
/**
* Causes the device to vibrate.
* @param {Integer} mills The number of milliseconds to vibrate for.
*/
Notification.prototype.vibrate = function(mills) {
}
/**
* Causes the device to beep.
* @param {Integer} count The number of beeps.
* @param {Integer} volume The volume of the beep.
*/
Notification.prototype.beep = function(count, volume) {
}
// TODO: of course on Blackberry and Android there notifications in the UI as well
if (typeof navigator.notification == "undefined") navigator.notification = new Notification();
/**
* This class provides access to the device orientation.
* @constructor
*/
function Orientation() {
/**
* The last known orientation.
*/
this.lastOrientation = null;
}
/**
* Asynchronously aquires the current orientation.
* @param {Function} successCallback The function to call when the orientation
* is known.
* @param {Function} errorCallback The function to call when there is an error
* getting the orientation.
*/
Orientation.prototype.getCurrentOrientation = function(successCallback, errorCallback) {
// If the position is available then call success
// If the position is not available then call error
}
/**
* Asynchronously aquires the orientation repeatedly at a given interval.
* @param {Function} successCallback The function to call each time the orientation
* data is available.
* @param {Function} errorCallback The function to call when there is an error
* getting the orientation data.
*/
Orientation.prototype.watchOrientation = function(successCallback, errorCallback) {
// Invoke the appropriate callback with a new Position object every time the implementation
// determines that the position of the hosting device has changed.
this.getCurrentPosition(successCallback, errorCallback);
return setInterval(function() {
navigator.orientation.getCurrentOrientation(successCallback, errorCallback);
}, 10000);
}
/**
* Clears the specified orientation watch.
* @param {String} watchId The ID of the watch returned from #watchOrientation.
*/
Orientation.prototype.clearWatch = function(watchId) {
clearInterval(watchId);
}
if (typeof navigator.orientation == "undefined") navigator.orientation = new Orientation();
/**
* This class contains position information.
* @param {Object} lat
* @param {Object} lng
* @param {Object} acc
* @param {Object} alt
* @param {Object} altacc
* @param {Object} head
* @param {Object} vel
* @constructor
*/
function Position(lat, lng, acc, alt, altacc, head, vel) {
/**
* The latitude of the position.
*/
this.latitude = lat;
/**
* The longitude of the position,
*/
this.longitude = lng;
/**
* The accuracy of the position.
*/
this.accuracy = acc;
/**
* The altitude of the position.
*/
this.altitude = alt;
/**
* The altitude accuracy of the position.
*/
this.altitudeAccuracy = altacc;
/**
* The direction the device is moving at the position.
*/
this.heading = head;
/**
* The velocity with which the device is moving at the position.
*/
this.velocity = vel;
/**
* The time that the position was obtained.
*/
this.timestamp = new Date().getTime();
}
/**
* This class specifies the options for requesting position data.
* @constructor
*/
function PositionOptions() {
/**
* Specifies the desired position accuracy.
*/
this.enableHighAccuracy = true;
/**
* The timeout after which if position data cannot be obtained the errorCallback
* is called.
*/
this.timeout = 10000;
}
/**
* This class contains information about any GSP errors.
* @constructor
*/
function PositionError() {
this.code = null;
this.message = "";
}
PositionError.UNKNOWN_ERROR = 0;
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
/**
* This class provides access to the device SMS functionality.
* @constructor
*/
function Sms() {
}
/**
* Sends an SMS message.
* @param {Integer} number The phone number to send the message to.
* @param {String} message The contents of the SMS message to send.
* @param {Function} successCallback The function to call when the SMS message is sent.
* @param {Function} errorCallback The function to call when there is an error sending the SMS message.
* @param {PositionOptions} options The options for accessing the GPS location such as timeout and accuracy.
*/
Sms.prototype.send = function(number, message, successCallback, errorCallback, options) {
}
if (typeof navigator.sms == "undefined") navigator.sms = new Sms();
/**
* This class provides access to the telephony features of the device.
* @constructor
*/
function Telephony() {
}
/**
* Calls the specifed number.
* @param {Integer} number The number to be called.
*/
Telephony.prototype.call = function(number) {
}
if (typeof navigator.telephony == "undefined") navigator.telephony = new Telephony();
// Android specific overrides here
Notification.prototype.vibrate = function(mills)
{
Device.vibrate(mills);
}
/*
* On the Android, we don't beep, we notify you with your
* notification! We shouldn't keep hammering on this, and should
* review what we want beep to do.
*/
Notification.prototype.beep = function(count, volume)
{
Device.beep(count);
}
/*
* Since we can't guarantee that we will have the most recent, we just try our best!
*
* Also, the API doesn't specify which version is the best version of the API
*/
Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options)
{
Geolocation.global_success = successCallback;
Geolocation.fail = errorCallback;
Geo.getCurrentLocation();
}
// Run the global callback
Geolocation.gotCurrentPosition = function(lat, lng)
{
if (lat == "undefined" || lng == "undefined")
{
this.fail();
}
else
{
p = {};
p.latitude = lat;
p.longitude = lng;
this.global_success(p);
}
}
/*
* This turns on the GeoLocator class, which has two listeners.
* The listeners have their own timeouts, and run independently of this process
* In this case, we return the key to the watch hash
*/
Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options)
{
var frequency = (options != undefined)? options.frequency : 10000;
if (!this.listeners)
{
this.listeners = []
}
var key = this.listeners.push( {"success" : successCallback, "fail" : failCallback }) - 1;
// TO-DO: Get the names of the method and pass them as strings to the Java.
return Geolocation.start(frequency, key);
}
/*
* Retrieve and stop this listener from listening to the GPS
*
*/
Geolocation.success = function(key, lat, lng)
{
this.listeners[key].success(lat,lng);
}
Geolocation.prototype.fail = function(key)
{
this.listeners[key].fail();
}
Geolocation.prototype.clearWatch = function(watchId)
{
Geo.stop(watchId);
}
/* Identical to the iPhone, except we have to create this in the JS */
_accel = {}
_accel.x = 0;
_accel.y = 0;
_accel.z = 0;
function gotAccel(x,y,z)
{
_accel.x = x;
_accel.y = y;
_accel.z = z;
}
Accelerometer.base_method = Accelerometer.prototype.watchAcceleration
Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options)
{
Accel.start();
Accelerometer.base_method(successCallback, errorCallback, options);
}
Accelerometer.prototype.clearWatch = function(watchId){
clearInterval(watchId);
Accel.stop();
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@+id/appView"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</LinearLayout>

View File

@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">PhoneGap</string>
<string name="url">file:///android_asset/index.html</string>
</resources>

View File

@@ -1,58 +0,0 @@
package com.phonegap.demo;
import static android.hardware.SensorManager.DATA_X;
import static android.hardware.SensorManager.DATA_Y;
import static android.hardware.SensorManager.DATA_Z;
import android.hardware.SensorManager;
import android.content.Context;
import android.hardware.SensorListener;
import android.webkit.WebView;
public class AccelListener implements SensorListener{
WebView mAppView;
Context mCtx;
private SensorManager sensorManager;
private long lastUpdate = -1;
AccelListener(Context ctx, WebView appView)
{
mCtx = ctx;
mAppView = appView;
sensorManager = (SensorManager) mCtx.getSystemService(Context.SENSOR_SERVICE);
}
public void start()
{
sensorManager.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
}
public void stop()
{
sensorManager.unregisterListener(this);
}
public void onAccuracyChanged(int sensor, int accuracy) {
// This should call the FAIL method
}
public void onSensorChanged(int sensor, float[] values) {
if (sensor != SensorManager.SENSOR_ACCELEROMETER || values.length < 3)
return;
long curTime = System.currentTimeMillis();
if (lastUpdate == -1 || (curTime - lastUpdate) > 1000) {
lastUpdate = curTime;
float x = values[DATA_X];
float y = values[DATA_Y];
float z = values[DATA_Z];
mAppView.loadUrl("javascript:gotAccel(" + x + ", " + y + "," + z + " )");
}
}
}

View File

@@ -1,29 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class AccelTuple {
public long accelX;
public long accelY;
public long accelZ;
}

View File

@@ -1,186 +0,0 @@
package com.phonegap.demo;
import java.io.File;
import java.io.IOException;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
public class AudioHandler implements OnCompletionListener, OnPreparedListener, OnErrorListener {
private MediaRecorder recorder;
private boolean isRecording = false;
MediaPlayer mPlayer;
private boolean isPlaying = false;
private String recording;
private String saveFile;
private Context mCtx;
public AudioHandler(String file, Context ctx) {
this.recording = file;
this.mCtx = ctx;
}
protected void startRecording(String file){
if (!isRecording){
saveFile=file;
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(this.recording);
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isRecording = true;
recorder.start();
}
}
private void moveFile(String file) {
/* this is a hack to save the file as the specified name */
File f = new File (this.recording);
f.renameTo(new File("/sdcard" + file));
}
protected void stopRecording(){
try{
if((recorder != null)&&(isRecording))
{
isRecording = false;
recorder.stop();
recorder.release();
}
moveFile(saveFile);
}catch (Exception e){e.printStackTrace();}
}
protected void startPlaying(String file) {
if (isPlaying==false) {
try {
mPlayer = new MediaPlayer();
isPlaying=true;
Log.d("Audio startPlaying", "audio: " + file);
if (isStreaming(file))
{
Log.d("AudioStartPlaying", "Streaming");
// Streaming prepare async
mPlayer.setDataSource(file);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.prepareAsync();
} else {
Log.d("AudioStartPlaying", "File");
// Not streaming prepare synchronous, abstract base directory
mPlayer.setDataSource("/sdcard/" + file);
mPlayer.prepare();
}
mPlayer.setOnPreparedListener(this);
} catch (Exception e) { e.printStackTrace(); }
}
}
protected void stopPlaying() {
if (isPlaying) {
mPlayer.stop();
mPlayer.release();
isPlaying=false;
}
}
public void onCompletion(MediaPlayer mPlayer) {
mPlayer.stop();
mPlayer.release();
isPlaying=false;
}
protected long getCurrentPosition() {
if (isPlaying)
{
return(mPlayer.getCurrentPosition());
} else { return(-1); }
}
private boolean isStreaming(String file)
{
if (file.contains("http://")) {
return true;
} else {
return false;
}
}
protected long getDuration(String file) {
long duration = -2;
if (!isPlaying & !isStreaming(file)) {
try {
mPlayer = new MediaPlayer();
mPlayer.setDataSource("/sdcard/" + file);
mPlayer.prepare();
duration = mPlayer.getDuration();
mPlayer.release();
} catch (Exception e) { e.printStackTrace(); return(-3); }
} else
if (isPlaying & !isStreaming(file)) {
duration = mPlayer.getDuration();
} else
if (isPlaying & isStreaming(file)) {
try {
duration = mPlayer.getDuration();
} catch (Exception e) { e.printStackTrace(); return(-4); }
}else { return -1; }
return duration;
}
public void onPrepared(MediaPlayer mPlayer) {
if (isPlaying) {
mPlayer.setOnCompletionListener(this);
mPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener()
{
public void onBufferingUpdate(MediaPlayer mPlayer, int percent)
{
/* TODO: call back, e.g. update outer progress bar */
Log.d("AudioOnBufferingUpdate", "percent: " + percent);
}
});
mPlayer.start();
}
}
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
Log.e("AUDIO onError", "error " + arg1 + " " + arg2);
return false;
}
protected void setAudioOutputDevice(int output){
// Changes the default audio output device to speaker or earpiece
AudioManager audiMgr = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
if (output == (2))
audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);
else if (output == (1)){
audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
}else
Log.e("AudioHandler setAudioOutputDevice", " unknown output device");
}
protected int getAudioOutputDevice(){
AudioManager audiMgr = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE)
return 1;
else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER)
return 2;
else
return -1;
}
}

View File

@@ -1,58 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class CameraHandler implements PictureCallback{
private OutputStream oStream;
BitmapFactory photoLab;
CameraHandler(OutputStream output)
{
oStream = output;
}
public void onPictureTaken(byte[] graphic, Camera arg1) {
try {
oStream.write(graphic);
oStream.flush();
oStream.close();
}
catch (Exception ex)
{
//TO-DO: Put some logging here saying that this epic failed
}
// Do some other things, like post it to a service!
}
}

View File

@@ -1,73 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.ContentValues;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.provider.MediaStore.Images.Media;
public class CameraListener implements ShutterCallback{
private Camera mCam;
private CameraHandler camHand;
private SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
private Context mCtx;
private Uri target = Media.EXTERNAL_CONTENT_URI;
CameraListener(Context ctx){
mCam = Camera.open();
mCtx = ctx;
}
public void snap()
{
String filename = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(Media.TITLE, filename);
values.put(Media.DESCRIPTION, "PhoneGap");
Uri uri = mCtx.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
try
{
OutputStream output = (OutputStream) mCtx.getContentResolver().openOutputStream(uri);
camHand = new CameraHandler(output);
mCam.takePicture(this, null, camHand);
}
catch (Exception ex)
{
/*TODO: Do some logging here */
}
}
public void onShutter() {
/* This is logged */
}
}

View File

@@ -1,126 +0,0 @@
package com.phonegap.demo;
import java.io.File;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
public class DirectoryManager {
protected boolean testFileExists (String name){
boolean status;
if ((testSaveLocationExists())&&(!name.equals(""))){
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), name);
status = newPath.exists();
}else{
status = false;
}
return status;
}
protected long getFreeDiskSpace(){
/*
* gets the available SD card free space or returns -1 if the SD card is not mounted.
*/
String status = Environment.getExternalStorageState();
long freeSpace = 0;
if (status.equals(Environment.MEDIA_MOUNTED)) {
try {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
freeSpace = availableBlocks*blockSize/1024;
} catch (Exception e) {e.printStackTrace(); }
} else { return -1; }
return (freeSpace);
}
protected boolean createDirectory(String directoryName){
boolean status;
if ((testSaveLocationExists())&&(!directoryName.equals(""))){
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), directoryName);
status = newPath.mkdir();
status = true;
}else
status = false;
return status;
}
protected boolean testSaveLocationExists(){
String sDCardStatus = Environment.getExternalStorageState();
boolean status;
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)){
status = true;
}else
status = false;
return status;
}
protected boolean deleteDirectory(String fileName){
boolean status;
SecurityManager checker = new SecurityManager();
if ((testSaveLocationExists())&&(!fileName.equals(""))){
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), fileName);
checker.checkDelete(newPath.toString());
if(newPath.isDirectory()){
String[] listfile = newPath.list();
// delete all files within the specified directory and then delete the directory
try{
for (int i=0; i < listfile.length; i++){
File deletedFile = new File (newPath.toString()+"/"+listfile[i].toString());
deletedFile.delete();
}
newPath.delete();
Log.i("DirectoryManager deleteDirectory", fileName);
status = true;
}catch (Exception e){
e.printStackTrace();
status = false;
}
}else
status = false;
}else
status = false;
return status;
}
protected boolean deleteFile(String fileName){
boolean status;
SecurityManager checker = new SecurityManager();
if ((testSaveLocationExists())&&(!fileName.equals(""))){
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), fileName);
checker.checkDelete(newPath.toString());
if (newPath.isFile()){
try {
Log.i("DirectoryManager deleteFile", fileName);
newPath.delete();
status = true;
}catch (SecurityException se){
se.printStackTrace();
status = false;
}
}else
status = false;
}else
status = false;
return status;
}
private File constructFilePaths (String file1, String file2){
File newPath;
newPath = new File(file1+"/"+file2);
return newPath;
}
}

View File

@@ -1,126 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* Software), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.lang.reflect.Field;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class DroidGap extends Activity {
private static final String LOG_TAG = "DroidGap";
private WebView appView;
private String uri;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(R.layout.main);
appView = (WebView) findViewById(R.id.appView);
/* This changes the setWebChromeClient to log alerts to LogCat! Important for Javascript Debugging */
appView.setWebChromeClient(new GapClient(this));
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
/* Bind the appView object to the gap class methods */
bindBrowser(appView);
/* Load a URI from the strings.xml file */
Class<R.string> c = R.string.class;
Field f;
int i = 0;
try {
f = c.getField("url");
i = f.getInt(f);
this.uri = this.getResources().getString(i);
} catch (Exception e)
{
this.uri = "http://www.phonegap.com";
}
appView.loadUrl(this.uri);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
//don't reload the current page when the orientation is changed
super.onConfigurationChanged(newConfig);
}
private void bindBrowser(WebView appView)
{
// The PhoneGap class handles the Notification and Android Specific crap
PhoneGap gap = new PhoneGap(this, appView);
GeoBroker geo = new GeoBroker(appView, this);
AccelListener accel = new AccelListener(this, appView);
// This creates the new javascript interfaces for PhoneGap
appView.addJavascriptInterface(gap, "Device");
appView.addJavascriptInterface(geo, "Geo");
appView.addJavascriptInterface(accel, "Accel");
}
/**
* Provides a hook for calling "alert" from javascript. Useful for
* debugging your javascript.
*/
final class GapClient extends WebChromeClient {
Context mCtx;
GapClient(Context ctx)
{
mCtx = ctx;
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
// This shows the dialog box. This can be commented out for dev
AlertDialog.Builder alertBldr = new AlertDialog.Builder(mCtx);
alertBldr.setMessage(message);
alertBldr.setTitle("Alert");
alertBldr.show();
result.confirm();
return true;
}
}
}

View File

@@ -1,41 +0,0 @@
package com.phonegap.demo;
import java.util.HashMap;
import android.content.Context;
import android.webkit.WebView;
/*
* This class is the interface to the Geolocation. It's bound to the geo object.
*
* This class only starts and stops various GeoListeners, which consist of a GPS and a Network Listener
*/
public class GeoBroker {
private WebView mAppView;
private Context mCtx;
private HashMap<String, GeoListener> geoListeners;
GeoBroker(WebView view, Context ctx)
{
mCtx = ctx;
mAppView = view;
}
public void getCurrentLocation()
{
GeoListener listener = new GeoListener("global", mCtx, 10000, mAppView);
}
public String start(int freq, String key)
{
GeoListener listener = new GeoListener(key, mCtx, freq, mAppView);
geoListeners.put(key, listener);
return key;
}
public void stop(String key)
{
GeoListener geo = geoListeners.get(key);
}
}

View File

@@ -1,63 +0,0 @@
package com.phonegap.demo;
import android.content.Context;
import android.location.Location;
import android.webkit.WebView;
public class GeoListener {
String id;
String successCallback;
String failCallback;
GpsListener mGps;
NetworkListener mNetwork;
Context mCtx;
private WebView mAppView;
int interval;
GeoListener(String i, Context ctx, int time, WebView appView)
{
id = i;
interval = time;
mCtx = ctx;
mGps = new GpsListener(mCtx, interval, this);
mNetwork = new NetworkListener(mCtx, interval, this);
mAppView = appView;
}
void success(Location loc)
{
/*
* We only need to figure out what we do when we succeed!
*/
if(id != "global")
{
mAppView.loadUrl("javascript:Geolocation.success(" + id + ", " + loc.getLatitude() + ", " + loc.getLongitude() + ")");
}
else
{
mAppView.loadUrl("javascript:Geolocation.gotCurrentPosition(" + loc.getLatitude() + ", " + loc.getLongitude() + ")");
this.stop();
}
}
void fail()
{
// Do we need to know why? How would we handle this?
mAppView.loadUrl("javascript:GeoLocation.fail(" + id + ")");
}
// This stops the listener
void stop()
{
mGps.stop();
mNetwork.stop();
}
public Location getCurrentLocation() {
Location loc = mGps.getLocation();
if (loc == null)
loc = mNetwork.getLocation();
return loc;
}
}

View File

@@ -1,32 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class GeoTuple {
public double lat;
public double lng;
public double ele;
}

View File

@@ -1,97 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class GpsListener implements LocationListener {
private Context mCtx;
private Location cLoc;
private LocationManager mLocMan;
private static final String LOG_TAG = "PhoneGap";
private GeoListener owner;
public GpsListener(Context ctx, int interval, GeoListener m)
{
owner = m;
mCtx = ctx;
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval, 0, this);
cLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
public Location getLocation()
{
cLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return cLoc;
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "The provider " + provider + " is disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "The provider "+ provider + " is enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "The status of the provider " + provider + " has changed");
if(status == 0)
{
Log.d(LOG_TAG, provider + " is OUT OF SERVICE");
}
else if(status == 1)
{
Log.d(LOG_TAG, provider + " is TEMPORARILY_UNAVAILABLE");
}
else
{
Log.d(LOG_TAG, provider + " is Available");
}
}
public void onLocationChanged(Location location) {
Log.d(LOG_TAG, "The location has been updated!");
owner.success(location);
}
public boolean hasLocation() {
return (cLoc != null);
}
public void stop()
{
mLocMan.removeUpdates(this);
}
}

View File

@@ -1,65 +0,0 @@
package com.phonegap.demo;
import java.io.EOFException;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpHandler {
protected Boolean get(String url, String file)
{
HttpEntity entity = getHttpEntity(url);
try {
writeToDisk(entity, file);
} catch (Exception e) { e.printStackTrace(); return false; }
try {
entity.consumeContent();
} catch (Exception e) { e.printStackTrace(); return false; }
return true;
}
private HttpEntity getHttpEntity(String url)
/**
* get the http entity at a given url
*/
{
HttpEntity entity=null;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
entity = response.getEntity();
} catch (Exception e) { e.printStackTrace(); return null; }
return entity;
}
private void writeToDisk(HttpEntity entity, String file) throws EOFException
/**
* writes a HTTP entity to the specified filename and location on disk
*/
{
int i=0;
String FilePath="/sdcard/" + file;
try {
InputStream in = entity.getContent();
byte buff[] = new byte[1024];
FileOutputStream out=
new FileOutputStream(FilePath);
do {
int numread = in.read(buff);
if (numread <= 0)
break;
out.write(buff, 0, numread);
System.out.println("numread" + numread);
i++;
} while (true);
out.flush();
out.close();
} catch (Exception e) { e.printStackTrace(); }
}
}

View File

@@ -1,102 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class NetworkListener implements LocationListener {
private Context mCtx;
private Location cLoc;
private LocationManager mLocMan;
private static final String LOG_TAG = "PhoneGap";
GeoListener owner;
public NetworkListener(Context ctx, int interval, GeoListener m)
{
owner = m;
mCtx = ctx;
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval, 0, this);
cLoc = mLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
public Location getLocation()
{
cLoc = mLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return cLoc;
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "The provider " + provider + " is disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "The provider "+ provider + " is enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "The status of the provider " + provider + " has changed");
if(status == 0)
{
Log.d(LOG_TAG, provider + " is OUT OF SERVICE");
}
else if(status == 1)
{
Log.d(LOG_TAG, provider + " is TEMPORARILY_UNAVAILABLE");
}
else
{
Log.d(LOG_TAG, provider + " is Available");
}
}
/*
* The GPS is the primary form of Geolocation in PhoneGap. Only fire the success variables if the GPS is down
* for some reason
*/
public void onLocationChanged(Location location) {
Log.d(LOG_TAG, "The location has been updated!");
if (!owner.mGps.hasLocation())
{
owner.success(location);
}
cLoc = location;
}
public void stop()
{
mLocMan.removeUpdates(this);
}
}

View File

@@ -1,69 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* “Software”), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import android.content.Context;
import android.hardware.SensorManager;
import android.hardware.SensorListener;
import android.webkit.WebView;
public class Orientation implements SensorListener{
private WebView mAppView;
private SensorManager sensorManager;
private Context mCtx;
Orientation(WebView kit, Context ctx) {
mAppView = kit;
mCtx = ctx;
sensorManager = (SensorManager) mCtx.getSystemService(Context.SENSOR_SERVICE);
this.resumeAccel();
}
public void onSensorChanged(int sensor, final float[] values) {
if (sensor != SensorManager.SENSOR_ACCELEROMETER || values.length < 3)
return;
float x = values[0];
float y = values[1];
float z = values[2];
mAppView.loadUrl("javascript:gotAcceleration(" + x + ", " + y + "," + z + ")");
}
public void onAccuracyChanged(int arg0, int arg1) {
// This is a stub method.
}
public void pauseAccel()
{
sensorManager.unregisterListener(this);
}
public void resumeAccel()
{
sensorManager.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
}
}

View File

@@ -1,306 +0,0 @@
package com.phonegap.demo;
/* License (MIT)
* Copyright (c) 2008 Nitobi
* website: http://phonegap.com
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* Software), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.IOException;
import java.util.TimeZone;
import android.content.Context;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.webkit.WebView;
import android.media.Ringtone;
import android.media.RingtoneManager;
public class PhoneGap{
private static final String LOG_TAG = "PhoneGap";
/*
* UUID, version and availability
*/
public boolean droid = true;
public static String version = "0.2";
public static String platform = "Android";
public static String uuid;
private Context mCtx;
private WebView mAppView;
SmsListener mSmsListener;
DirectoryManager fileManager;
AudioHandler audio;
public PhoneGap(Context ctx, WebView appView) {
this.mCtx = ctx;
this.mAppView = appView;
mSmsListener = new SmsListener(ctx,mAppView);
fileManager = new DirectoryManager();
audio = new AudioHandler("/sdcard/tmprecording.mp3", ctx);
uuid = getUuid();
}
public void beep(long pattern)
{
RingtoneManager beeper = new RingtoneManager(mCtx);
Uri ringtone = beeper.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = beeper.getRingtone(mCtx, ringtone);
notification.play();
}
public void vibrate(long pattern){
// Start the vibration, 0 defaults to half a second.
if (pattern == 0)
pattern = 500;
Vibrator vibrator = (Vibrator) mCtx.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern);
}
public String getPlatform()
{
return this.platform;
}
public String getUuid()
{
TelephonyManager operator = (TelephonyManager) mCtx.getSystemService(Context.TELEPHONY_SERVICE);
String uuid = operator.getDeviceId();
return uuid;
}
public void init()
{
mAppView.loadUrl("javascript:Device.setData('Android','" + version + "','" + this.getUuid() + "')");
}
public String getModel()
{
String model = android.os.Build.MODEL;
return model;
}
public String getProductName()
{
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getOSVersion()
{
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion()
{
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getVersion()
{
return version;
}
// Old SMS code, figure out what to do with this!
// BTW: This is awesome!
public void notificationWatchPosition(String filter)
/**
* Starts the listener for incoming notifications of type filter
* TODO: JavaScript Call backs for success and error handling. More filter types.
*/
{
if (filter.contains("SMS"))
{
IntentFilter mFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
mCtx.registerReceiver(mSmsListener,mFilter);
}
}
public void notificationClearWatch(String filter)
/**
* Stops the listener for incoming notifications of type filter
* TODO: JavaScript Call backs for success and error handling
*/
{
if (filter.contains("SMS"))
{
mCtx.unregisterReceiver(mSmsListener);
}
}
public void httpGet(String url, String file)
/**
* grabs a file from specified url and saves it to a name and location
* the base directory /sdcard is abstracted so that paths may be the same from one mobile OS to another
* TODO: JavaScript call backs and error handling
*/
{
HttpHandler http = new HttpHandler();
http.get(url, file);
}
public int testSaveLocationExists(){
if (fileManager.testSaveLocationExists())
return 0;
else
return 1;
}
public long getFreeDiskSpace(){
long freeDiskSpace=fileManager.getFreeDiskSpace();
return freeDiskSpace;
}
public int testFileExists(String file){
if (fileManager.testFileExists(file))
return 0;
else
return 1;
}
public int testDirectoryExists(String file){
if (fileManager.testFileExists(file))
return 0;
else
return 1;
}
/**
* Delete a specific directory.
* Everyting in side the directory would be gone.
* TODO: JavaScript Call backs for success and error handling
*/
public int deleteDirectory (String dir){
if (fileManager.deleteDirectory(dir))
return 0;
else
return 1;
}
/**
* Delete a specific file.
* TODO: JavaScript Call backs for success and error handling
*/
public int deleteFile (String file){
if (fileManager.deleteFile(file))
return 0;
else
return 1;
}
/**
* Create a new directory.
* TODO: JavaScript Call backs for success and error handling
*/
public int createDirectory(String dir){
if (fileManager.createDirectory(dir))
return 0;
else
return 1;
}
/**
* AUDIO
* TODO: Basic functions done but needs more work on error handling and call backs, remove record hack
*/
public void startRecordingAudio(String file)
{
/* for this to work the recording needs to be specified in the constructor,
* a hack to get around this, I'm moving the recording after it's complete
*/
audio.startRecording(file);
}
public void stopRecordingAudio()
{
audio.stopRecording();
}
public void startPlayingAudio(String file)
{
audio.startPlaying(file);
}
public void stopPlayingAudio()
{
audio.stopPlaying();
}
public long getCurrentPositionAudio()
{
System.out.println(audio.getCurrentPosition());
return(audio.getCurrentPosition());
}
public long getDurationAudio(String file)
{
System.out.println(audio.getDuration(file));
return(audio.getDuration(file));
}
public void setAudioOutputDevice(int output){
audio.setAudioOutputDevice(output);
}
public int getAudioOutputDevice(){
return audio.getAudioOutputDevice();
}
public String getLine1Number() {
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getLine1Number());
}
public String getVoiceMailNumber() {
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getVoiceMailNumber());
}
public String getNetworkOperatorName(){
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getNetworkOperatorName());
}
public String getSimCountryIso(){
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getSimCountryIso());
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return(tz.getID());
}
}

View File

@@ -1,68 +0,0 @@
package com.phonegap.demo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.webkit.WebView;
public class SmsListener extends BroadcastReceiver
{
private WebView mAppView;
public SmsListener(Context ctx, WebView mAppView)
{
this.mAppView = mAppView;
}
String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public void onReceive(Context ctx, Intent intent)
{
SmsMessage[] msg;
if (intent.getAction().equals(ACTION))
{
msg = getMessagesFromIntent(intent);
String smsContent = null;
String sendersNumber = null;
for(int i=0; i < msg.length; i++)
{
sendersNumber = msg[i].getDisplayOriginatingAddress();
smsContent = msg[i].getDisplayMessageBody();
}
onReceiveSMS(sendersNumber, smsContent);
}
}
protected void onReceiveSMS(String sendersNumber, String smsContent)
/**
* Call back to Java Script
*/
{
mAppView.loadUrl("javascript:onReceiveSms('"+sendersNumber+"',"+"'"+ smsContent +"'"+")");
}
private SmsMessage[] getMessagesFromIntent(Intent intent)
{
SmsMessage retMsgs[] = null;
Bundle bdl = intent.getExtras();
try
{
Object pdus[] = (Object [])bdl.get("pdus");
retMsgs = new SmsMessage[pdus.length];
for(int n=0; n < pdus.length; n++)
{
byte[] byteData = (byte[])pdus[n];
retMsgs[n] = SmsMessage.createFromPdu(byteData);
}
} catch(Exception e)
{
Log.e("SMS_getMessagesFromIntent", "fail", e);
}
return retMsgs;
}
}

View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/NET_RIM_BLACKBERRY"/>
<classpathentry kind="src" path=".tmp"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>phonegap</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>net.rim.eide.RIMResourcesBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>net.rim.eide.PreprocessBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>net.rim.eide.JavaIncrementalProjectBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>net.rim.eide.rimnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>net.rim.eide.PreprocessingNature</nature>
</natures>
</projectDescription>

View File

@@ -1,3 +0,0 @@
#Fri May 15 15:56:25 CEST 2009
RIM.BLACKBERRY.TYPE=COPY
eclipse.preferences.version=1

View File

@@ -1,5 +0,0 @@
#Sat May 16 13:53:35 CEST 2009
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
org.eclipse.jdt.core.compiler.compliance=1.4
org.eclipse.jdt.core.compiler.source=1.3

View File

@@ -1,3 +0,0 @@
# GAP
### Blackberry

Some files were not shown because too many files have changed in this diff Show More