Below is main activity code where I got text from service throug broadcast and I'd like to forward this text to server using wifi.
I was thinking that I can just register this app as client and send text to another phone where server app is installed.
But I'm not sure how to do that.
It should be done automatically without pushing any buttons.
Any ideas???
This code is put together from different examples, so sorry if it looks very rough but at least it works;)
I separated lines I added for TCP client:
//for socket client start
//for socket client end
Thanks!
Code
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
public ResponseReceiver receiver;
public CountDownTimer countDownTimer;
//for socket client start
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.0.106";
//for socket client end
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "SINIHAMMAS OLEMAS", Toast.LENGTH_SHORT).show();
SystemClock.sleep(3000);
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
countDownTimer.cancel();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Toast.makeText(getApplicationContext(), "SINIHAMMAS LAHTI", Toast.LENGTH_SHORT).show();
countDownTimer.start();
}//else if...
}//onReceive
};//BroadcastReceiver
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startTime = 30000;
long interval = 1000;
countDownTimer = new MyCountDownTimer(startTime, interval);
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//for socket client start
new Thread(new ClientThread()).start();
//for socket client end
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
Log.d("sinihammas", "Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
unregisterReceiver(this);
}//if
}//onRecieve
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));//registerReciever
Log.d("sinihammas", "starting bluetooth");
am.startBluetoothSco();
SystemClock.sleep(2000);
Intent msgIntent = new Intent(MainActivity.this, SimpleIntentService.class);
startService(msgIntent);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
am.setBluetoothScoOn(false);
am.stopBluetoothSco();
System.exit(0);
}
});
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
}//onCreate
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "alar.alar.com.rahelividinakes2.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
TextView result = (TextView) findViewById(R.id.textView);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(Html.fromHtml(text + "<br>" + result.getText()));
**I THINK I SHOULD SEND TEXT HERE, BUT I DONT KNOW HOW**
}//onReceive
}//BroadcastReceiver
public class MyCountDownTimer extends CountDownTimer {
MediaPlayer mediaPlayer = MediaPlayer.create(alar.alar.com.rahelividinakes2.MainActivity.this, R.raw.haire);
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
mediaPlayer.start();
SystemClock.sleep(7000);
mediaPlayer.release();
}
#Override
public void onTick(long millisUntilFinished) {
}
}
//for socket client start
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//for socket client end
}//Activity
server code EDITED
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
First of all, SystemClock.sleep() in MainActivity.onCreate() is a really bad idea due to possible ANR.
Your question actually contains 2 subquestions:
How to send our data to the client thread?
Add a queue member to the activity class. We'll use it in our client thread.
//for socket client start
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.0.106";
private ConcurrentLinkedQueue<String> mSendQueue = new ConcurrentLinkedQueue<String>();
//for socket client end
And make ResponseReceiver to add data to a queue.
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "alar.alar.com.rahelividinakes2.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
TextView result = (TextView) findViewById(R.id.textView);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(Html.fromHtml(text + "<br>" + result.getText()));
MainActivity.this.mSendQueue.add(text);
}//onReceive
}//BroadcastReceiver
How to send our data via the socket?
Use a queue in ClientThread
class ClientThread implements Runnable {
private final ConcurrentLinkedQueue<String> mQueue;
public ClientThread(ConcurrentLinkedQueue<String> queue) {
mQueue = queue;
}
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
OutputStream stream = socket.getOutputStream();
while(true) {
String data = mQueue.poll();
if(data == null) {
//queue is empty, waiting...
SystemClock.sleep(100);
continue;
}
byte[] bytes = data.getBytes();
stream.write(bytes, 0, bytes.length);
stream.flush();
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
//free resources
}
}
}
//for socket client end
Related
In my application, it was possibly for me to establish a bluetooth connection and sending bytes with an own Service and send some bytes to the receiver.
Now I tried unsuccessfully to connect to my own server for sending a text and get an answer. For any reason, I get a NullPointerException for my Service if I try to call the sendMessage() Method..
Service:
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
public class ClientService extends Service {
private String LOG_TAG = null;
private final IBinder mBinder = new LocalBinder();
private final String url_string = "";
private int receivedUcCommand = 0;
#Override
public void onCreate() {
super.onCreate();
}
public void sendToServer(final String text){
new Thread(new Runnable() {
#Override
public void run() {
if(internetAvailable()){
try {
String textParam = "text1" + URLEncoder.encode(text,"UTF-8");
URL scriptUrl = new URL(url_string);
HttpURLConnection connection = (HttpURLConnection) scriptUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setFixedLengthStreamingMode(textParam.getBytes().length);
OutputStreamWriter contextWriter = new OutputStreamWriter(connection.getOutputStream());
contextWriter.write(textParam);
contextWriter.flush();
contextWriter.close();
InputStream answerInputStream = connection.getInputStream();
String answer = read(answerInputStream);
answerInputStream.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
private String read(InputStream is){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String currentLine;
try {
while((currentLine = br.readLine()) != null){
sb.append(currentLine+"\n");
}
}catch (IOException e){
e.printStackTrace();
}
return sb.toString().trim();
}
private boolean internetAvailable(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
#Override
public IBinder onBind(Intent intent) {
// Wont be called as service is not bound
Log.i(LOG_TAG, "In onBind");
return mBinder;
}
public class LocalBinder extends Binder {
ClientService getService() {
// Return this instance of LocalService so clients can call public methods
return ClientService.this;
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "In onTaskRemoved");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
}
In Activity I do this:
public class loggedInActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
public static final String mBroadcastStringAction = "com.truiton.broadcast.string";
public static final String mBroadcastIntegerAction = "com.truiton.broadcast.integer";
public static final String mBroadcastArrayListAction = "com.truiton.broadcast.arraylist";
private TextView mTextView;
private IntentFilter mIntentFilter;
BluetoothService bService;
ClientService cService;
boolean btBound = false;
boolean clientBound = false;
// private View startButton;
Button testButton;
EditText et;
static final int CAM_REQUEST = 1;
//Button reconnectButton;
TextView recText;
recText = (TextView) findViewById(R.id.receivedText);
//recText.setText("KEIN ALARM");
et = (EditText) findViewById(R.id.editText);
testButton = (Button) findViewById(R.id.testButton);
// This way I start and bind the service for Bluetooth, to my activity
Intent btIntent = new Intent(this, BluetoothService.class);
startService(btIntent);
bindService(btIntent, btServiceConnection, Context.BIND_AUTO_CREATE);
//And this way I unsuccessfully trying to bind and start the ClientService for ServerConnection
Intent clientIntent = new Intent(this, ClientService.class);
startService(clientIntent);
bindService(clientIntent, clientServiceConnection, Context.BIND_AUTO_CREATE);
testButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//ATTENTION: TRYING TO SENDING TO SERVER HERE, IT THROWS ME A NULLPOINTER
cService.sendToServer(et.getText().toString());
}
});
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection btServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
bService = binder.getService();
btBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
btBound = false;
}
};
//I think it has to be to do something with that code here, but
this is the only place, where cService is defined...
private ServiceConnection clientServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
ClientService.LocalBinder binder = (ClientService.LocalBinder) service;
cService = binder.getService();
clientBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
clientBound = false;
}
};
It was like I said a mistake, which only could produced by a newbie like me. I forget to sign in the tag in the AndroidManifest.xml
I have been trying to send data from arduino to an Android application via Bluetooth Module HC-05 and i couldn't get any readings from the arduino to be displayed in the application
The arduino code is :
void setup() {
Serial.begin(9600);
}
void loop()
{
char c;
if(Serial.available())
{
c = Serial.read();
Serial.print(c);
}
}
The Android code is:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// private final String DEVICE_NAME="MyBTBee";
private final String DEVICE_ADDRESS="30:14:12:18:01:38";
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device=iterator;
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
public void onClickStart(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
}
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes,"UTF-8");
handler.post(new Runnable() {
public void run()
{
textView.append(string);
}
});
}
}
catch (IOException ex)
{
stopThread = true;
}
}
}
});
thread.start();
}
public void onClickSend(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
public void onClickStop(View view) throws IOException {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("\nConnection Closed!\n");
}
public void onClickClear(View view) {
textView.setText("");
}
}
The first issue I see right now is in your Arduino code:
You're never sending the message over Bluetooth as you're using the same Serial for input and output. If you're using an Arduino Mega using Serial1 would fixe this (Using TX1 and RX1). If you're not using a Mega you should consider to use the SerialSoftware library which allows you to create a new custom Serial.
It would be nice to see your Arduino setup to see how you wired it up.
Hope that helps you, feel free to ask any question.
I am implementing a simple app that sends and receives data between two devices via bluetooth.
I am following the android developer's blog's bluetoothchat example, but my application seems unable to read from the inputstream of a socket.
Writing to the socket is fine. The app does not throw an error nor update the textview as it is supposed to. Any help would be appreciated. Thank you!
Main activity.java(where list of devices are shown and selected) - probably not the errored file:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
private final static int REQUEST_ENABLE_BT = 22;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "Bluetooth!";
ListView listView;
ArrayList<BluetoothDevice> deviceList;
ArrayAdapter<String> arrayAdapter;
ScanReciever reciever;
BluetoothAdapter bluetooth_adapter;
Button onButton;
Button scanButton;
Button alreadyButton;
AcceptThread acceptThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceList = new ArrayList<>();
//arrayAdapter = new ArrayAdapter<>(this, R.xml.table_item, android.R.id.text1, deviceList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.table_item);
// Set up Buttons
onButton = (Button) findViewById(R.id.onButton);
scanButton = (Button) findViewById(R.id.scanButton);
onButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
askAdapterOn();
}
});
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanForDevices();
}
});
// Set up listview
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
callButtons(deviceList.get(position));
}
});
// Bluetooth setup.
bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
// If device is incapable of using bluetooth:
if (bluetooth_adapter == null) {
onButton.setEnabled(false);
scanButton.setEnabled(false);
}
else if (!bluetooth_adapter.isEnabled()) { // If bluetooth is off:
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
else { // Bluetooth is on and ready:
onButton.setEnabled(false);
scanButton.setEnabled(true);
alreadyButton = (Button) findViewById(R.id.alreadyButton);
alreadyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Collect current devices into a set.
Set<BluetoothDevice> pairedDevices = bluetooth_adapter.getBondedDevices();
// Pass the index of the paired device
if (pairedDevices.size() > 0) {
callButtons(pairedDevices.iterator().next()); // First element in set.
} else {
System.out.println("No paired Device!");
}
}
});
acceptThread = new AcceptThread();
acceptThread.start();
}
}
private class ScanReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
System.out.println("Started");
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("finished");
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("FOUND: " + device.getName());
deviceList.add(device);
arrayAdapter.add(device.getName()+" - Click to pair");
arrayAdapter.notifyDataSetChanged();
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
System.out.println("Connected~!!!!!!!!!!!!!!");
callButtons(deviceList.get(deviceList.size()-1));
}
}
};
protected void askAdapterOn() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
protected void scanForDevices() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
reciever = new ScanReciever();
registerReceiver(reciever, filter);
bluetooth_adapter.startDiscovery();
}
protected void callButtons(BluetoothDevice bd) {
bluetooth_adapter.cancelDiscovery();
Intent toButton = new Intent(getApplicationContext(), buttons.class);
toButton.putExtra("selected",bd);
startActivity(toButton);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK){
if (bluetooth_adapter.isEnabled()){
onButton.setEnabled(false);
scanButton.setEnabled(true);
}
else {
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDestroy() {
unregisterReceiver(reciever);
super.onDestroy();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetooth_adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
System.out.println("READY TO ACCEPT");
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
Buttons.java(where the app will initiate a connection and maintain communication) - probably the file with the error:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class buttons extends Activity {
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
BluetoothDevice selected;
BluetoothAdapter bluetoothAdapter;
TextView tv;
Button button1;
Button button2;
Button button3;
Button unpairB;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
ConnectThread connectThread;
ConnectedThread connectedThread;
BluetoothSocket mmSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
selected = getIntent().getExtras().getParcelable("selected");
pair(selected);
connectedThread = null;
try {
connectedThread = new ConnectedThread(mmSocket);
connectedThread.start();
System.out.println("ConnectedThread started!");
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
// Set up Buttons
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
unpairB = (Button) findViewById(R.id.unpairButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(2);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(3);
}
});
unpairB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unpair(selected);
finish();
}
});
// Set up textview
tv = (TextView) findViewById(R.id.textView);
tv.setText("connected to: " + selected.getName());
}
protected void buttonPressed(int i) {
connectedThread.write(i);
tv.setText(Integer.toString(i));
}
private void pair(BluetoothDevice device) {
connectThread = new ConnectThread(device);
connectThread.start();
}
private void unpair(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
}
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("Socket was created in ConnectThread");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
// bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
System.out.println("Connected to " + socket.getRemoteDevice().getName());
try {
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
if (inputStream == null) System.out.println("Inputstream is null");
else System.out.println("Inputstream is safe");
if (outputStream == null) System.out.println("outstream is null");
else System.out.println("Outputstream is safe");
while (true) {
try {
System.out.println("Blocking?");
bytes = inputStream.read(buffer);
System.out.println("NO");
handler.obtainMessage(MESSAGE_READ, bytes, -1,
buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(int i) {
try {
byte[] buffer = new byte[1024];
buffer[0] = (byte) i;
outputStream.write(buffer);
outputStream.flush();
handler.obtainMessage(MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
System.out.println("Write SUCCESS!!!!!!!!!!!!!!");
} catch (IOException e) {
System.out.println("write ERRORRRRRRRRRRRRRRRRR");
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
}
}
}
private final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
System.out.println("Write was broadcasted");
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(Integer.toString(writeBuf[0]));
///tv.setText(writeMessage);
break;
case MESSAGE_READ:
System.out.println("Read was broadcasted");
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(Integer.toString(readBuf[0]));
tv.setText(readMessage);
break;
}
}
};
}
i'm trying to get the communication between activities and a service to work.
i am pretty new to android and java, learned it my self through youtube :D, but cant find or solve this one.
at first i made an activity with a class thread which handles an ethernet socket. but i discovered when i leave the activity and switch to another the thread is destroyed. to preserve the thread i included the thread inside an service. but now i cant use the functions inside the thread (like sending/getting status). how can i get the instance of my ethernet class back to all of my activities. below i clipped my code.
the code works and run. but when i want to call my send() function or getConStatus() it crashed.
working on a client server communication for home domotics.
// my main activity
import java.io.IOException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
//UI declerations
Button button1, button2;
EditText text1,text2;
ProgressBar waiter;
Ethernets eth;
house house;
Toast message;
ProgressTask Task;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
text1 = (EditText)findViewById(R.id.editText1);
text2 = (EditText)findViewById(R.id.editText2);
waiter = (ProgressBar)findViewById(R.id.Waiter);
}
protected void onStop()
{
Intent intent = new Intent(this, Ethernet_Service.class);
stopService(intent);
}
public void start(View view)
{
eth.send("Turn ON"); // i cant USE this !!
}
public void connect(View view) throws UnknownHostException, IOException
{
String ip = null;
int port = 0;
ip = text1.getText().toString();
port = Integer.parseInt(text2.getText().toString());
Intent intent = new Intent(this, Ethernet_Service.class);
startService(intent);
}
}
// my service
package com.example.homeapp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class Ethernet_Service extends Service{
public Ethernet_Service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Ethernets eth = new Ethernets("I9001", "192.168.1.101", 4000);
eth.start();
return startid;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
// my ethernet thread class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import android.util.Log;
public class Ethernets extends Thread {
Thread ethernetThread, recieveThread;
Socket ethernetSocket;
PrintStream PW;
String IP;
int PORT;
boolean connect_status = false;
String Client_Name;
public Ethernets(String name, String ip, int port)
{
Client_Name = name;
PORT = port;
IP = ip;
}
public void run()
{
try
{
ethernetSocket = new Socket(IP,PORT);
if(ethernetSocket.isConnected() == true)
{
connect_status = true;
}
else{connect_status = false;}
PW = new PrintStream(ethernetSocket.getOutputStream(),true);
}catch(Exception ex){}
recieveThread = new Thread(new Runnable() {
#Override
public void run() {
String message;
try
{
BufferedReader BR = new BufferedReader(new InputStreamReader(ethernetSocket.getInputStream()));
while((message = BR.readLine()) != null)
{
System.out.println("message: "+message);
}
} catch (IOException e) {e.printStackTrace();}
}
});
recieveThread.start();
}
public void send(String msg)
{
//protocol description
byte[] buffer = {(byte) 0x02, (byte) 0x04, (byte) 'B', (byte) 0x02, 0x00, 0x00, (byte) 0x46 };
try
{
Log.i("hi","hi");
PW.write(buffer);
PW.flush();
} catch (IOException e) {e.printStackTrace();}
}
public boolean getconStatus()
{
return connect_status;
}
}
I'm very new to Android Programming, It would be really great if someone can help me in this.My project contains two JAVA files.
MainActivity.java extends Activity
SMSReceiver.java extends Broadcastreceiver
The SMSreceiver.java has the code which displays any incoming SMS in toast. Can you please tell me how to call a function in MainActivity whenever a particular SMS is received. For eg: when I receive sms called as starttemp it should call a function starttemp.
I have searched a lot and found that intents are a way to do this and we cannot call these methods directly. Please can anyone help me in this? And it would be really great if someone can send me working code.
This would be my MainACtivity.Java
package com.wissen.sms;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ToggleButton;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" }) public class MainActivity extends Activity
{
TextView myLabel;
EditText myTextbox;
ToggleButton switch1;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
String status;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myTextbox = (EditText)findViewById(R.id.entry);
//switch1
switch1 = (ToggleButton) findViewById(R.id.switch1);
switch1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(switch1.isChecked()){
try
{
String msg = "01ON";
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
catch (IOException ex) { }
}else{
try
{
String msg = "01OF";
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
catch (IOException ex) { }
}
}
});
//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Send Button
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("HomeAutomation"))
{
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
status=data;
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData() throws IOException
{
String msg = myTextbox.getText().toString();
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}
This would be My SMSReceiver.Java
package com.wissen.sms.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
}
Now i want to call a method of MainActivity.java whenever a new message is received
void somemethod()
{
try
{
String msg = "01ON";
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
catch (IOException ex) { }
}
}
One best way for use MainActivity method from Broadcast receiver class is
Define your method as a static and than you can use that method using below code
Activityname.methodname()
I tried this and its worked fine for me.
for example
public class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction() == SMS_RECEIVED) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
abc.methodtocall();
}
}
}
}
and your Activity code like this
public class abc extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static void methodtocall(){
//Your code here...
}
}