Bluetooth not writing or taking forever to read - java

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
#TargetApi(18)
public class MainActivity extends AppCompatActivity{
`int b = 0;
BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
BluetoothSocket BS;
BluetoothServerSocket server;
UUID uuid = UUID.fromString("f63b93f5-56e0-47bb-8972-996e34cfb9a8");`
`#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);`
`Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);`
`Accept accept = new Accept();
accept.start();`
Set<BluetoothDevice> devices = BA.getBondedDevices();
for(BluetoothDevice bt : devices) {
try {
if (bt.getName().equals("Overlord")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
} else if (bt.getName().equals("Huawei Y5")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
}
}catch(IOException IOE){}
}
}
public interface MessageContents{
int MSG_MESSAGE = 0;
}
Handler handler = new Handler(){
public void handleMessage(Message msg) {
TextView tx = (TextView)findViewById(R.id.textView2);
switch(msg.what){
case MessageContents.MSG_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d("TAG", readMessage);
tx.setText(readMessage);
break;
default:
tx.setText("No text");
}
}
};
class Connect extends Thread{
public void run(){
try {
try {
BS.connect();
Log.d("LOG", " e");
Log.d("LOG", "r" + BS.isConnected());
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.start();
}catch(NullPointerException e){
Log.d("LOG", " meezaan");
}
}catch(IOException e){
Log.d("LOG", "t");
}
}
}
class Accept extends Thread{
public void run() {
try {
while (true) {
server = BA.listenUsingRfcommWithServiceRecord("Secure Connection", uuid);
server.accept();
Log.d("LOG", "accept");
}
}catch(IOException E) {
}
}
}
class DataTransfer extends Thread{
#Override
public void run() {
int d = 1;
InputStream receive = null;
Log.d("LOG", "On");
int numBytes;
byte[] buffer = new byte[1024];
try {
receive = BS.getInputStream();
Log.d("LOG", "pn");
while (BS.isConnected()) {
try {
if (d <= 5) {
Log.d("LOG", "did");
++d;
}
numBytes = receive.read(buffer);
handler.obtainMessage(MessageContents.MSG_MESSAGE, numBytes, -1, buffer).sendToTarget();
} catch (NullPointerException e) {
Log.d("LOG", "error read(null)");
}
}
Log.d("LOG", "pnA");
} catch (IOException IOE) {
Log.d("LOG", "error read(IOE)");
}
}
}
public void onOne(View view){
write("1".getBytes());
}
public void onClick(View view){
Button b1 = (Button) findViewById(R.id.button);
EditText pin = (EditText) findViewById(R.id.editText);
pin.setRawInputType(Configuration.KEYBOARD_QWERTY);
pin.setVisibility(View.VISIBLE);
b1.setVisibility(View.VISIBLE);
}
public void pin (View view) {
Button b1 = (Button)findViewById(R.id.button);
EditText pin = (EditText)findViewById(R.id.editText);
String pin1 = pin.getText().toString();
if (pin1.equals("")) {
Connect connect = new Connect();
connect.run();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(getApplicationContext(), "Wrong Pin!"+pin1, Toast.LENGTH_SHORT).show();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
}
}
public void onTwo(View v){
Toast.makeText(getApplicationContext(), "" + handler.hasMessages(MessageContents.MSG_MESSAGE) + " " + BS.isConnected(), Toast.LENGTH_SHORT).show();
}
public void write(byte[] Byte){
try {
OutputStream transfer = BS.getOutputStream();
try {
transfer.write(Byte);
}catch(NullPointerException e){
Log.d("LOG", "error write(null) " + BS.isConnected());}
}catch (IOException IOE){ Log.d("LOG", "b");
Log.d("LOG", "error write(IOE) " + BS.isConnected());}
}
}`
Hi, this is my code. After writing Bytes[] I don't receive anything on second device. When I remove 'numBytes = receive.read(buffer)' handler would work or display
'no text'
I think receive.read(buffer) waits for an input which means write is a problem or receive.read(buffer) is the problem. Please ignore names, logs with random letters in or device names or unnecessary imports or variables. Thank You :) Sorry I did not have time to indent everything. If you are viewing please put something like don't know.Thank you.

Related

Socket Server controller Android App, Socket error

So basically I want to create some kind of controller for my pc, where on pc, runs java socket server. The server is working, I have tried it. Also, Port Forwarding in the router is allright. Source code is here :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_BOLD = "\033[1m";
public static final String ANSI_RED = "\u001B[31m";
public static void main(String[] args) throws IOException {
// Creating server instance
ServerSocket serverSocket = new ServerSocket(2000);
Socket socket = serverSocket.accept();
System.out.println(ANSI_GREEN + "Controller connected" + ANSI_RESET);
// Input Output streams
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String command = "";
do {
command = dataInputStream.readUTF();
switch (command.trim()){
case "volume up":
Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\volup.bat");
break;
case "volume down":
Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\voldown.bat");
break;
default:
// Unknown command
break;
}
}while (!command.equals("stop"));
socket.close();
System.out.println(ANSI_RED + "Controller disconnected" + ANSI_RESET);
}
}
And it is supposed to interact with the android app, but I got an error and I can't quite figure out why is that so, here is the source code for ActivityMain :
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private boolean connected;
private DataOutputStream dataOutputStream;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pripájanie na server
try {
socket = new Socket("172.0.0.1",2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Not Connected!",
Toast.LENGTH_LONG).show();
}
Button VolumeUp = (Button) findViewById(R.id.VolumeUpButton);
VolumeUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("volume up");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button VolumeDown = (Button) findViewById(R.id.VolumeDownButton);
VolumeDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("volume down");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button DisconnectButton = (Button) findViewById(R.id.DisconnectButton);
DisconnectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("stop");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void send(String command) throws IOException {
if (socket != null){
dataOutputStream.writeUTF(command);
}
else Toast.makeText(MainActivity.this, "Socket is not defined",
Toast.LENGTH_SHORT).show();
}
public void disconnect() throws IOException {
if (socket != null){
socket.close();
}
else Toast.makeText(MainActivity.this, "Socket is not defined",
Toast.LENGTH_SHORT).show();
}
}
So if you could help me with it, I would be thankful, <3
Well the reason for that was silly. When I'm loading data from Stream it says nextLine which means the ending point is \n so I could never get that line because I haven't put it there.

How to reestablish a Bluetooth connection after I leave an activity in Android Studio?

I am working on a project that can send and receive Strings to and from an Arduino to control and monitor various sensors and lights. I am running into an issue where once I leave the activity that connects to Bluetooth and then return to that same activity after visiting the home activity I am no longer able to send and receive data. The sending and receiving of strings works perfectly until I leave the activity to go to the home activity and come back.
Here is the Java code for the sensor activity:
package com.example.arduinocontrol;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class uvlight extends AppCompatActivity implements OnClickListener{
private static final int REQUEST_ENABLE_BT = 1;
private CardView uvLight;
//listeners for button presses
Button on, off,clear;
//textbox below buttons
TextView t1,t2,t3;
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mDevice;
ByteArrayInputStream mSocket;
ConnectedThread mConnectedThread = null;
ConnectThread mConnectThread = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
//Instantiation
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uvlight);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"BT not supported!", Toast.LENGTH_SHORT).show();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
//opens a window to ask user to turn on bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
try {
setw();
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("ClickableViewAccessibility")
private void setw() throws IOException {
//text for bluetooth device details
t1=(TextView)findViewById(R.id.textView3);
t2=(TextView)findViewById(R.id.response);
t2.setMovementMethod(new ScrollingMovementMethod());
String name = mDevice.getName().toString();
try {
t1.setText("Connected to: " + name);
} catch (Exception e) {
e.printStackTrace();
}
//links on and off to their element IDs
on=(Button)findViewById(R.id.uvlighton);
off=(Button)findViewById(R.id.uvlightoff);
clear=(Button)findViewById(R.id.clear);
//clears log text
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t2.setText("");
}
});
on.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//sends 'o' char to Arduino
// method to turn on uv light
if(mConnectedThread != null) {
//String sig = "o";
//mConnectedThread.write(sig.getBytes());
int sig = 112;
mConnectedThread.write(sig);
}
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//method to turn off uv light
if(mConnectedThread != null) {
//String sig1 = "f";
//mConnectedThread.write(sig1.getBytes());
int sig = 113;
mConnectedThread.write(sig);
}
}
});
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
//HC-05 unique uuid
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
try {
//creates RFCOMM socket
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
//shows user they are connected
Toast.makeText(getApplicationContext(), "Connected to your Arduino", Toast.LENGTH_SHORT).show();
//displays bt info in text field
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to connect!", Toast.LENGTH_SHORT).show();
}
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
//need the if for this edge case
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
if (mSocket != null) {
mSocket.close();
}
} catch (IOException closeException) {
Toast.makeText(getApplicationContext(), "Unable to connect socket!", Toast.LENGTH_SHORT).show();
}
return;
}
//new connected thread obj
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Thread for bluetooth process
private class ConnectedThread extends Thread {
//copies bt socket for threading
private final BluetoothSocket mmSocket;
//copies input stream obj for threading
private final InputStream mmInStream;
//copies output stream obj for threading
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
//reads from Arduino
#Override
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for (int i = begin; i < bytes; i++) {
//end char for a given message from Arduino
if (buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if (i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
//writes to the output stream (in this case the Arduino)
public void write(/*byte[] bytes*/int num) {
try {
Toast.makeText(getApplicationContext(), "sending bytes", Toast.LENGTH_SHORT).show();
mmOutStream.write(num);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v)
{
try
{
}
catch (Exception e)
{
//displays toast message
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//Suppresses an annoying handler lear warning
#SuppressLint("HandlerLeak")
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
//sends message to homepage to turn cardview red
//string called error contains value of writeMessage
Intent intent = new Intent("errorCode").putExtra("error", writeMessage);
LocalBroadcastManager.getInstance(uvlight.this).sendBroadcast(intent);
//write message to the scrolling textbox
t2.append(writeMessage);
break;
}
}
};
}
Here is the Java code for the home activity:
package com.example.arduinocontrol;
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.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
private CardView airPump, flowMeter, humiditySensor, levelSwitch1, levelSwitch2, lightStrip, phMeter, uvLight, waterPump, solenoidValve, nutrientPump;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//defines cards
airPump = (CardView) findViewById(R.id.airpump);
flowMeter = (CardView) findViewById(R.id.flowmeter);
humiditySensor = (CardView) findViewById(R.id.humiditysensor);
levelSwitch1 = (CardView) findViewById(R.id.levelswitch1);
levelSwitch2 = (CardView) findViewById(R.id.levelswitch2);
lightStrip = (CardView) findViewById(R.id.lightstrip);
phMeter = (CardView) findViewById(R.id.phmeter);
uvLight = (CardView) findViewById(R.id.uvlight);
waterPump = (CardView) findViewById(R.id.waterpump);
solenoidValve = (CardView) findViewById(R.id.solenoidvalve);
nutrientPump = (CardView) findViewById(R.id.nutrientpump);
//click listeners
airPump.setOnClickListener(this);
flowMeter.setOnClickListener(this);
humiditySensor.setOnClickListener(this);
levelSwitch1.setOnClickListener(this);
levelSwitch2.setOnClickListener(this);
lightStrip.setOnClickListener(this);
phMeter.setOnClickListener(this);
uvLight.setOnClickListener(this);
waterPump.setOnClickListener(this);
solenoidValve.setOnClickListener(this);
nutrientPump.setOnClickListener(this);
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("errorCode"));
}
//turns Uvlight card red when an error is sent
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String errorMsg = intent.getStringExtra("error");
if (errorMsg.equals("-3")){
uvLight.setCardBackgroundColor(0xFFFF0000);
}
}
};
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
#Override
public void onClick(View v) {
Intent i;
//on click opens the new activity
switch(v.getId()){
case R.id.airpump : i = new Intent(this,Airpump.class); startActivity(i); break;
case R.id.flowmeter : i = new Intent(this,Flowmeter.class); startActivity(i); break;
case R.id.humiditysensor : i =new Intent(this,Humiditysensor.class); startActivity(i); break;
case R.id.levelswitch1 : i = new Intent(this,Levelswitch1.class); startActivity(i); break;
case R.id.levelswitch2 : i = new Intent(this,Levelswitch2.class); startActivity(i); break;
case R.id.lightstrip : i = new Intent(this,Lightstrip.class); startActivity(i); break;
case R.id.phmeter : i = new Intent(this,Phmeter.class); startActivity(i); break;
case R.id.uvlight : i = new Intent(this,uvlight.class); startActivity(i); break;
case R.id.waterpump : i = new Intent(this,Waterpump.class); startActivity(i); break;
case R.id.solenoidvalve : i = new Intent(this,solenoidvalve.class); startActivity(i); break;
case R.id.nutrientpump : i = new Intent(this,Nutrientpump.class); startActivity(i); break;
default:break;
}
}
}
I am new to Android Studio and this is the first time I have had to make a multi-threaded application. Thank You.
you can try to extract the Bluetooth connection method into a simple profit class, similar to "local broadcast manager". When "uvlight" on destroy Bluetooth connection will continue to open. Or you can refer to GitHub's excellent open source libraries, such as: https://github.com/akexorcist/BluetoothSPPLibrary 。 I believe you can learn more in it

Connect MainActivity to a python server (Android Studio)

I'm trying to develop my first app in Android Studio and connect it to a server in python. I wrote a Client class and MainActivity with java in Android Studio and I wrote the Server in Pycharm. When I create a client object in different class, the connection between the client and the server works fine. However, when i do the same thing in the MainActivity it doesnt work and i get this error:
" E/m.example.mage: Unknown bits set in runtime_flags: 0x8000 ".
Do i need to do something else or is there a way to fix it?
package com.example.magen;
import android.widget.TextView;
import java.util.*;
import java.net.*;
import java.io.*;
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("connected to server");
}
catch(Exception e){
System.out.println("error 1 " + e.getMessage());
}
}
public String sendMessage(String msg) {
String resp="";
try {
out.println(msg);
System.out.println("client: "+msg);
resp = in.readLine();
}
catch(Exception e){
System.out.println("error 2 " + e.getMessage());
}
return resp;
}
public void stopConnection() {
try {
in.close();
out.close();
clientSocket.close();
}
catch(Exception e){
System.out.println("error 3 " + e.getMessage());
}
}
}
import socket
import select
import datetime
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 6969))
server_socket.listen(10)
open_client_sockets = []
def main():
while True:
rlist, wlist, xlist = select.select([server_socket]+open_client_sockets, open_client_sockets, [])
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
open_client_sockets.append(new_socket)
else:
full_msg = current_socket.recv(1024).decode()
print(full_msg)
current_socket.send("hi".encode())
...
...
...
...
...
if __name__ == '__main__':
main()
package com.example.magen;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText username;
private EditText password;
private Button loginButton;
private Button registerButton;
private TextView tvInfo;
private Client client = new Client();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.etUsername);
password = (EditText)findViewById(R.id.etPassword);
loginButton = (Button)findViewById(R.id.loginButton);
registerButton = (Button)findViewById(R.id.registerButton);
tvInfo = (TextView)findViewById(R.id.tvInfo);
connectToServer(client);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(username.getText().toString(), password.getText().toString(),tvInfo);
}
});
}
private void connectToServer(Client client){
client.startConnection("127.0.0.1", 6969);
String resp = client.sendMessage("hello");
tvInfo.setText(resp);
}
private void validate(String name, String password, TextView tvInfo){
if(name.equals("king_mageni") && password.equals("123456789")){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("username",name);
startActivity(intent);
}
else{
String errorMassage = "Incorrect username or password!";
tvInfo.setText(errorMassage);
}
}
}

Bluetooth communication in Android Cant get the message

I am trying to make a link (bluetooth) between my arduino and android. i want to recieve the data from the arduino. The ListenInput thread does get started but nothing more
Here is my code
package com.codeyard.teleprompter;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
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.io.InputStream;
import java.util.UUID;
public class bleutoothrevivedeletenow extends AppCompatActivity {
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
Button StartConnection;
Button Disconnect;
Button Recieve;
TextView incomingData;
InputStream mmInStream = null;
String incomingMessage;
StringBuilder messages;
Thread ListenInput = new Thread() {
#Override
public void run() {
try {
mmInStream = btSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
Toast.makeText(getApplicationContext(), "Thread started///", Toast.LENGTH_LONG).show();
while (true) {
// Read from the InputStream
try {
if (mmInStream == null) {
Log.e("", "InputStream is null");
}
bytes = mmInStream.read(buffer);
incomingMessage = new String(buffer, 0, bytes);
messages.append(incomingMessage);
Toast.makeText(getApplicationContext(), "incoming message", Toast.LENGTH_LONG).show();
Toast.makeText(bleutoothrevivedeletenow.this, incomingMessage, Toast.LENGTH_LONG).show();
//TODO Remove this
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "128", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "133", Toast.LENGTH_SHORT).show();
}
}
};
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bleutoothrevivedeletenow);
messages = new StringBuilder();
SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(bleutoothrevivedeletenow.this);
address = sharedPreferences.getString("ADDRESS", "");
StartConnection = findViewById(R.id.button5);
Disconnect = findViewById(R.id.button6);
incomingData = findViewById(R.id.textView);
Recieve = findViewById(R.id.button7);
StartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ConnectBT().execute();
}
});
Disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btSocket != null) //If the btSocket is busy
{
try {
btSocket.close(); //close connection
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
}
});
Recieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListenInput.start();
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
incomingData.setText(messages);
handler.postDelayed(this, 2000);
}
};
runnable.run();
}
});
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Connecting....", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
}
}
}
P.S. i have provided the entire code. this code is actually of this github repo:
https://github.com/IamMayankThakur/android-arduino-using-bluetooth
The code first genereated a IllegalThreadException but after debugging i edited the code and now it doesn't crash but still no incoming data

Android telnet client through apache commons

I am fairly new to Android, i want to write a telnet client app for my Android. I have written the code using Apache commons library for telnet. Now i am able to connect to telnet server (for that i have used Asyctask concept) and able to read login banner after a long time i don't know what is causing that. I have modified the example given in Apache commons to work with my android code.I have two java codes in my "src" folder (MainActivity.java and TelnetClientExample.java). First, i want to get the login prompt and then i want user to interact with it please help, Thanks in advance :)
I am posting my screen capture of what i am getting.
MainActivity.java
package com.example.telnetapp;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity{
public static int port_int_address;
private EditText server,port;
private Button connect;
public static String ip,port_address;
public PrintWriter out;
public static TextView textResponse;
static String response;
public InputStream instr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = (EditText)findViewById(R.id.edittext1);
port = (EditText)findViewById(R.id.edittext2);
connect = (Button)findViewById(R.id.connect);
textResponse = (TextView)findViewById(R.id.response);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ip = server.getText().toString();
port_address = port.getText().toString();
port_int_address = Integer.parseInt(port_address);
try{
MyClientTask task = new MyClientTask(ip, port_int_address);
task.execute();
}
catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
TelnetClientExample job;
MyClientTask(String inetAddress, int port){
dstAddress = inetAddress;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
job = new TelnetClientExample();
job.backgroundjob();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
TelnetClientExample.java
package com.example.telnetapp;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetClientExample {
public String remoteip = MainActivity.ip;
public int remoteport= MainActivity.port_int_address;
public static TelnetClient tc = null;
public void backgroundjob() throws IOException {
tc = new TelnetClient();
try {
tc.connect(remoteip, remoteport);
}
catch (Exception e) {
}
}
public void close_con(){
try {
tc.disconnect();
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from disconnecting telnet server ! \n";
}
}
}
The problem is in this code snippet . please look into this and help me to get an interactive session.
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
The problem i am getting -

Categories