SecureAlert Android Source Code

Secure Alert
ConfigEditor.java
package com.jcarx.securealert;
/*
 * netsolvers.net (c) 2012
 *
 * @author Ravi Manthena
 */
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
//import android.widget.EditText;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;

public class ConfigEditor extends Activity{
	
	private static final String TAG = "ConfigEditor";
	private Button backB = null;
	private Button saveB = null;
	private Spinner pranksoundspinner = null; 
	private Spinner alertsoundspinner = null; 
	private SeekBar sensativityB = null;
	private EditText phonenumber = null;
	private EditText smsnumber = null;
	private CheckBox vibratechkbox = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pref);
        
        // cop,lion,tiger,wolf
        
        // see what the user alreadys has 
        SharedPreferences soloPrefs = this.getSharedPreferences("soloPrefs", MODE_WORLD_READABLE);
		String pranksoundtouseuserpref = soloPrefs.getString("pranksoundtouse", "nothing");
		String alertsoundtouseuserpref = soloPrefs.getString("alertsoundtouse", "nothing");
		String sensitivityleveluserpref = soloPrefs.getString("sensitivitylevel", "nothing");
		String phonenumbertouseuserpref = soloPrefs.getString("phonenumbertouse", "nothing");
		String smsnumbertouseuserpref = soloPrefs.getString("smsnumbertouse", "nothing");
		String vibratepref = soloPrefs.getString("vibratechkboxuse", "nothing");
		
		String debuguserpref = 
		"pranksoundtouseuserpref="+pranksoundtouseuserpref+" " +
		"\nalertsoundtouseuserpref="+alertsoundtouseuserpref+" " +
		"\nsensitivityleveluserpref="+sensitivityleveluserpref   +
		"\nphonenumbertouseuserpref="+phonenumbertouseuserpref  + 
		"\nsmsnumbertouseuserpref="+smsnumbertouseuserpref +
		"\nvibratechkboxuse="+vibratepref
		;
		
		Log.d(TAG, debuguserpref);
    	
		Toast.makeText(getApplicationContext(),
				"Saving your configurations"+debuguserpref,
				Toast.LENGTH_LONG).show();
			
		sensativityB = (SeekBar) findViewById(R.id.sensitivityB);
        sensativityB.setMax(10);
        sensativityB.setProgress(Integer.parseInt(sensitivityleveluserpref));
        
        pranksoundspinner = (Spinner) findViewById(R.id.pranksound);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        		  this, R.array.pranksoundslist, android.R.layout.simple_spinner_item );
        		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
        pranksoundspinner.setAdapter(adapter);		
        int pranksoundsPosition = adapter.getPosition(pranksoundtouseuserpref.trim());
        Log.d(TAG, "Prank sounds picked = "+pranksoundtouseuserpref+ " ="+String.valueOf(pranksoundsPosition));
        //set the default according to value
        pranksoundspinner.setSelection(pranksoundsPosition);
	
        alertsoundspinner = (Spinner) findViewById(R.id.alertsound);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
        		  this, R.array.alertsoundslist, android.R.layout.simple_spinner_item );
        		adapter2.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
        alertsoundspinner.setAdapter(adapter2);
        int alertsoundPosition = adapter2.getPosition(alertsoundtouseuserpref.trim());
        Log.d(TAG, "Prank sounds picked = "+alertsoundtouseuserpref+ " ="+String.valueOf(alertsoundPosition));
        //set the default according to value
        alertsoundspinner.setSelection(alertsoundPosition);
        
        vibratechkbox = (CheckBox)findViewById(R.id.vibrateCheckBox);
        if(vibratepref.equals("false")){
        	vibratechkbox.setSelected(false);
        }else{
         	vibratechkbox.setSelected(true);
        }
        
        phonenumber = (EditText)findViewById(R.id.phonenumber);
    	phonenumber.setText(phonenumbertouseuserpref);
    	
    	smsnumber = (EditText)findViewById(R.id.smsnumber);
    	smsnumber.setText(smsnumbertouseuserpref);
    	
        backB = (Button) findViewById(R.id.backB);
        backB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
		    		Intent intent = new Intent();
		    		intent.setClass( ConfigEditor.this, SecureAlertActivity.class);
		    		startActivity(intent);
		    		finish();
		    	}catch(Exception x){
		    			x.printStackTrace();
		    	}
			}
       });
       
       saveB = (Button) findViewById(R.id.saveB);
       saveB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
					saveuserpref();
				}catch(Exception x){
		    			x.printStackTrace();
		    	}
			}
       });
    }
    
    public void saveuserpref(){
		try{
			String pranksoundtouse = (String)pranksoundspinner.getSelectedItem();
			String alertsoundtouse = (String)alertsoundspinner.getSelectedItem();
			String sensitivitylevel = Integer.toString(sensativityB.getProgress());
			String phonenumbertouse = phonenumber.getText().toString();
			String smsnumbertouse = smsnumber.getText().toString();
			String vibratechkboxuse = ""; 
			if(vibratechkbox.isChecked()){
				vibratechkboxuse = "true";
			}else{
				vibratechkboxuse = "false";
			}
			
			
			String debug = "pranksoundtouse="+pranksoundtouse+" " +
					"\nalertsoundtouse="+alertsoundtouse+" " +
					"\nsensitivitylevel="+sensitivitylevel   +
					"\nphonenumbertouse="+phonenumbertouse  + 
					"\nsmsnumbertouse="+smsnumbertouse +
					"\nvibratechkboxuse="+vibratechkboxuse
					;
			
			// save pref
			SharedPreferences myPrefs = this.getSharedPreferences("soloPrefs", MODE_WORLD_READABLE);
			SharedPreferences.Editor prefsEditor = myPrefs.edit();
			prefsEditor.putString("pranksoundtouse", pranksoundtouse);
			prefsEditor.putString("alertsoundtouse", alertsoundtouse);
			prefsEditor.putString("sensitivitylevel", sensitivitylevel);
			prefsEditor.putString("phonenumbertouse", phonenumbertouse);
			prefsEditor.putString("smsnumbertouse", smsnumbertouse);
			prefsEditor.putString("vibratechkboxuse",vibratechkboxuse);
			prefsEditor.commit();
			
			Log.d(TAG, debug);
	    	
			Toast.makeText(getApplicationContext(),
					"Saving your configurations"+debug,
					Toast.LENGTH_LONG).show();
			
		}catch(Exception x){
    			x.printStackTrace();
    	}
    }
}
Contact.java
package com.jcarx.securealert;
/*
 * netsolvers.net (c) 2012
 *
 * @author Ravi Manthena
 */

public class Contact {
	 
    //private variables
    String _id;
    String _name;
    String _phone_number;
 
    // Empty constructor
    public Contact(){
 
    }
    // constructor
    public Contact(String id, String name, String _phone_number){
        this._id = id;
        this._name = name;
        this._phone_number = _phone_number;
    }
 
    // constructor
    public Contact(String name, String _phone_number){
        this._name = name;
        this._phone_number = _phone_number;
    }
    // getting ID
    public String getID(){
        return this._id;
    }
 
    // setting id
    public void setID(String id){
        this._id = id;
    }
 
    // getting name
    public String getName(){
        return this._name;
    }
 
    // setting name
    public void setName(String name){
        this._name = name;
    }
 
    // getting phone number
    public String getPhoneNumber(){
        return this._phone_number;
    }
 
    // setting phone number
    public void setPhoneNumber(String phone_number){
        this._phone_number = phone_number;
    }
}
DatabaseHandler.java
package com.jcarx.securealert;
/*
 * netsolvers.net (c) 2012
 *
 * @author Ravi Manthena
 */

import java.util.ArrayList;
import java.util.List;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class DatabaseHandler extends SQLiteOpenHelper {
 
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
 
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
 
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
 
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " TEXT PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
 
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
 
        // Create tables again
        onCreate(db);
    }
 
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
 
    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
 
        // Inserting Row
        db.insert(TABLE_CONTACTS, "Stuff", values);
        db.close(); // Closing database connection
    }
 
    // Getting single contact
    Contact getContact(String id) {
        SQLiteDatabase db = this.getReadableDatabase();
 
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { id }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
 
        Contact contact = new Contact(cursor.getString(0),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }
 
    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
 
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
 
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(cursor.getString(0));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
 
        // return contact list
        return contactList;
    }
 
    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
 
        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }
 
    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }
 
    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
 
        // return count
        return cursor.getCount();
    }
}
GMailSender.java
package com.jcarx.securealert;
/*
 * netsolvers.net (c) 2012
 *
 * @author Ravi Manthena
 */

import javax.activation.DataHandler;   
import javax.activation.DataSource;   
import javax.mail.Message;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeMessage;   
import java.io.ByteArrayInputStream;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.OutputStream;   
import java.security.Security;   
import java.util.Properties;   

public class GMailSender extends javax.mail.Authenticator {   
    private String mailhost = "smtp.gmail.com";   
    private String user;   
    private String password;   
    private Session session;   

    static {   
        Security.addProvider(new com.jcarx.securealert.JSSEProvider());   
    }  

    public GMailSender(String user, String password) {   
        this.user = user;   
        this.password = password;   

        Properties props = new Properties();   
        props.setProperty("mail.transport.protocol", "smtp");   
        props.setProperty("mail.host", mailhost);   
        props.put("mail.smtp.auth", "true");   
        props.put("mail.smtp.port", "465");   
        props.put("mail.smtp.socketFactory.port", "465");   
        props.put("mail.smtp.socketFactory.class",   
                "javax.net.ssl.SSLSocketFactory");   
        props.put("mail.smtp.socketFactory.fallback", "false");   
        props.setProperty("mail.smtp.quitwait", "false");   

        session = Session.getDefaultInstance(props, this);   
    }   

    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
        MimeMessage message = new MimeMessage(session);   
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
        message.setSender(new InternetAddress(sender));   
        message.setSubject(subject);   
        message.setDataHandler(handler);   
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        Transport.send(message);   
        }catch(Exception e){

        }
    }   

    public class ByteArrayDataSource implements DataSource {   
        private byte[] data;   
        private String type;   

        public ByteArrayDataSource(byte[] data, String type) {   
            super();   
            this.data = data;   
            this.type = type;   
        }   

        public ByteArrayDataSource(byte[] data) {   
            super();   
            this.data = data;   
        }   

        public void setType(String type) {   
            this.type = type;   
        }   

        public String getContentType() {   
            if (type == null)   
                return "application/octet-stream";   
            else  
                return type;   
        }   

        public InputStream getInputStream() throws IOException {   
            return new ByteArrayInputStream(data);   
        }   

        public String getName() {   
            return "ByteArrayDataSource";   
        }   

        public OutputStream getOutputStream() throws IOException {   
            throw new IOException("Not Supported");   
        }   
    }   
}  
JSSEProvider.java
package com.jcarx.securealert;

/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Alexander Y. Kleymenov
 * @version $Revision$
 */


import java.security.AccessController;
import java.security.Provider;

public final class JSSEProvider extends Provider {

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}
SecureAlertActivity.java
package com.jcarx.securealert;

/*
 * netsolvers.net (c) 2012
 *
 * @author Ravi Manthena
 */

import java.io.File;
import java.io.IOException;
import java.util.List;


import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.jcarx.util.JCarxFileUtil;

import android.app.Activity;
import android.app.PendingIntent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import android.os.PowerManager;



public class SecureAlertActivity extends Activity implements Runnable{
	ListenToPhoneState listener;
	SensorManager sensorManager; 
	PowerManager pm = null;
	PowerManager.WakeLock wl = null;
	private static final String TAG = "SecureAlertActivity";
    private static String mFileName = null;
    private static String mLogfileroot = null;
    
    EditText statustx = null;
    Button condifB = null; 
    
    private MediaRecorder mRecorder = null;
    private MediaPlayer   mPlayer = null;
    
    private ProgressBar ampP = null;
    
    private boolean writetolog = true;
    
    static final private double EMA_FILTER = 0.6;
    
    private double mEMA = 0.0;
    
	private MediaPlayer mMediaPlayer;
    private static final String MEDIA = "media";
    private static final int LOCAL_AUDIO = 1;
    private static final int STREAM_AUDIO = 2;
    private static final int RESOURCES_AUDIO = 3;
    private static final int LOCAL_VIDEO = 4;
    private static final int STREAM_VIDEO = 5;
    
    // phone moved
    private double moved = 0;
    private boolean playedonce = true;
    
    
    private Thread solothelistner = null;
    
    public Button configb = null;
    
    boolean runner = true;
    
    //View mainLayout = null;
    
    String pranksoundtouseuserpref = "";
	String alertsoundtouseuserpref = "";
	String sensitivityleveluserpref = "";
	String phonenumbertouseuserpref = "";
	String smsnumbertouseuserpref = "";
	String vibrateuserpref = "";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        //mainLayout = findViewById(R.id.relativeLayout1);
        
        ampP = (ProgressBar)findViewById(R.id.progressBar1);
        
        statustx = (EditText)findViewById(R.id.editText1);
        
        //
    	//Log.d(TAG, e1);
		
    	condifB = (Button)findViewById( R.id.configB);
        
        if (writetolog) {
			//fileLogger("Initilazied");
        	Log.d(TAG, " Initilazied");
		}
        
        this.loadthePref();
        
        // load the database
        //loadthedb();
        
        ampP.setVisibility(ProgressBar.VISIBLE);
        ampP.setProgress(0);
        ampP.setMax(15);
        
        //ampEmaP.setVisibility(ProgressBar.VISIBLE);
        //ampEmaP.setProgress(0);
        //ampEmaP.setMax(15);
        
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag");
		wl.acquire();
		
		configb = (Button) findViewById(R.id.configB);
		configb.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
					if(solothelistner != null){
						//solothelistner.suspend();
						//solothelistner.destroy();
						//solothelistner.stop();
						runner = false;
						Thread.sleep(300);
					}
				}catch(Exception x){
					x.printStackTrace();
				}
				Intent intent = new Intent();
				intent.setClass(SecureAlertActivity.this, ConfigEditor.class);
				startActivity(intent);
				//startSubActivity(intent);
				//startActivityForResult(intent);
				//finish();
			}
		});
		
		
        // start the listener thread
		solothelistner = new Thread(this);
		solothelistner.start();
		
		try{
			Thread.sleep(300);
		}catch(Exception x){
			x.printStackTrace();
		}
		sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        
        sensorManager.registerListener(sensorListener, 
                                       SensorManager.SENSOR_ACCELEROMETER,
                                       SensorManager.SENSOR_DELAY_UI);
    }
    
    public void run(){
    	mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mRecorder.setOutputFile("/dev/null"); 
        try{
            mRecorder.prepare();
        }catch(Exception x){
        	x.printStackTrace();
        	
        }
        mRecorder.start();
        mEMA = 0.0;
    	
        //mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //mRecorder.setOutputFile(mFileName);
        //mRecorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+"record.3gp");
        //mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //mRecorder.setOnInfoListener(new listener());
        // try {
        //    mRecorder.prepare();
        // } catch (IOException e) {
        //     Log.d(LOG_TAG, "prepare() failed");
        // }
		
        //ampP.setProgress(0);
        //ampP.setMax(6);
    	//int FREQUENCY = 44100;
    	//int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
    	//AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, FREQUENCY, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
        
        
    	int testprogress = 0;
    	
    	
    	while(runner){
    		try{
    			double amp = mRecorder.getMaxAmplitude()/2700.0;
    			//double amp = ampit;
    			
    			//mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
                
    			//Log.d(TAG, "amp ="+amp);
    			
    			//String test = Double.toString(amp);
    			//statustx.setText(test);
    			
    			int progressamp = getAmpProgress(amp);
    			
    			if(progressamp > Integer.parseInt(sensitivityleveluserpref)){
    				//sendemail(Integer.toString(progressamp));
    				
                    if(vibrateuserpref.equals("true")){
                        vibrate();
                    }		
                    
                    if(mMediaPlayer != null){
                        if(mMediaPlayer.isPlaying()){
                            try{
                                Thread.sleep(300);
                            }catch(Exception x){
                                x.printStackTrace();
                            }
                        }else{
                            playpranksound();			
                        }
                    }else{
                        playpranksound();			
                    }
                    
        		}else{
        			// don;t do anything other than listen
        		}
    			
    			ampP.setProgress(progressamp);
    			
    			Thread.sleep(130);
    			// Reset the Progress
    			ampP.setProgress(0);
    			Thread.sleep(10);
                
    		}catch(Exception x){
    			if (writetolog) {
    				//fileLogger("Exception"+x.toString());
    				Log.d(TAG, "Exception"+x.toString());
    			}
    		}
    	}
    }
    
    public void loadthedb(){
    	try{
            DatabaseHandler db = new DatabaseHandler(this);
            
            /**
             * CRUD Operations
             * */
            // Inserting Contacts
            Log.d(TAG, "Inserting ..");
            
            db.addContact(new Contact("zz","Ravi", "9100000000"));
            
            // Reading all contacts
            Log.d("Reading: ", "Reading all contacts..");
            List<Contact> contacts = db.getAllContacts();      
            
            for (Contact cn : contacts) {
                String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
                // Writing Contacts to log
                Log.d("Inserting Name: ", log);
            }
    	}catch(Exception x){
    		x.printStackTrace();
    	}
    }
    
    public int getAmpProgress(double amp){
    	if((amp > .02 && amp < .05)){
    		return 1;
    	}else if(amp > .05 && amp < .08){
    		return 3;
    	}else if(amp > .08 && amp < .1){
    		return 4;
    	}else if(amp > .1 && amp < 1.2){
    		return 5;
    	}else if(amp > 1.2 && amp < 1.5){
    		return 6;
    	}else if(amp > 1.5 && amp < 2.5){
    		return 7;
    	}else if(amp > 2.5 && amp < 3.0){
    		return 8;
    	}else if(amp > 3.0 && amp < 3.5){
    		return 9;
    	}else if(amp > 3.5 && amp < 4.0){
    		return 10;
    	}else if(amp > 4.0 && amp < 4.5){
    		return 11;
    	}else if(amp > 4.5 && amp < 5.0){
    		return 12;
    	}else if(amp > 5.0 && amp < 5.5){
    		return 13;
    	}else if(amp > 5.5 && amp < 6.){
    		return 14;
    	}else if(amp > 6.0 && amp < 6.5){
    		return 15;
    	}else{
    		return 0;
    	}
    }
    
    private void sendemail(String amp){
    	try {  
    		/*
             GMailSender sender = new GMailSender("@gmail.com", "");
             sender.sendMail("Phone Email Alert Test",   
             "I am the Alert DOG there is something going on in your house "+amp,   
             "email1gmail.com",   
             "email2@yahoo.com");
             */   
    	} catch (Exception e) {   
    		Log.d("SendMail", e.getMessage(), e);   
    	} 
    }
    
    public void playpranksound(){
    	//mainLayout.setBackgroundResource(R.drawable.solo1);
    	try{
    		Log.d(TAG, "Playing Prank Sound ="+pranksoundtouseuserpref);
    		if(pranksoundtouseuserpref.equals("lion")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.lion);
    	    }else if(pranksoundtouseuserpref.equals("wolf")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.wolf);
    	    }else if(pranksoundtouseuserpref.equals("noSnore")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.snore);
    		}else if(pranksoundtouseuserpref.equals("rooster")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.roaster);
    		}else if(pranksoundtouseuserpref.equals("drum")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.drum);
    	    }else if(pranksoundtouseuserpref.equals("dog")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.dog);
    	    }else if(pranksoundtouseuserpref.equals("cow")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.cow);
    		}else if(pranksoundtouseuserpref.equals("chimp")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.chimp);
    		}else if(pranksoundtouseuserpref.equals("laughter")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.laughter);
    		}else{
    			mMediaPlayer = MediaPlayer.create(this, R.raw.dog);
    		}
    		
    		mMediaPlayer.setLooping(false);
    		// max volume
    		mMediaPlayer.setVolume(1f,1f);
    		
    		runner = false;
    		
    		mMediaPlayer.start();
        	
    		while(!isstillplayingSound(mMediaPlayer)){
    			// just sleep until sound is done
    		}
    		mMediaPlayer.stop();
    		mMediaPlayer = null;
    		//mainLayout.setBackgroundResource(R.drawable.solo2);	
    		runner = true;
    	}catch(Exception x){
    		x.printStackTrace();
    	}
    }
    
    public boolean isstillplayingSound(MediaPlayer mpl){
    	boolean status = false;
    	try{
    		Thread.sleep(2000);
    		status = mpl.isPlaying();
    	}catch(Exception x){
    		x.printStackTrace();
    	}
    	return status; 
    }
    
    public void playalertsound(){
    	try{
    		Log.d(TAG, "Playing Alert Sound ="+alertsoundtouseuserpref);
    		
    		if(alertsoundtouseuserpref.equals("cop")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.policesiren);
    	    }else if(alertsoundtouseuserpref.equals("wolf")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.wolf);
    	    }else if(alertsoundtouseuserpref.equals("dog")){
    			mMediaPlayer = MediaPlayer.create(this, R.raw.dog);
    		}else{
    			mMediaPlayer = MediaPlayer.create(this, R.raw.policesiren);
    		}
    		
    		//mMediaPlayer.seekTo(10);
    		//mMediaPlayer.setVolume(0.001f, 0.001f);
    		// max volume
    		mMediaPlayer.setVolume(1f,1f);
    		mMediaPlayer.start();
    		mMediaPlayer.setLooping(false);
    		// max volume
    		mMediaPlayer.setVolume(1f,1f);
    		
    		runner = false;
    		
    		mMediaPlayer.start();
        	
    		while(!isstillplayingSound(mMediaPlayer)){
    			// just sleep until sound is done
    		}
    		mMediaPlayer.stop();
    		mMediaPlayer = null;
    		
    		runner = true;
    	}catch(Exception x){
    		x.printStackTrace();
    	}
    }
    
    public void dialnumber(String number){
    	try{
            
    		startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number)));
    		finish();
    	}catch(Exception x){
    		x.printStackTrace();
    	}
    }
    
    private void sendSMS(String phoneNumber, String message)
    {     
    	try{
    		Log.v(TAG,phoneNumber);
    		Log.v(TAG,message);
    		SmsManager sms = SmsManager.getDefault();
    		sms.sendTextMessage(phoneNumber, null, message, null, null);        
    	}catch(Exception x){
    		x.printStackTrace();
    	}    
    }
    
    private void call(String number) {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:"+number));
            startActivity(callIntent);
            
            TelephonyManager tManager = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);
            listener = new ListenToPhoneState();
            tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        } catch (ActivityNotFoundException activityException) {
            Log.d(TAG, "Call failed", activityException);
        }
    }
    
    private class ListenToPhoneState extends PhoneStateListener {
        
        public void onCallStateChanged(int state, String incomingNumber) {
            Log.i(TAG, "State changed: " + stateName(state));
        }
        
        String stateName(int state) {
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE: return "Idle";
                case TelephonyManager.CALL_STATE_OFFHOOK: return "Off hook";
                case TelephonyManager.CALL_STATE_RINGING: return "Ringing";
            }
            return Integer.toString(state);
        }
    }
    
    public void vibrate(){   
        
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    	// This example will cause the phone to vibrate "SOS" in Morse Code
    	// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
    	// There are pauses to separate dots/dashes, letters, and words
    	// The following numbers represent millisecond lengths
    	int dot = 200;      // Length of a Morse Code "dot" in milliseconds
    	int dash = 500;     // Length of a Morse Code "dash" in milliseconds
    	int short_gap = 200;    // Length of Gap Between dots/dashes
    	int medium_gap = 500;   // Length of Gap Between Letters
    	int long_gap = 1000;    // Length of Gap Between Words
    	long[] pattern = {
    		0,  // Start immediately
    		dot, short_gap, dot, short_gap, dot,    // s
    		medium_gap,
    		dash, short_gap, dash, short_gap, dash, // o
    		medium_gap,
    		dot, short_gap, dot, short_gap, dot,    // s
    		long_gap
    	};
        
    	// Only perform this pattern one time (-1 means "do not repeat")
    	v.vibrate(pattern, -1);
 	}
    
    
    public void loadthePref(){
    	try{
    		SharedPreferences soloPrefs = this.getSharedPreferences("soloPrefs", MODE_WORLD_READABLE);
    		pranksoundtouseuserpref = soloPrefs.getString("pranksoundtouse", "nothing");
    		alertsoundtouseuserpref = soloPrefs.getString("alertsoundtouse", "nothing");
    		sensitivityleveluserpref = soloPrefs.getString("sensitivitylevel", "nothing");
    		phonenumbertouseuserpref = soloPrefs.getString("phonenumbertouse", "nothing");
    		smsnumbertouseuserpref = soloPrefs.getString("smsnumbertouse", "nothing");
    		vibrateuserpref = soloPrefs.getString("vibratechkboxuse", "nothing");
            
    		String debuguserpref = 
            "pranksoundtouseuserpref="+pranksoundtouseuserpref+" " +
            "\nalertsoundtouseuserpref="+alertsoundtouseuserpref+" " +
            "\nsensitivityleveluserpref="+sensitivityleveluserpref   +
            "\nphonenumbertouseuserpref="+phonenumbertouseuserpref  + 
            "\nsmsnumbertouseuserpref="+smsnumbertouseuserpref + 
            "\nvibrateuserpref="+ vibrateuserpref
            ;
            
    		// no pref in history so set defaults
    		if(pranksoundtouseuserpref == "nothing"){
    			setdefaultPref();
    			Toast.makeText(getApplicationContext(),
                               "Setting default Configration "+debuguserpref,
                               Toast.LENGTH_LONG).show();
    	    	
    		}
    		
    		Log.d(TAG, debuguserpref);
            
    		//Toast.makeText(getApplicationContext(),
 			//	"Saving your configurations"+debuguserpref,
 			//	Toast.LENGTH_LONG).show();
    	}catch(Exception x){
    		x.printStackTrace();
    	}
    }
    
    public void setdefaultPref(){
    	try{
            SharedPreferences myPrefs = this.getSharedPreferences("soloPrefs", MODE_WORLD_READABLE);
            SharedPreferences.Editor prefsEditor = myPrefs.edit();
            prefsEditor.putString("pranksoundtouse", "wolf");
            prefsEditor.putString("alertsoundtouse", "NoSecurity");
            prefsEditor.putString("sensitivitylevel", "6");
            prefsEditor.putString("phonenumbertouse", "");
            prefsEditor.putString("smsnumbertouse", "");
            prefsEditor.putString("vibratechkboxuse","false");
            prefsEditor.commit();
    	}catch(Exception x){
    		x.printStackTrace();
    	}
	}
    
    protected void onDestroy(){		
		Log.v(TAG, "onDestroy");
		super.onDestroy();
		wl.release();
	    if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
	}
    
    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }
    
    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }
    
    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.d(TAG, "prepare() failed");
        }
    }
    
    private void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }
    
    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //mRecorder.setOutputFile(mFileName);
        //mRecorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+"record.3gp");
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //mRecorder.setOnInfoListener(new listener());
        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.d(TAG, "prepare() failed");
        }
        //mRecorder.start();
    }
    
    class listener implements MediaRecorder.OnInfoListener {
        public void onInfo(MediaRecorder recorder, int what, int extra) {
            Log.d("TAG", "Video Info: "+what+", "+extra);
        }
    }
    
    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
        
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
    
    public static void fileLogger(String content) {
		try {
			String filename = "snore.log";
			
			String readPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
			
			File fileOut = new File(readPath + filename);
			if (fileOut.exists()) {
				java.io.RandomAccessFile raf = new java.io.RandomAccessFile(
                                                                            fileOut, "rw");
				// Read a character
				char ch = raf.readChar();
				// Seek to end of file
				raf.seek(fileOut.length());
				// Append to the end
				raf.write("\n".getBytes());
				raf.write(content.getBytes());
				raf.close();
			} else {
				StringBuffer buf = new StringBuffer();
				buf.append("Logger \n");
				JCarxFileUtil.writeToFile(buf, filename, readPath);
				java.io.RandomAccessFile raf = new java.io.RandomAccessFile(
                                                                            fileOut, "rw");
				// Read a character
				char ch = raf.readChar();
				// Seek to end of file
				raf.seek(fileOut.length());
				// Append to the end
				raf.write("\n".getBytes());
				raf.write(content.getBytes());
				raf.close();
			}
		} catch (Exception x) {
			x.printStackTrace();
		}
	}
    
    @SuppressWarnings("deprecation")
	private final SensorListener sensorListener = new SensorListener() {
    
    double calibration = Double.NaN;
    
    public void onSensorChanged(int sensor, float[] values) { 
        double x = values[SensorManager.DATA_X];
        double y = values[SensorManager.DATA_Y];
        double z = values[SensorManager.DATA_Z];
    	
        //Log.d(TAG, "value was X="+ x + " Y="+ y + " Z="+ z);
        
        double a = -1*Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
        
        if(moved == 0){
            moved = a; 
            Log.d(TAG, "Setting moved for the first time to ="+ moved);
            Log.d(TAG, "Setting moved for the first time to ="+ moved);
        }else{
            double diffvalue = a;
            double startvalue = moved;
            double percentage = (diffvalue/startvalue) * 100.00;
            //Log.d(TAG, "percentage ="+percentage);
        	
            if((percentage > 150) || (percentage < 50)){
                try{
                    if(solothelistner != null){
                        //solothelistner.suspend();
                        //solothelistner.destroy();
                        //solothelistner.stop();
                        
                    	//runner = false;
                        
                        Log.e(TAG, "alersound ="+alertsoundtouseuserpref);
                        boolean securityon = alertsoundtouseuserpref.equalsIgnoreCase("NoSecurity");
                        if(securityon){
                            securityon = false;
                        }else{
                            securityon = true;
                        }
                        Log.e(TAG, " securityon ="+securityon);
                        
                        if(playedonce && securityon){
                            
                        	// first it vibrates
                        	if(vibrateuserpref.equals("true")){
                                vibrate();
                            }
                        	
                        	Log.e(TAG, "playalertsound =");
                            
                            if(smsnumbertouseuserpref.length() > 5){
                                sendSMS(smsnumbertouseuserpref,"SecureAlert");
                            }
                            if(phonenumbertouseuserpref.length() > 5){
                                call(phonenumbertouseuserpref);
                            }
                            
                            if(mMediaPlayer != null){
        						if(mMediaPlayer.isPlaying()){
        							try{
        								Thread.sleep(300);
        							}catch(Exception x2){
        								x2.printStackTrace();
        							}
        						}else{
        							playalertsound();			
            					}
        					}else{
        						playalertsound();			
        					}
                            
                            // sleep according to the sound length
                            /*Thread.sleep(2000);
                             
                             if(mMediaPlayer != null){
                             if(mMediaPlayer.isPlaying()){
                             try{
                             Thread.sleep(300);
                             }catch(Exception x2){
                             x2.printStackTrace();
                             }
                             }else{
                             playalertsound();			
                             }
                             }else{
                             playalertsound();			
                             }
                             
                             if(mMediaPlayer != null){
                             if(mMediaPlayer.isPlaying()){
                             try{
                             Thread.sleep(300);
                             }catch(Exception x2){
                             x2.printStackTrace();
                             }
                             }else{
                             if(mMediaPlayer != null){
                             mMediaPlayer.release();
                             mMediaPlayer = null;
                             }
                             }
                             }
                             */
            				
                            playedonce = false;
                            try{
                            	if(solothelistner.isAlive()){
                					Log.e(TAG, "solothelistner isAlive");
                				}
                				if(solothelistner.isDaemon()){
                					Log.e(TAG, "solothelistner isDaemon");
                				}
                				if(solothelistner.isInterrupted()){
                					Log.e(TAG, "solothelistner isInterrupted()");
                				}
                				
                				if(solothelistner != null){
                					Log.e(TAG, "solothelistner not null");
                    			}else{
                					Log.e(TAG, "solothelistner is null");
                    			}
                				// stop doing the sensor stuff
                				sensorManager.unregisterListener(this, sensor);
                            	
                				Thread.sleep(1000);
    						}catch(Exception x2){
    							x2.printStackTrace();
    						}
    						Intent intent = new Intent();
            				intent.setClass(SecureAlertActivity.this, SecureBreach.class);
            				startActivity(intent);
            			    //moved = a; 
                            moved = 0.0;
                        	//runner = true;
            				/*
                             if(solothelistner.isAlive()){
                             Log.e(TAG, "solothelistner isAlive");
                             }
                             if(solothelistner.isDaemon()){
                             Log.e(TAG, "solothelistner isDaemon");
                             }
                             if(solothelistner.isInterrupted()){
                             Log.e(TAG, "solothelistner isInterrupted()");
                             }
                             
                             if(solothelistner != null){
                             Log.e(TAG, "solothelistner not null");
                             }else{
                             Log.e(TAG, "solothelistner is null");
                             }
                             solothelistner.resume();
                             */
                            //solothelistner.resume();
                            
                            //finish();
                        }
                    }
                }catch(Exception x2){
                    x2.printStackTrace();
                    Log.e(TAG, "Exception in Security loop="+x2.getMessage());
                    
                }
                Log.d(TAG, "alertsoundtouseuserpref ="+alertsoundtouseuserpref);
                Log.d(TAG, "percentage Looked like you moved="+percentage);
            }else{
                try{
                    if(solothelistner != null){
                        //solothelistner.suspend();
                        //solothelistner.destroy();
                        //solothelistner.stop();
                        runner = true;
                    }
                }catch(Exception x2){
                    x2.printStackTrace();
                }
            }
            
        }
        
        
        //Log.d(TAG, "value was A="+ a);
        
        
        if (calibration == Double.NaN) 
            calibration = a;
        else {
            //updateVelocity(); 
            //currentAcceleration = (float)a;
        }
        //updateGUI();
    }
    public void onAccuracyChanged(int sensor, int accuracy) {} 
    
};   
}
SecureBreach.java
package com.jcarx.securealert;
/*
 * netsolvers.net (c) 2012
 *
 * @author Ravi Manthena
 */
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.Toast;

public class SecureBreach extends Activity{
	
	private static final String TAG = "SecureAlertActivityPro";
	private Button backB = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.securebreach);
        
		Log.e(TAG, "Security Breach Alert");
    	
		Toast.makeText(getApplicationContext(),
				"Security Breach Alert",
				Toast.LENGTH_LONG).show();
		
		backB = (Button) findViewById(R.id.securebackB);
		if(backB != null){
			Log.e(TAG, "Security Breach Alert backb was not null");
		}else{
			Log.e(TAG, "Security Breach Alert backb is null");
		}
		backB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
					Log.e(TAG, "Security Breach backb clicked");
					Intent intent = new Intent();
		    		intent.setClass( SecureBreach.this, SecureAlertActivity.class);
		    		startActivity(intent);
		    		finish();
		    	}catch(Exception x){
		    			Log.e(TAG, x.getMessage());
						x.printStackTrace();
		    	}
			}
       });
			
    }
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.