Skip to content

Commit e1f41ce

Browse files
committed
Initial commit
0 parents  commit e1f41ce

File tree

18 files changed

+471
-0
lines changed

18 files changed

+471
-0
lines changed

app/.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/build

app/build.gradle

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
apply plugin: 'com.android.application'
2+
3+
android {
4+
compileSdkVersion 25
5+
buildToolsVersion "24.0.2"
6+
7+
defaultConfig {
8+
applicationId "com.meow.hanwei.epdandroidworkshop"
9+
minSdkVersion 21
10+
targetSdkVersion 25
11+
versionCode 1
12+
versionName "1.0"
13+
}
14+
buildTypes {
15+
release {
16+
minifyEnabled false
17+
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18+
}
19+
}
20+
}
21+
22+
dependencies {
23+
compile fileTree(dir: 'libs', include: ['*.jar'])
24+
testCompile 'junit:junit:4.12'
25+
compile 'com.android.support:appcompat-v7:25.0.1'
26+
}

app/proguard-rules.pro

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Add project specific ProGuard rules here.
2+
# By default, the flags in this file are appended to flags specified
3+
# in C:\Users\HanWei\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
4+
# You can edit the include path and order by changing the proguardFiles
5+
# directive in build.gradle.
6+
#
7+
# For more details, see
8+
# http://developer.android.com/guide/developing/tools/proguard.html
9+
10+
# Add any project specific keep options here:
11+
12+
# If your project uses WebView with JS, uncomment the following
13+
# and specify the fully qualified class name to the JavaScript interface
14+
# class:
15+
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16+
# public *;
17+
#}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.meow.hanwei.epdandroidworkshop;
2+
3+
import android.app.Application;
4+
import android.test.ApplicationTestCase;
5+
6+
/**
7+
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
8+
*/
9+
public class ApplicationTest extends ApplicationTestCase<Application> {
10+
public ApplicationTest() {
11+
super(Application.class);
12+
}
13+
}

app/src/main/AndroidManifest.xml

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3+
package="com.meow.hanwei.epdandroidworkshop">
4+
5+
<uses-permission android:name="android.permission.BLUETOOTH" />
6+
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
7+
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
8+
9+
<application
10+
android:allowBackup="true"
11+
android:icon="@mipmap/ic_launcher"
12+
android:label="@string/app_name"
13+
android:supportsRtl="true"
14+
android:theme="@style/AppTheme">
15+
<activity android:name=".MainActivity">
16+
<intent-filter>
17+
<action android:name="android.intent.action.MAIN" />
18+
19+
<category android:name="android.intent.category.LAUNCHER" />
20+
</intent-filter>
21+
</activity>
22+
</application>
23+
24+
</manifest>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
package com.meow.hanwei.epdandroidworkshop;
2+
3+
import android.bluetooth.BluetoothAdapter;
4+
import android.bluetooth.BluetoothDevice;
5+
import android.bluetooth.BluetoothSocket;
6+
import android.content.BroadcastReceiver;
7+
import android.content.Context;
8+
import android.content.Intent;
9+
import android.content.IntentFilter;
10+
import android.os.Handler;
11+
import android.os.Message;
12+
import android.os.ParcelUuid;
13+
import android.support.v7.app.AppCompatActivity;
14+
import android.os.Bundle;
15+
import android.util.Log;
16+
import android.view.View;
17+
import android.widget.AdapterView;
18+
import android.widget.ArrayAdapter;
19+
import android.widget.ListView;
20+
import android.widget.Toast;
21+
22+
import java.io.IOException;
23+
import java.io.InputStream;
24+
import java.io.OutputStream;
25+
import java.lang.reflect.Method;
26+
import java.util.ArrayList;
27+
import java.util.Set;
28+
import java.util.UUID;
29+
30+
public class MainActivity extends AppCompatActivity {
31+
32+
private static final String TAG = "MY_APP_DEBUG_TAG"; // just the Tag that error messages will
33+
// contain when written to from this app
34+
35+
private Handler mHandler = new Handler(); // handler that gets info from Bluetooth service
36+
37+
/**
38+
* Bluetooth adapter
39+
*/
40+
BluetoothAdapter mBluetoothAdapter;
41+
42+
/**
43+
* Bluetooth devices
44+
*/
45+
Set<BluetoothDevice> pairedDevices; // Set of devices that are paired to phone
46+
// (i.e. are bonded)
47+
48+
ArrayList<String> nameList = new ArrayList(); // namelist of paired/in-range devices for adapter
49+
50+
ArrayAdapter adapter; // adapter for listview
51+
ListView list; // to display names of devices
52+
53+
ArrayList<BluetoothDevice> devices = new ArrayList<>();
54+
private ConnectedThread connectedThread;
55+
56+
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
57+
@Override
58+
public void onReceive(Context context, Intent intent) {
59+
String action = intent.getAction();
60+
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
61+
// Discovery has found a device. Get the BluetoothDevice
62+
// object and its info from the Intent.
63+
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
64+
String deviceName = device.getName();
65+
if (!nameList.contains(deviceName)) {
66+
devices.add(device);
67+
nameList.add(deviceName);
68+
adapter.notifyDataSetChanged();
69+
}
70+
// String deviceHardwareAddress = device.getAddress(); // MAC address
71+
}
72+
}
73+
};
74+
75+
@Override
76+
protected void onDestroy() {
77+
super.onDestroy();
78+
// Don't forget to unregister the ACTION_FOUND receiver.
79+
unregisterReceiver(mReceiver);
80+
}
81+
82+
@Override
83+
protected void onCreate(Bundle savedInstanceState) {
84+
super.onCreate(savedInstanceState);
85+
setContentView(R.layout.activity_main);
86+
87+
// Register for broadcasts when a device is discovered.
88+
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
89+
registerReceiver(mReceiver, filter);
90+
91+
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, nameList);
92+
list = (ListView) findViewById(R.id.devices);
93+
list.setAdapter(adapter);
94+
95+
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
96+
@Override
97+
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
98+
if (mBluetoothAdapter.isEnabled()) {
99+
String devName = (String) list.getItemAtPosition(i);
100+
for (BluetoothDevice bt :
101+
devices) {
102+
if (bt.getName().equals(devName)) {
103+
connectedThread = new ConnectedThread(bt);
104+
String meow = "1";
105+
connectedThread.write(meow.getBytes());
106+
Toast.makeText(MainActivity.this, "MADE CONNECTION", Toast.LENGTH_LONG).show();
107+
}
108+
}
109+
} else {
110+
Toast.makeText(MainActivity.this, "Bluetooth is not on", Toast.LENGTH_SHORT).show();
111+
}
112+
}
113+
});
114+
115+
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
116+
117+
try {
118+
Method getUuidsMethod = BluetoothAdapter.class.getDeclaredMethod("getUuids", null);
119+
120+
ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(mBluetoothAdapter, null);
121+
for (ParcelUuid uuid : uuids) {
122+
Log.d(TAG, "UUID: " + uuid.getUuid().toString());
123+
}
124+
} catch (Exception e) {
125+
e.printStackTrace();
126+
}
127+
}
128+
129+
protected void toggleBT(View view) {
130+
if (mBluetoothAdapter != null) {
131+
if (!mBluetoothAdapter.isEnabled()) {
132+
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
133+
startActivityForResult(enableIntent, 0);
134+
Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
135+
} else {
136+
mBluetoothAdapter.disable();
137+
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG).show();
138+
}
139+
} else {
140+
Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_LONG).show();
141+
}
142+
}
143+
144+
protected void getPaired(View view) {
145+
if (mBluetoothAdapter.isEnabled()) {
146+
pairedDevices = mBluetoothAdapter.getBondedDevices();
147+
nameList.clear();
148+
devices.clear();
149+
for (BluetoothDevice bt : pairedDevices) {
150+
if (!nameList.contains(bt.getName())) {
151+
nameList.add(bt.getName());
152+
adapter.notifyDataSetChanged();
153+
devices.add(bt);
154+
System.out.println(bt.getName() + ": ");
155+
for (ParcelUuid meow :
156+
bt.getUuids()) {
157+
System.out.println(meow.getUuid());
158+
}
159+
}
160+
}
161+
Toast.makeText(getApplicationContext(), "Showing Paired Devices", Toast.LENGTH_SHORT).show();
162+
} else {
163+
Toast.makeText(MainActivity.this, "Bluetooth is not on", Toast.LENGTH_SHORT).show();
164+
}
165+
}
166+
167+
protected void discover(View view) {
168+
if (mBluetoothAdapter.isDiscovering()) {
169+
boolean discovering = mBluetoothAdapter.cancelDiscovery();
170+
if (discovering) {
171+
Toast.makeText(MainActivity.this, "Stopping discovery", Toast.LENGTH_LONG).show();
172+
} else {
173+
Toast.makeText(MainActivity.this, "Could not start discovery", Toast.LENGTH_LONG).show();
174+
}
175+
} else {
176+
mBluetoothAdapter.startDiscovery();
177+
Toast.makeText(MainActivity.this, "Started discovering", Toast.LENGTH_LONG).show();
178+
}
179+
}
180+
181+
182+
private interface MessageConstants {
183+
int MESSAGE_READ = 0;
184+
int MESSAGE_WRITE = 1;
185+
int MESSAGE_TOAST = 2;
186+
// ... (Add other message types here as needed.)
187+
}
188+
189+
190+
private class ConnectedThread extends Thread {
191+
private final BluetoothSocket mmSocket;
192+
private final BluetoothDevice mmDevice;
193+
private final InputStream mmInStream;
194+
private final OutputStream mmOutStream;
195+
private byte[] mmBuffer; // mmBuffer store for the stream
196+
197+
protected ConnectedThread(BluetoothDevice device) {
198+
// Use a temporary object that is later assigned to mmSocket
199+
// because mmSocket is final.
200+
BluetoothSocket tmp = null;
201+
mmDevice = device;
202+
203+
try {
204+
// Get a BluetoothSocket to connect with the given BluetoothDevice.
205+
// MY_UUID is the app's UUID string.
206+
207+
// tmp = device.createRfcommSocketToServiceRecord(mmDevice.getUuids()[0].getUuid());
208+
// This gets the first item from the array returned by getUuids().
209+
210+
// 00001101 represents the COM/Serial port for bluetooth.
211+
tmp = mmDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
212+
tmp.connect();
213+
} catch (IOException e) {
214+
Log.e(TAG, "Socket's create() method failed", e);
215+
}
216+
mmSocket = tmp;
217+
InputStream tmpIn = null;
218+
OutputStream tmpOut = null;
219+
220+
// Get the input and output streams; using temp objects because
221+
// member streams are final.
222+
try {
223+
tmpIn = mmSocket.getInputStream();
224+
} catch (IOException e) {
225+
Log.e(TAG, "Error occurred when creating input stream", e);
226+
}
227+
try {
228+
tmpOut = mmSocket.getOutputStream();
229+
} catch (IOException e) {
230+
Log.e(TAG, "Error occurred when creating output stream", e);
231+
}
232+
233+
mmInStream = tmpIn;
234+
mmOutStream = tmpOut;
235+
}
236+
237+
public void run() {
238+
mmBuffer = new byte[1024];
239+
int numBytes; // bytes returned from read()
240+
241+
// Keep listening to the InputStream until an exception occurs.
242+
while (true) {
243+
try {
244+
// Read from the InputStream.
245+
numBytes = mmInStream.read(mmBuffer);
246+
// Send the obtained bytes to the UI activity.
247+
Message readMsg = mHandler.obtainMessage(
248+
MessageConstants.MESSAGE_READ, numBytes, -1,
249+
mmBuffer);
250+
readMsg.sendToTarget();
251+
} catch (IOException e) {
252+
Log.d(TAG, "Input stream was disconnected", e);
253+
break;
254+
}
255+
}
256+
}
257+
258+
// Call this from the main activity to send data to the remote device.
259+
protected void write(byte[] msgbytes) {
260+
try {
261+
mmOutStream.write(msgbytes); // This is the only call that's actually sending
262+
// data to the connected bluetooth device
263+
264+
// Share the sent message with the UI activity.
265+
Message writtenMsg = mHandler.obtainMessage(
266+
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
267+
writtenMsg.sendToTarget();
268+
} catch (IOException e) {
269+
Log.e(TAG, "Error occurred when sending data", e);
270+
271+
// Send a failure message back to the activity.
272+
Message writeErrorMsg =
273+
mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
274+
Bundle bundle = new Bundle();
275+
bundle.putString("toast",
276+
"Couldn't send data to the other device");
277+
writeErrorMsg.setData(bundle);
278+
mHandler.sendMessage(writeErrorMsg);
279+
}
280+
}
281+
282+
// Call this method from the main activity to shut down the connection.
283+
protected void cancel() {
284+
try {
285+
mmSocket.close();
286+
} catch (IOException e) {
287+
Log.e(TAG, "Could not close the connect socket", e);
288+
}
289+
}
290+
}
291+
}

0 commit comments

Comments
 (0)