From 22f3d8256ed2fc0380e6b5a93bb01542645efbc7 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 1 Apr 2009 16:56:43 -0700 Subject: [PATCH] Refactored because of translink app --- src/com/phonegap/demo/AccelListener.java | 59 ++++ src/com/phonegap/demo/AccelTuple.java | 29 ++ src/com/phonegap/demo/AudioHandler.java | 177 +++++++++++ src/com/phonegap/demo/CameraHandler.java | 58 ++++ src/com/phonegap/demo/CameraListener.java | 73 +++++ src/com/phonegap/demo/DirectoryManager.java | 126 ++++++++ src/com/phonegap/demo/DroidGap.java | 126 ++++++++ src/com/phonegap/demo/GeoBroker.java | 41 +++ src/com/phonegap/demo/GeoListener.java | 63 ++++ src/com/phonegap/demo/GeoTuple.java | 32 ++ src/com/phonegap/demo/GpsListener.java | 97 +++++++ src/com/phonegap/demo/HttpHandler.java | 65 +++++ src/com/phonegap/demo/NetworkListener.java | 102 +++++++ src/com/phonegap/demo/Orientation.java | 69 +++++ src/com/phonegap/demo/PhoneGap.java | 306 ++++++++++++++++++++ src/com/phonegap/demo/R.java | 31 ++ src/com/phonegap/demo/SmsListener.java | 68 +++++ 17 files changed, 1522 insertions(+) create mode 100644 src/com/phonegap/demo/AccelListener.java create mode 100644 src/com/phonegap/demo/AccelTuple.java create mode 100644 src/com/phonegap/demo/AudioHandler.java create mode 100644 src/com/phonegap/demo/CameraHandler.java create mode 100644 src/com/phonegap/demo/CameraListener.java create mode 100644 src/com/phonegap/demo/DirectoryManager.java create mode 100644 src/com/phonegap/demo/DroidGap.java create mode 100644 src/com/phonegap/demo/GeoBroker.java create mode 100644 src/com/phonegap/demo/GeoListener.java create mode 100644 src/com/phonegap/demo/GeoTuple.java create mode 100644 src/com/phonegap/demo/GpsListener.java create mode 100644 src/com/phonegap/demo/HttpHandler.java create mode 100644 src/com/phonegap/demo/NetworkListener.java create mode 100644 src/com/phonegap/demo/Orientation.java create mode 100644 src/com/phonegap/demo/PhoneGap.java create mode 100644 src/com/phonegap/demo/R.java create mode 100644 src/com/phonegap/demo/SmsListener.java diff --git a/src/com/phonegap/demo/AccelListener.java b/src/com/phonegap/demo/AccelListener.java new file mode 100644 index 00000000..a2cb1c0c --- /dev/null +++ b/src/com/phonegap/demo/AccelListener.java @@ -0,0 +1,59 @@ +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); + } + + @Override + public void onAccuracyChanged(int sensor, int accuracy) { + // This should call the FAIL method + } + @Override + 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 + " )"); + } + } + + +} diff --git a/src/com/phonegap/demo/AccelTuple.java b/src/com/phonegap/demo/AccelTuple.java new file mode 100644 index 00000000..95a101a1 --- /dev/null +++ b/src/com/phonegap/demo/AccelTuple.java @@ -0,0 +1,29 @@ +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; +} diff --git a/src/com/phonegap/demo/AudioHandler.java b/src/com/phonegap/demo/AudioHandler.java new file mode 100644 index 00000000..6371859b --- /dev/null +++ b/src/com/phonegap/demo/AudioHandler.java @@ -0,0 +1,177 @@ +package com.phonegap.demo; + +import java.io.File; + +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); + recorder.prepare(); + 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; + } +} diff --git a/src/com/phonegap/demo/CameraHandler.java b/src/com/phonegap/demo/CameraHandler.java new file mode 100644 index 00000000..13c64bd6 --- /dev/null +++ b/src/com/phonegap/demo/CameraHandler.java @@ -0,0 +1,58 @@ +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! + } + + +} diff --git a/src/com/phonegap/demo/CameraListener.java b/src/com/phonegap/demo/CameraListener.java new file mode 100644 index 00000000..68ca1770 --- /dev/null +++ b/src/com/phonegap/demo/CameraListener.java @@ -0,0 +1,73 @@ +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 */ + + } + +} diff --git a/src/com/phonegap/demo/DirectoryManager.java b/src/com/phonegap/demo/DirectoryManager.java new file mode 100644 index 00000000..ef91d240 --- /dev/null +++ b/src/com/phonegap/demo/DirectoryManager.java @@ -0,0 +1,126 @@ +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; + } + +} \ No newline at end of file diff --git a/src/com/phonegap/demo/DroidGap.java b/src/com/phonegap/demo/DroidGap.java new file mode 100644 index 00000000..4fc09e32 --- /dev/null +++ b/src/com/phonegap/demo/DroidGap.java @@ -0,0 +1,126 @@ +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 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; + } + } + +} \ No newline at end of file diff --git a/src/com/phonegap/demo/GeoBroker.java b/src/com/phonegap/demo/GeoBroker.java new file mode 100644 index 00000000..682e010b --- /dev/null +++ b/src/com/phonegap/demo/GeoBroker.java @@ -0,0 +1,41 @@ +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 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); + } +} diff --git a/src/com/phonegap/demo/GeoListener.java b/src/com/phonegap/demo/GeoListener.java new file mode 100644 index 00000000..5a05328a --- /dev/null +++ b/src/com/phonegap/demo/GeoListener.java @@ -0,0 +1,63 @@ +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; + } +} diff --git a/src/com/phonegap/demo/GeoTuple.java b/src/com/phonegap/demo/GeoTuple.java new file mode 100644 index 00000000..e6272cbb --- /dev/null +++ b/src/com/phonegap/demo/GeoTuple.java @@ -0,0 +1,32 @@ +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; + +} diff --git a/src/com/phonegap/demo/GpsListener.java b/src/com/phonegap/demo/GpsListener.java new file mode 100644 index 00000000..a4e531ba --- /dev/null +++ b/src/com/phonegap/demo/GpsListener.java @@ -0,0 +1,97 @@ +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); + } + +} diff --git a/src/com/phonegap/demo/HttpHandler.java b/src/com/phonegap/demo/HttpHandler.java new file mode 100644 index 00000000..bd26d75f --- /dev/null +++ b/src/com/phonegap/demo/HttpHandler.java @@ -0,0 +1,65 @@ +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(); } + } +} diff --git a/src/com/phonegap/demo/NetworkListener.java b/src/com/phonegap/demo/NetworkListener.java new file mode 100644 index 00000000..2db7b8c6 --- /dev/null +++ b/src/com/phonegap/demo/NetworkListener.java @@ -0,0 +1,102 @@ +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); + } + +} diff --git a/src/com/phonegap/demo/Orientation.java b/src/com/phonegap/demo/Orientation.java new file mode 100644 index 00000000..755e4156 --- /dev/null +++ b/src/com/phonegap/demo/Orientation.java @@ -0,0 +1,69 @@ +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); + } + +} diff --git a/src/com/phonegap/demo/PhoneGap.java b/src/com/phonegap/demo/PhoneGap.java new file mode 100644 index 00000000..aa319cd7 --- /dev/null +++ b/src/com/phonegap/demo/PhoneGap.java @@ -0,0 +1,306 @@ +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()); + } + +} + diff --git a/src/com/phonegap/demo/R.java b/src/com/phonegap/demo/R.java new file mode 100644 index 00000000..75eced2a --- /dev/null +++ b/src/com/phonegap/demo/R.java @@ -0,0 +1,31 @@ +/* AUTO-GENERATED FILE. DO NOT MODIFY. + * + * This class was automatically generated by the + * aapt tool from the resource data it found. It + * should not be modified by hand. + */ + +package com.phonegap.demo; + +public final class R { + public static final class attr { + } + public static final class drawable { + public static final int icon=0x7f020000; + } + public static final class id { + public static final int appView=0x7f060000; + } + public static final class layout { + public static final int main=0x7f030000; + } + public static final class raw { + public static final int bird=0x7f040000; + public static final int off=0x7f040001; + public static final int on=0x7f040002; + } + public static final class string { + public static final int app_name=0x7f050000; + public static final int url=0x7f050001; + } +} diff --git a/src/com/phonegap/demo/SmsListener.java b/src/com/phonegap/demo/SmsListener.java new file mode 100644 index 00000000..57c61ba6 --- /dev/null +++ b/src/com/phonegap/demo/SmsListener.java @@ -0,0 +1,68 @@ +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; + } + +} +