Browse Source

Updated Bluetooth and NFC Synchronization
- BluetoothSync is now an Activity that manages all bluetooth related
subjects.

Lars 10 years ago
parent
commit
aab9d4b4fa

+ 9 - 1
AndroidManifest.xml

@@ -57,9 +57,15 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:label="@string/gui_playground" >
         </activity>
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.sync.BluetoothSync" 
+            android:theme="@android:style/Theme.Dialog"
+            android:label="@string/gui_bluetooth">
+        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
-            android:label="@string/gui_playground" >
+            android:theme="@android:style/Theme.Dialog"
+            android:label="@string/gui_nfc" >
             <intent-filter>
                 <action android:name="android.nfc.action.NDEF_DISCOVERED" />
 
@@ -81,6 +87,8 @@
             android:authorities="de.tudarmstadt.informatik.hostage.provider"
             android:exported="false" >
         </provider>
+        
+
     </application>
 
 </manifest>

+ 18 - 0
res/layout/activity_bluetooth.xml

@@ -0,0 +1,18 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:orientation="vertical"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    android:id="@+id/bluetoothLayout" >
+
+    <TextView
+        android:id="@+id/bluetoothInfoText"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        />
+
+</LinearLayout>

+ 7 - 0
res/layout/list_view_bluetooth_devices.xml

@@ -0,0 +1,7 @@
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@android:id/text1"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:textAppearance="?android:attr/textAppearanceSmall"
+    android:gravity="center_vertical"
+/>

+ 3 - 0
res/values/strings_gui.xml

@@ -27,5 +27,8 @@
     <string name="gui_ssid">SSID:</string>
     <string name="gui_statistics">Statistics</string>
     <string name="gui_status">Status</string>
+    <string name="gui_choose_device">Choose Device</string>
+    <string name="gui_nfc">NFC</string>
+    <string name="gui_bluetooth">Bluetooth</string>
     
 </resources>

+ 368 - 292
src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java

@@ -1,292 +1,368 @@
-package de.tudarmstadt.informatik.hostage.sync;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.UUID;
-
-import android.app.AlertDialog;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothServerSocket;
-import android.bluetooth.BluetoothSocket;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.widget.ArrayAdapter;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-
-public class BluetoothSync {
-
-	private class ClientThread extends Thread {
-		private final BluetoothSocket socket;
-
-		public ClientThread(BluetoothDevice device) {
-			BluetoothSocket tmp = null;
-			try {
-				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
-			} catch (IOException e) {
-			}
-			socket = tmp;
-		}
-
-		/** Will cancel an in-progress connection, and close the socket */
-		public void cancel() {
-			try {
-				socket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-
-			try {
-				socket.connect();
-			} catch (IOException connectException) {
-				// Unable to connect; close the socket and get out
-				try {
-					socket.close();
-				} catch (IOException closeException) {
-				}
-				return;
-			}
-
-			manageConnectedSocket(socket, CLIENT);
-		}
-	}
-
-	private class CommunicationThread extends Thread {
-		private final BluetoothSocket mmSocket;
-		private final ObjectInputStream objectInput;
-		private final ObjectOutputStream objectOuput;
-		private final int identifier;
-
-		public CommunicationThread(BluetoothSocket socket, int identifier) {
-			mmSocket = socket;
-			ObjectInputStream tmpIn = null;
-			ObjectOutputStream tmpOut = null;
-
-			// Get the input and output streams, using temp objects because
-			// member streams are final
-			try {
-				tmpOut = new ObjectOutputStream(socket.getOutputStream());
-				tmpIn = new ObjectInputStream(socket.getInputStream());
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-
-			objectInput = tmpIn;
-			objectOuput = tmpOut;
-			this.identifier = identifier;
-		}
-
-		/* Call this from the main activity to shutdown the connection */
-		public void cancel() {
-			try {
-				mmSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			// Keep listening to the InputStream until an exception occurs
-			// while (true) {
-			try {
-				// TODO Ersetze dbh mit Logger
-				HostageDBOpenHelper dbh = new HostageDBOpenHelper(context);
-				ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
-				if (identifier == SERVER) {
-					// Read from the InputStream
-					ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput.readObject();
-					;
-					dbh.updateNetworkInformation(remoteNetworkInformation);
-					objectOuput.writeObject(localNetworkInformation);
-				} else {
-					objectOuput.writeObject(localNetworkInformation);
-					// Read from the InputStream
-					ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput.readObject();
-					dbh.updateNetworkInformation(remoteNetworkInformation);
-					mmSocket.close();
-				}
-			} catch (ClassNotFoundException e) {
-				e.printStackTrace();
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-			// }
-		}
-
-		/* Call this from the main activity to send data to the remote device */
-		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
-			try {
-				objectOuput.writeObject(networkInformation);
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
-	}
-
-	private class ServerThread extends Thread {
-		private final BluetoothServerSocket serverSocket;
-
-		public ServerThread() {
-			BluetoothServerSocket tmp = null;
-			try {
-				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(context.getResources().getString(R.string.app_name), serviceUUID);
-			} catch (IOException e) {
-			}
-			serverSocket = tmp;
-		}
-
-		/** Will cancel the listening socket, and cause the thread to finish */
-		public void cancel() {
-			try {
-				serverSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			BluetoothSocket socket = null;
-			while (true) {
-				try {
-					socket = serverSocket.accept();
-				} catch (IOException e) {
-					e.printStackTrace();
-					break;
-				}
-
-				if (socket != null) {
-					// Do work to manage the connection (in a separate thread)
-					manageConnectedSocket(socket, SERVER);
-					try {
-						serverSocket.close();
-					} catch (IOException e) {
-						e.printStackTrace();
-					}
-					break;
-				}
-			}
-		}
-	}
-
-	private final UUID serviceUUID;
-	private final int SERVER = 0;
-	private final int CLIENT = 1;
-
-	private BluetoothAdapter mBluetoothAdapter;
-	private Context context;
-
-	private ArrayAdapter<String> arrayAdapter;
-
-	private ServerThread serverThread;
-
-	private AlertDialog ad;
-
-	// Create a BroadcastReceiver for ACTION_FOUND
-	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			String action = intent.getAction();
-			// When discovery finds a device
-			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
-				// Get the BluetoothDevice object from the Intent
-				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
-				// Add the name and address to an array adapter to show in a
-				// ListView
-				arrayAdapter.add(device.getName() + "\n" + device.getAddress());
-				arrayAdapter.notifyDataSetChanged();
-			}
-		}
-	};
-
-	public BluetoothSync(Context context) {
-		this.context = context;
-		serviceUUID = UUID.fromString(context.getResources().getString(R.string.UUID));
-		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
-	}
-
-	public boolean syncData() {
-		if (!bluetoothAvaible())
-			return false;
-		syncDataPassive();
-		return syncDataActive();
-	}
-
-	private boolean bluetoothAvaible() {
-		if (mBluetoothAdapter == null) {
-			// Device does not support Bluetooth
-			return false;
-		}
-		if (!mBluetoothAdapter.isEnabled()) {
-			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
-			context.startActivity(enableBtIntent);
-			return false;
-		}
-		return true;
-	}
-
-	private void deviceDialog() {
-		AlertDialog.Builder builder = new AlertDialog.Builder(context);
-		// TODO in resources auslagern
-		builder.setTitle("Choose Device");
-		builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
-			@Override
-			public void onClick(DialogInterface dialog, int position) {
-				String deviceInfo = arrayAdapter.getItem(position);
-				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
-				ClientThread clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac));
-				clientThread.start();
-			}
-		});
-		// builder.create();
-		ad = builder.show();
-	}
-
-	private void manageConnectedSocket(BluetoothSocket socket, int identifier) {
-		if (identifier == SERVER) {
-			ad.dismiss();
-		}
-		mBluetoothAdapter.cancelDiscovery();
-		context.unregisterReceiver(mReceiver);
-		CommunicationThread commThread = new CommunicationThread(socket, identifier);
-		commThread.start();
-	}
-
-	// Register the BroadcastReceiver
-	private void registerBroadcastReceiver() {
-		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
-		context.registerReceiver(mReceiver, filter); // Don't forget to
-														// unregister during
-														// onDestroy
-	}
-
-	private boolean syncDataActive() {
-		registerBroadcastReceiver();
-		arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
-		// Start scanning for devices
-		if (!mBluetoothAdapter.startDiscovery())
-			return false;
-
-		deviceDialog();
-		return true;
-	}
-
-	private void syncDataPassive() {
-		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
-		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
-		context.startActivity(discoverableIntent);
-
-		serverThread = new ServerThread();
-		serverThread.start();
-	}
-
-}
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.UUID;
+
+import android.util.Log;
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothServerSocket;
+import android.bluetooth.BluetoothSocket;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.AdapterView.OnItemClickListener;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+public class BluetoothSync extends Activity{	
+	
+    private static final int CONNECTION_ESTABLISHED = 0x0;
+    private static final int CONNECTION_FAILED = 0x1;
+    private static final int MESSAGE_SENT = 0x2;
+    private static final int MESSAGE_RECIEVED = 0x3;
+    
+	private UUID serviceUUID;
+	
+	private BluetoothAdapter mBluetoothAdapter;
+	private ArrayAdapter<String> arrayAdapter;
+
+	private ServerThread serverThread;	
+	private ClientThread clientThread;
+	CommunicationThread commThread;
+	
+	TextView mInfoText;
+	ListView listView;
+	LinearLayout layout;
+	
+	
+	@Override
+	public void onCreate(Bundle savedInstanceState){
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_bluetooth);		
+		
+		serviceUUID = UUID.fromString(getResources().getString(R.string.UUID));
+		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();					
+		arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_view_bluetooth_devices);	
+		setLayoutElement();
+		registerBroadcastReceiver();
+				
+		if (mBluetoothAdapter == null) {
+			// Device does not support Bluetooth
+			mInfoText.setText("Bluetooth is not available on this device.");
+		}
+		else if (!mBluetoothAdapter.isEnabled()) {
+			mInfoText.setText("Enable Bluetooth before synchronizing.");
+			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+			startActivity(enableBtIntent);
+		} else {
+			startConnectionListener();
+			chooseDevice();
+		}
+	}
+		
+	
+	@Override
+	public void onDestroy(){
+		super.onDestroy();
+		if(mRecieverRegistered){
+			unregisterBroadcastReceiver();
+		}
+		if(commThread != null) {
+			commThread.cancel();
+		}
+		if(clientThread != null){
+			clientThread.cancel();
+		}
+		if(serverThread != null){
+			serverThread.cancel();
+		}
+	}
+	
+	private void chooseDevice(){
+		arrayAdapter.clear();
+		if (!mBluetoothAdapter.startDiscovery())
+			return;
+		mInfoText.setText("Choose Device for synchronizing:\n");
+		layout.addView(listView);
+		setContentView(layout);
+	}
+
+	private void startConnectionListener() {
+		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
+		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
+		startActivity(discoverableIntent);
+
+		serverThread = new ServerThread();
+		serverThread.start();
+	}
+		
+
+	private void manageConnectedSocket(BluetoothSocket socket) {
+		mBluetoothAdapter.cancelDiscovery();
+		unregisterBroadcastReceiver();
+		commThread = new CommunicationThread(socket);
+		commThread.start();
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		commThread.write(localNetworkInformation);
+	}
+
+	private class ClientThread extends Thread {
+		private final BluetoothSocket socket;
+
+		public ClientThread(BluetoothDevice device) {
+			BluetoothSocket tmp = null;
+			try {
+				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
+			} catch (IOException e) {
+			}
+			socket = tmp;
+		}
+
+		/** Will cancel an in-progress connection, and close the socket */
+		public void cancel() {
+			try {
+				socket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+
+			try {
+				socket.connect();
+			} catch (IOException connectException) {
+				mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
+				// Unable to connect; close the socket and get out
+				try {
+					socket.close();
+				} catch (IOException closeException) {
+				}
+				return;
+			}
+			mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
+			manageConnectedSocket(socket);
+		}
+	}
+
+	private class ServerThread extends Thread {
+		private final BluetoothServerSocket serverSocket;
+
+		public ServerThread() {
+			BluetoothServerSocket tmp = null;
+			try {
+				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getResources().getString(R.string.app_name), serviceUUID);
+			} catch (IOException e) {
+			}
+			serverSocket = tmp;
+		}
+
+		/** Will cancel the listening socket, and cause the thread to finish */
+		public void cancel() {
+			try {
+				serverSocket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+			BluetoothSocket socket = null;
+			while (true) {
+				try {
+					socket = serverSocket.accept();
+				} catch (IOException e) {
+					e.printStackTrace();
+					mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
+					break;
+				}
+
+				if (socket != null) {
+					// Do work to manage the connection (in a separate thread)
+					manageConnectedSocket(socket);
+					mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
+					try {
+						serverSocket.close();
+					} catch (IOException e) {
+						e.printStackTrace();
+					}
+					break;
+				}
+			}
+		}
+	}
+	
+	private class CommunicationThread extends Thread {
+		private final BluetoothSocket mmSocket;
+		private final ObjectInputStream objectInput;
+		private final ObjectOutputStream objectOuput;
+
+		public CommunicationThread(BluetoothSocket socket) {
+			mmSocket = socket;
+			ObjectInputStream tmpIn = null;
+			ObjectOutputStream tmpOut = null;
+
+			// Get the input and output streams, using temp objects because
+			// member streams are final
+			try {
+				tmpOut = new ObjectOutputStream(socket.getOutputStream());
+				tmpIn = new ObjectInputStream(socket.getInputStream());
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+
+			objectInput = tmpIn;
+			objectOuput = tmpOut;
+		}
+
+		/* Call this from the main activity to shutdown the connection */
+		public void cancel() {
+			try {
+				mmSocket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+			// Keep listening to the InputStream until an exception occurs
+			while (true) {
+			try {
+				// TODO Ersetze dbh mit Logger
+				HostageDBOpenHelper dbh = new HostageDBOpenHelper(getContext());
+				// Read from the InputStream
+				ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput.readObject();
+				// update database
+				dbh.updateNetworkInformation(remoteNetworkInformation);	
+				mHandler.obtainMessage(MESSAGE_RECIEVED).sendToTarget();
+			} catch (ClassNotFoundException e) {
+				e.printStackTrace();
+			} catch (IOException e) {
+				e.printStackTrace();
+				break;
+			}
+			}
+		}
+
+		/* Call this from the main activity to send data to the remote device */
+		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
+			try {
+				objectOuput.writeObject(networkInformation);
+				mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+
+	// Create a BroadcastReceiver for ACTION_FOUND
+	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+		@Override
+		public void onReceive(Context context, Intent intent) {
+			String action = intent.getAction();
+			// When discovery finds a device
+			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+				// Get the BluetoothDevice object from the Intent
+				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+				// Add the name and address to an array adapter to show in a ListView
+				arrayAdapter.add(device.getName() + "\n" + device.getAddress());
+				arrayAdapter.notifyDataSetChanged();
+			}else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
+				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
+				Log.i("BluetoothSync", state + "");
+				if(state == BluetoothAdapter.STATE_ON){
+					startConnectionListener();
+					chooseDevice();
+				}else if(state == BluetoothAdapter.STATE_OFF ||  state == BluetoothAdapter.STATE_TURNING_OFF){
+					mInfoText.setText("Enable Bluetooth before synchronizing.");
+					layout.removeView(listView);
+				}
+			}
+		}
+	};
+	
+	private boolean mRecieverRegistered = false;
+
+
+	// Register the BroadcastReceiver
+	private void registerBroadcastReceiver() {
+		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
+		filter.addAction(BluetoothAdapter. ACTION_STATE_CHANGED);
+		registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
+		mRecieverRegistered = true;
+	}
+	
+	private void unregisterBroadcastReceiver(){
+		unregisterReceiver(mReceiver);
+		mRecieverRegistered = false;
+	}
+	
+	private Context getContext(){
+		return this;
+	}
+	
+	private void setLayoutElement(){
+		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
+		layout = (LinearLayout) findViewById(R.id.bluetoothLayout);
+		listView = new ListView(this);
+		listView.setAdapter(arrayAdapter);
+		listView.setOnItemClickListener(new OnItemClickListener() {
+			@Override
+			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+				String deviceInfo = arrayAdapter.getItem(position);
+				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
+				clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac));
+				clientThread.start();
+			}
+		});		
+	}	
+	
+	private boolean message_sent = false;
+	private boolean message_recieved = false;
+	
+	private Handler mHandler = new Handler() {
+
+        @Override
+        public void handleMessage(Message msg) {
+        	switch(msg.what){
+        		case CONNECTION_ESTABLISHED: 
+        			layout.removeView(listView);
+        			BluetoothSocket socket = (BluetoothSocket) msg.obj;
+        			String deviceName = socket.getRemoteDevice().getName();
+        			mInfoText.setText("Synchronizing with " + deviceName + "...");	
+        			break;
+        		case CONNECTION_FAILED: 
+        			mInfoText.setText("Synchronization failed!");
+        			break;
+        		case MESSAGE_SENT: 
+        			message_sent = true;
+        			if(message_recieved)
+        				mInfoText.setText("Synchronization successfull!");
+        			break;	
+        		case MESSAGE_RECIEVED: 
+        			message_recieved = true;
+        			if(message_sent)
+        				mInfoText.setText("Synchronization successfull!");
+        			break;	
+        	}        		
+        }
+};
+}

+ 169 - 178
src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java

@@ -1,178 +1,169 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed 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.
- */
-
-package de.tudarmstadt.informatik.hostage.sync;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.annotation.TargetApi;
-import android.app.Activity;
-import android.content.Intent;
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import android.nfc.NfcAdapter;
-import android.nfc.NfcAdapter.CreateNdefMessageCallback;
-import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
-import android.nfc.NfcEvent;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Parcelable;
-import android.util.Log;
-import android.widget.TextView;
-import android.widget.Toast;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-
-@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
-public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
-	NfcAdapter mNfcAdapter;
-	TextView mInfoText;
-	private static final int MESSAGE_SENT = 1;
-
-	public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
-		ByteArrayInputStream in = new ByteArrayInputStream(data);
-		ObjectInputStream is = new ObjectInputStream(in);
-		return is.readObject();
-	}
-
-	public static byte[] serialize(Object obj) throws IOException {
-		ByteArrayOutputStream out = new ByteArrayOutputStream();
-		ObjectOutputStream os = new ObjectOutputStream(out);
-		os.writeObject(obj);
-		return out.toByteArray();
-	}
-
-	/** This handler receives a message from onNdefPushComplete */
-	private final Handler mHandler = new Handler() {
-		@Override
-		public void handleMessage(Message msg) {
-			switch (msg.what) {
-			case MESSAGE_SENT:
-				Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
-				Log.i("NFC", "Message sent!");
-				break;
-			}
-		}
-	};
-
-	/**
-	 * Implementation for the CreateNdefMessageCallback interface
-	 */
-	@Override
-	public NdefMessage createNdefMessage(NfcEvent event) {
-		// Get Networkdata
-		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
-		Log.i("NFC", "Creating Message");
-		NdefMessage msg = null;
-		try {
-			msg = new NdefMessage(NdefRecord.createMime("application/de.tudarmstadt.informatik.hostage", serialize(localNetworkInformation))
-			/**
-			 * The Android Application Record (AAR) is commented out. When a
-			 * device receives a push with an AAR in it, the application
-			 * specified in the AAR is guaranteed to run. The AAR overrides the
-			 * tag dispatch system. You can add it back in to guarantee that
-			 * this activity starts when receiving a beamed message. For now,
-			 * this code uses the tag dispatch system.
-			 */
-			// ,NdefRecord.createApplicationRecord("com.example.android.beam")
-			);
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		return msg;
-	}
-
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_nfc);
-
-		mInfoText = (TextView) findViewById(R.id.textView);
-		// Check for available NFC Adapter
-		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
-		if (mNfcAdapter == null) {
-			mInfoText = (TextView) findViewById(R.id.textView);
-			mInfoText.setText("NFC is not available on this device.");
-		} else {
-			// Register callback to set NDEF message
-			mNfcAdapter.setNdefPushMessageCallback(this, this);
-			// Register callback to listen for message-sent success
-			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
-		}
-	}
-
-	/**
-	 * Implementation for the OnNdefPushCompleteCallback interface
-	 */
-	@Override
-	public void onNdefPushComplete(NfcEvent arg0) {
-		// A handler is needed to send messages to the activity when this
-		// callback occurs, because it happens from a binder thread
-		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
-	}
-
-	@Override
-	public void onNewIntent(Intent intent) {
-		// onResume gets called after this to handle the intent
-		setIntent(intent);
-	}
-
-	// HELPER
-
-	@Override
-	public void onResume() {
-		super.onResume();
-		// Check to see that the Activity started due to an Android Beam
-		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
-			processIntent(getIntent());
-		}
-	}
-
-	/**
-	 * Parses the NDEF Message from the intent and prints to the TextView
-	 */
-	void processIntent(Intent intent) {
-		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
-		// only one message sent during the beam
-		NdefMessage msg = (NdefMessage) rawMsgs[0];
-		// record 0 contains the MIME type, record 1 is the AAR, if present
-		Object object;
-		Log.i("NFC", "Getting Message!");
-		try {
-			object = deserialize(msg.getRecords()[0].getPayload());
-			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
-			HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-			dbh.updateNetworkInformation(remoteNetworkInformation);
-		} catch (ClassNotFoundException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-	}
-
-}
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed 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.
+ */
+
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import android.annotation.TargetApi;
+import android.app.Activity;
+import android.content.Intent;
+import android.nfc.NdefMessage;
+import android.nfc.NdefRecord;
+import android.nfc.NfcAdapter;
+import android.nfc.NfcAdapter.CreateNdefMessageCallback;
+import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
+import android.nfc.NfcEvent;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Parcelable;
+import android.util.Log;
+import android.widget.TextView;
+import android.widget.Toast;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
+	NfcAdapter mNfcAdapter;
+	TextView mInfoText;
+	private static final int MESSAGE_SENT = 1;
+
+
+
+	/** This handler receives a message from onNdefPushComplete */
+	private final Handler mHandler = new Handler() {
+		@Override
+		public void handleMessage(Message msg) {
+			switch (msg.what) {
+			case MESSAGE_SENT:
+				Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
+				Log.i("NFC", "Message sent!");
+				break;
+			}
+		}
+	};
+
+	/**
+	 * Implementation for the CreateNdefMessageCallback interface
+	 */
+	@Override
+	public NdefMessage createNdefMessage(NfcEvent event) {
+		// Get Networkdata
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		Log.i("NFC", "Creating Message");
+		NdefMessage msg = null;
+		try {
+			msg = new NdefMessage(NdefRecord.createMime("application/de.tudarmstadt.informatik.hostage", serialize(localNetworkInformation))
+					
+			);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		return msg;
+	}
+
+	@Override
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_nfc);
+
+		mInfoText = (TextView) findViewById(R.id.textView);
+		// Check for available NFC Adapter
+		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+		if (mNfcAdapter == null) {
+			mInfoText.setText("NFC is not available on this device.");
+		} else {
+			mInfoText.setText("Hold phones together to synchronize.");
+			// Register callback to set NDEF message
+			mNfcAdapter.setNdefPushMessageCallback(this, this);
+			// Register callback to listen for message-sent success
+			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
+		}
+	}
+
+	/**
+	 * Implementation for the OnNdefPushCompleteCallback interface
+	 */
+	@Override
+	public void onNdefPushComplete(NfcEvent arg0) {
+		// A handler is needed to send messages to the activity when this
+		// callback occurs, because it happens from a binder thread
+		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
+	}
+
+	@Override
+	public void onNewIntent(Intent intent) {
+		// onResume gets called after this to handle the intent
+		setIntent(intent);
+	}
+
+	// HELPER
+
+	@Override
+	public void onResume() {
+		super.onResume();
+		// Check to see that the Activity started due to an Android Beam
+		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
+			processIntent(getIntent());
+		}
+	}
+
+	/**
+	 * Parses the NDEF Message from the intent and prints to the TextView
+	 */
+	void processIntent(Intent intent) {
+		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
+		// only one message sent during the beam
+		NdefMessage msg = (NdefMessage) rawMsgs[0];
+		// record 0 contains the MIME type, record 1 is the AAR, if present
+		Object object;
+		Log.i("NFC", "Getting Message!");
+		try {
+			object = deserialize(msg.getRecords()[0].getPayload());
+			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
+			HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+			dbh.updateNetworkInformation(remoteNetworkInformation);
+		} catch (ClassNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
+		ByteArrayInputStream in = new ByteArrayInputStream(data);
+		ObjectInputStream is = new ObjectInputStream(in);
+		return is.readObject();
+	}
+
+	private static byte[] serialize(Object obj) throws IOException {
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		ObjectOutputStream os = new ObjectOutputStream(out);
+		os.writeObject(obj);
+		return out.toByteArray();
+	}
+
+}

+ 95 - 97
src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java

@@ -1,98 +1,96 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Random;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.view.Menu;
-import android.view.View;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
-import de.tudarmstadt.informatik.hostage.sync.NFCSync;
-
-public class PlayGroundActivity extends Activity {
-
-	BluetoothSync bs;
-
-	public void createNetworkData(View view) {
-		Random rnd = new Random();
-		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
-		for (int i = 0; i < 25; i++) {
-			HashMap<String, Object> network = new HashMap<String, Object>();
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID, createRandomBSSID());
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID, new BigInteger(130, rnd).toString(32));
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE, rnd.nextDouble() * 360);
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE, rnd.nextDouble() * 360);
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY, rnd.nextFloat());
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, System.currentTimeMillis());
-			fakeNetInfo.add(network);
-		}
-
-		setNetworkInfoText();
-		new HostageDBOpenHelper(this).updateNetworkInformation(fakeNetInfo);
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
-
-	public void startNFC(View view) {
-		startActivity(new Intent(this, NFCSync.class));
-	}
-
-	public void syncData(View view) {
-		bs.syncData();
-	}
-
-	private String createRandomBSSID() {
-		Random rnd = new Random();
-		char[] symbols = new char[16];
-		for (int idx = 0; idx < 10; ++idx)
-			symbols[idx] = (char) ('0' + idx);
-		for (int idx = 10; idx < 16; ++idx)
-			symbols[idx] = (char) ('a' + idx - 10);
-
-		char[] buf = new char[17];
-		for (int i = 0; i < 18; i += 3) {
-			buf[i] = symbols[rnd.nextInt(symbols.length)];
-			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
-			if (i < 15) {
-				buf[i + 2] = ':';
-			}
-		}
-		return new String(buf);
-	}
-
-	private void setNetworkInfoText() {
-		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-		TextView bssids = (TextView) findViewById(R.id.textView1);
-		String text = "";
-		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
-		for (HashMap<String, Object> network : netInfo) {
-			text = text + (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID) + "\n"
-					+ (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP) + "\n\n";
-		}
-		bssids.setText(text);
-	}
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_playground);
-		bs = new BluetoothSync(this);
-		setNetworkInfoText();
-	}
+package de.tudarmstadt.informatik.hostage.ui;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Random;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.Menu;
+import android.view.View;
+import android.widget.TextView;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
+import de.tudarmstadt.informatik.hostage.sync.NFCSync;
+
+public class PlayGroundActivity extends Activity {
+
+
+	public void createNetworkData(View view) {
+		Random rnd = new Random();
+		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
+		for (int i = 0; i < 25; i++) {
+			HashMap<String, Object> network = new HashMap<String, Object>();
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID, createRandomBSSID());
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID, new BigInteger(130, rnd).toString(32));
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE, rnd.nextDouble() * 360);
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE, rnd.nextDouble() * 360);
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY, rnd.nextFloat());
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, System.currentTimeMillis());
+			fakeNetInfo.add(network);
+		}
+
+		setNetworkInfoText();
+		new HostageDBOpenHelper(this).updateNetworkInformation(fakeNetInfo);
+	}
+
+	@Override
+	public boolean onCreateOptionsMenu(Menu menu) {
+		getMenuInflater().inflate(R.menu.main, menu);
+		return true;
+	}
+
+	public void startNFC(View view) {
+		startActivity(new Intent(this, NFCSync.class));
+	}
+
+	public void syncData(View view) {
+		startActivity(new Intent(this, BluetoothSync.class));
+	}
+
+	private String createRandomBSSID() {
+		Random rnd = new Random();
+		char[] symbols = new char[16];
+		for (int idx = 0; idx < 10; ++idx)
+			symbols[idx] = (char) ('0' + idx);
+		for (int idx = 10; idx < 16; ++idx)
+			symbols[idx] = (char) ('a' + idx - 10);
+
+		char[] buf = new char[17];
+		for (int i = 0; i < 18; i += 3) {
+			buf[i] = symbols[rnd.nextInt(symbols.length)];
+			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
+			if (i < 15) {
+				buf[i + 2] = ':';
+			}
+		}
+		return new String(buf);
+	}
+
+	private void setNetworkInfoText() {
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		TextView bssids = (TextView) findViewById(R.id.textView1);
+		String text = "";
+		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
+		for (HashMap<String, Object> network : netInfo) {
+			text = text + (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID) + "\n"
+					+ (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP) + "\n\n";
+		}
+		bssids.setText(text);
+	}
+
+	@Override
+	protected void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_playground);
+		setNetworkInfoText();
+	}
 }