my code stock.com

Snippet options

Download: Download snippet as mainactivity.java.
Copy snippet: For this you need a free my code stock.com account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

package com.example.flash;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class MainActivity extends Activity {

	private EditText textField, ip_field;
	private Button admin_button,connect, on,off;
	private TextView recieve_text, text_ip, switch_stats;
	static BufferedReader inFromUser;
	static DataOutputStream outToServer ;
	static BufferedReader inFromServer;
	static Socket clientSocket = null;
	static boolean admin_granted=false;
	static String ourValue;
	
	static boolean isFlashlightOn=false;
	static  boolean runnable_running=false;
	static int i=0;
	String recieved_value;
	 String IPAdd="";
	 
	 private Camera camera;
		private  Camera.Parameters p;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		text_ip = (TextView)findViewById(R.id.text_ip);
		ip_field=(EditText)findViewById(R.id.ip_field);
		textField = (EditText) findViewById(R.id.string_field);
		admin_button = (Button) findViewById(R.id.admin_button); 
		connect = (Button)findViewById(R.id.connect);
		recieve_text = (TextView)findViewById(R.id.recieve_text);
		switch_stats = (TextView)findViewById(R.id.switch_stats);
		
		on = (Button)findViewById(R.id.on);
		off = (Button)findViewById(R.id.off);
		final GravitySensor sensor = new GravitySensor();
		final Runnable runnable;
		
		final int interval=50;   // INTERVAL switch off on
		
		
		//clientSocket= null;
		recieved_value="0";
		sensor.mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		   sensor.mSensorManager.registerListener(sensor.mSensorListener, sensor.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
		  //sensor.mAccel = 0.00f;
		  sensor.mAccelCurrent = SensorManager.GRAVITY_EARTH;
		 // sensor.mAccelLast = SensorManager.GRAVITY_EARTH;
		  
		  camera = Camera.open();
			
			
			
		  runnable = new Runnable() {
		      @Override
		      public void run() {
		        for ( i = 1; i <= 20; i++) {
		          
		         runnable_running=true;
		         
		      
		        
		         doWork(interval);
		         if(i>=20){  runnable_running=false; 
		         
		        
		         } }

		     
		        }
		      };
		  
		  
		      on.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					p.setFlashMode(Parameters.FLASH_MODE_TORCH);

					camera.setParameters(p);
					camera.startPreview();
				} });
		      
		      off.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						p.setFlashMode(Parameters.FLASH_MODE_OFF);
						camera.setParameters(p);
						camera.stopPreview();
					} });
		      
		connect.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					     .detectAll()
					     .penaltyLog()
					     .build();
					 StrictMode.setThreadPolicy(policy);
					 
				IPAdd = ip_field.getText().toString(); 

			
			
				try {
					
					//creating socket, streamers for read and write
					clientSocket = new Socket(IPAdd, 6789);
					inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));  
					inFromUser = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
					
					 
					String send_value= textField.getText().toString() + '\n';
					outToServer.writeBytes(send_value);
					
					
					Message messageTask = new Message();   //creating and executing the method that will recieve info from server
					messageTask.execute();
					
				} catch (UnknownHostException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}


			}
		});
	
		
admin_button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				admin_granted = true;
				Toast.makeText(getApplicationContext(), "Admin granted!",
						Toast.LENGTH_LONG).show();  
				
				// giving admin right (with admin rights you can decide if phones will start or not the activity of flashing light
				
				
				// new Thread(runnable).start();
			}	
		}); 
		

	
	
	
	 new CountDownTimer(120*1000,500)
	    {
		
			@Override
			public void onTick(long millisUntilFinished) {
				
				text_ip.setText(sensor.mAccelCurrent+"");
				//showing the proximity sensor value to user
				
				
				if(IPAdd.equals(""))
				{}else
				{
					try {
						clientSocket = new Socket(IPAdd, 6789);
						inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));  
						inFromUser = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
						outToServer = new DataOutputStream(clientSocket.getOutputStream()); 

					if(admin_granted)
					{
						// when phone is shaked we have values under 9 and over 11, when phone is in pause we have values around 9-11
						
						//down here we are writing values to server. "1" for shake, "0" for not shaked, 
						//and "2" if we dont have admin rights
						if(sensor.mAccelCurrent <9 || sensor.mAccelCurrent >= 11)
						{ 
							outToServer.writeBytes("1"+'\n');//1 
							
						}
						else
						{
							outToServer.writeBytes("0"+'\n');//1 //0
						}
					}else
					{
						outToServer.writeBytes("2"+'\n');//2
					}

						Message messageTask = new Message();
						messageTask.execute();
						
						
						
						
						
						
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					///
					if(recieved_value.equals("1") && runnable_running==false)
					{
						
						 new Thread(runnable).start();
					}
					
					///
				
				}
						
				
			}
				
			public void onFinish() {
				this.start();  
			}
	    }.start();
	} 
			

	
	private class Message extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			
			try {
				//recieving values from server
				recieved_value= inFromServer.readLine();
					runOnUiThread(new Runnable() {
					     @Override
					     public void run() {
					    	 recieve_text.setText(recieved_value); //
					    }
					});
					
					clientSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					final String error = e.toString();
					runOnUiThread(new Runnable() {
					     @Override
					     public void run() {
					    	 text_ip.setText(error); //
					    }
					});
				}    


			return null;
		}

	}

	
	
	private void doWork(int interval) {
		
		
	    try {
	    	Thread.sleep(interval);
	    	start_Activity();
	    }catch(final InterruptedException e)
	    {
	    	e.printStackTrace();
	    }
	    	 runOnUiThread(new Runnable() {

	    		    @Override
	    		    public void run() {
	    		    	
	    		            }
	    	 });
		
	  }
	
	public void start_Activity(){
		
		
if(camera==null){return;}


//wit this algorithm we switch to ON and OFF when   app is calling start_activity() method.
		if(isFlashlightOn==false)
		{
			
			isFlashlightOn = true;
			
			p = camera.getParameters();
			p.setFlashMode(Parameters.FLASH_MODE_TORCH);

			camera.setParameters(p);
			camera.startPreview();
			
	    
		}
		else
		{
			isFlashlightOn = false;
			p = camera.getParameters();
			p.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.setParameters(p);
			camera.stopPreview();
			force_stop();  // some phones experiencing problems and we have to force the flash to switch off.
		        
		}

	}
	
	private void force_stop(){
	
		p.setFlashMode(Parameters.FLASH_MODE_OFF);
		camera.setParameters(p);
		camera.stopPreview();
	}
	

}



 class GravitySensor  {
	
	SensorManager mSensorManager;
	  float mAccel; // acceleration apart from gravity
	  float mAccelCurrent; // current acceleration including gravity
	  float mAccelLast; // last acceleration including gravity

	  final SensorEventListener mSensorListener = new SensorEventListener() {

	    public void onSensorChanged(SensorEvent se) {
	      float x = se.values[0];
	      float y = se.values[1];
	      float z = se.values[2];
	      mAccelLast = mAccelCurrent;
	      mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
	      float delta = mAccelCurrent - mAccelLast;
	      mAccel = mAccel * 0.9f + delta; // perform low-cut filter
	    }

	    public void onAccuracyChanged(Sensor sensor, int accuracy) {
	    }
	  };


}

Create a free my code stock.com account now.

my code stok.com is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.