I am not a seasoned Java and Android practitioner, however, I will try to explain my issue clearly.
Non-descriptive explanation of what is needed:
Client: Android app, Server: Localhost
Client ---> Server, i.e., clients sends something to server.
Client <--- Server
Client ---> Server
Client <--- Server
Basically what's supposed to happen is RSA key exchanged led by encrypted AES key exchange.
Descriptive explanation:
Both client and server are generating RSA key-pair and they intend to send the public key (post conversion to strings), to each other, in a localhost environment, using Client-Server model, on a button click from my Android app.
Here is my code, which is seeming to work in Telnet, however, it is not the same when it comes to Android. In other words, it is printing the statements I put in to verify failures.
MainActivity.java file:
package com.avineshwar.secureclient;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
public class MainActivity extends AppCompatActivity {
private Socket client;
private PrintWriter printwriter;
private Button button;
private TextView textView;
private String messsage;
SecureRandom random;
KeyPairGenerator keyPairGenerator;
KeyPair keyPair;
PrivateKey privateKey;
PublicKey publicKey;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader = null;
String server = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView);
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
random = new SecureRandom();
keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyPairGenerator.initialize(2048, random);
keyPair = keyPairGenerator.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
messsage = String.valueOf(publicKey);
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
if (server == null || server == "null") {
server = "null";
textView.setText(server);
} else {
textView.setText(server);
}
}
}
);
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
try {
client = new Socket("192.168.1.169", 4444); // connect to the server
} catch (IOException e) {
e.printStackTrace();
}
printwriter = null;
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage);
inputStreamReader = null;
inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
server = bufferedReader.readLine();
StringBuilder stringBuilder = new StringBuilder();
while ((server = bufferedReader.readLine()) != null) {
stringBuilder.append(server + "\n");
}
server = stringBuilder.toString();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
//#Override
//public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.slimple_text_client, menu);
// return true;
// }
}
SecureServer.java file:
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.KeyGeneratorSpi;
import sun.nio.cs.Surrogate;
public class SecureServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) throws NoSuchAlgorithmException {
SecureRandom random = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048, random);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started listening on the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = null;
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
if (message == null || message == "null") {
message = "null";
}
System.out.println(message);
PrintWriter out = null;
out = new PrintWriter(clientSocket.getOutputStream(), true);
message = publicKey.toString();
out.write(message);
System.out.println(message);
out.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press to send RSA key"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avineshwar.secureclient">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I do understand one thing though, however, I am not sure if it is correct and that is until I don't close my PrintWriter object in the Android app, the data is not going to be reflected on the server side, however, even if I do that, it is just solving one part of the scene, i.e., data from Android to server. I am not sure about any specific manner of collecting the data being sent from server though it is working for Telnet, i.e., both to and fro.
In SecureServer.java file, this statement,
inputStreamReader.close();
If put before these statements,
out = new PrintWriter(clientSocket.getOutputStream(), true);
message = publicKey.toString();
out.write(message);
System.out.println(message);
is throwing a handled IOException, which says Problem in message reading.
Apart from this, what I have observed is that in case we are writing anything to a socket, the "output to socket" stream has to be immediately closed as well, i.e., we cannot deal with any other stream related to that socket until this stream is closed.
A higher-level view of, my experience with, and approach to, the problem:
Program structure has to be in opposite direction.
When client sends something, server should be in a receiving state and vice-versa.
For that to be possible, any previous state has to be completed.
My client is sending some data to server (which is being received as well).
Server on receiving that data, wants to send some data back.
For that, server has to open an output stream for the same socket through which he read the data. I assume we shouldn't close the previously opened input stream before doing this because it never worked for me that way.
Server does the job of creating an input stream and then writing the data to the input stream.
However, parallely, in the client Android app, it is also expecting the data from server at socket's input stream. I assumed when server will send the data, this stream will receive it (and display it in a text view widget).
Right now, this idea/implementation seeming to work for Telnet (client) and Server.
In the past, data transfer from server to Android app has worked for me though. If there is just one-way transfer from server to client (Android app), it works.
Related
I created a code that sends commands to a server I wrote using Python. The code only works once (the server receives what I sent the first time) but the second time it seems that nothing is sent because the server does not receive new information it keeps waiting for new information. My code:
StringBuilder Data = new StringBuilder(); // The Data to send
public void Send(View view) {
Thread send = new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket("20.7.65.2", 6398); // Create connection to the server
OutputStream output = socket.getOutputStream(); // Get the key to output to server
PrintWriter writer = new PrintWriter(output, true);
writer.println(Data.toString()); // Send the data
Data.setLength(0); // Delete "Data" contant
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
send.start();
}
public void Continue(View view) {
Data.append("Hello from client"); // Append to "Data"
Send(null); // Run the send functionn (again)
}
}
My Python Server:
import socket, time
soc = socket.socket()
soc.bind((socket.gethostname(), 6398))
soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()
print("Client connected")
while True:
message = client.recv(1024).decode()
if(message != ""):
print(message)
time.sleep(0.1)
In short, I try to run the run function twice. The first time it sends to the server and it receives the information, and the second time the server is still waiting for the information and not receiving what I sent again. Maybe it's because he's not available to receive all messages sent to him from all clients
It is also possible instead of sending me a Java code to send a Python code that will work and receive all messages from all clients
In your code, the server is only accepting a cnnection once and then it recieves from same client. But according to your question, I think your server should be able to listen to mulitple clients hence, you could use multithreading in the server. Instead of threading the client, I used button which when clicked connects with server. I also can't understand the need of threading the client. If you think, some changes are required in the answer, you could comment.
this is python server
import socket, time
import threading
soc = socket.socket()
# print(socket.)
soc.bind(("192.168.1.5", 6398))
soc.listen(5)
def info(client):
message = client.recv(1024).decode()
if(message != ""):
print(message)
return
while True:
(client, (ipNum, portNum)) = soc.accept()
print("Client connected")
threading.Thread(target=info,args=(client,)).start()
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
StringBuilder Data = new StringBuilder(); // The Data to send
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= findViewById(R.id.connectBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Continue();
}
});
}
public void Send() {
Thread send = new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket("192.168.1.5", 6398); // Create connection to the server
OutputStream output = socket.getOutputStream(); // Get the key to output to server
PrintWriter writer = new PrintWriter(output, true);
writer.println(Data.toString()); // Send the data
Data.setLength(0); // Delete "Data" contant
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
send.start();
}
public void Continue() {
Data.append("Hello from client"); // Append to "Data"
Send(); // Run the send functionn (again)
}
}
Don't forget to add <uses-permission android:name="android.permission.INTERNET"/> in the AndroidManifest.xml.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/connectBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I can't receive any packets on my app. I have a computer running from console-php this script:
$broadcast_string='http://hellokitty/shownumber.html';
$port=2328;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
while(true){
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
sleep(1);
echo "Broadcasting ...\n";
}
on the other hand I got this code running on my phonegap app on the MainActivity.java file:
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.content.Context;
import org.apache.cordova.*;
import java.io.*;
import java.net.*;
import java.util.*;
import android.content.BroadcastReceiver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.content.Context;
import android.app.DialogFragment;
import android.app.AlertDialog;
import android.view.Menu;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.provider.Settings;
import android.view.WindowManager;
import android.util.Log;
import android.content.res.AssetManager;
public class MainActivity extends CordovaActivity
{
public static String URL = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
DatagramSocket socket;
//Wakelock------------------------------------------------------------------------------------------------------------------
WakeLock mWakeLock = null,mPartialWakeLock = null;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// lock used to keep the processor awake.
mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
mPartialWakeLock.acquire();
final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock lock = wifi.createMulticastLock("UDP");
lock.acquire();
//--------------------------------------------------------------------------------------------------------------------------
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
//socket = new DatagramSocket(2328, InetAddress.getByName("0.0.0.0"));
socket = new DatagramSocket(2328);
socket.setBroadcast(true);
URL = null;
while (URL == null) {
System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!");
//Receive a packet
byte[] recvBuf = new byte[12000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
//socket.setSoTimeout(10000);
socket.receive(packet);
//Packet received
System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData()));
String message = new String(packet.getData()).trim();
URL=message;
break;
}
} catch (IOException ex) {
//Nothing
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
while(URL == null){
continue;
}
Log.d("net_discover",URL);
super.loadUrl(URL);
}
}
I've tested the network sniffing packets and traffic it's ok.
I've added the wakelock section since I've read that android blocks broadcast packets, but I'm still not getting anything on my device.
I'm working on a Motorola running Android 4.4.4
On the adb logcat, app is stuck on the msg "Ready to receive.." and that's all I get.
Any suggestions?
UPDATE:
I added code to my app to send packet before starting receiving and for my surprise it does receive it. So I started sending packets and sniffing the network from my computer and I don't see any. So doing some more research I found that the app is working on the lo interface (loopback, 127.0.0.1).
So my question now is, how do I make the app receive packets from wifi interface?
I have made application : mysql <-> Android using php.
I success to mysql with php.
http://localhost/phptest/newfile.php
id: jogi - password: 1234
id: jogi1 - password: 12341
id: jogi2 - password: 12342
but i have some trouble with connet Android.
Some code's are ignored. and does not message on log.
also android AVD not stopped but do not show any change. console do not show error, too... What can i do? or How can i check errors?
MainActivity.java
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.text_view1);
}
public void Show_list(View view){
new SigninActivity(this,result,0).execute();
}
}
SigninActivity.java
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView resultField; //statusField
private int byGetOrPost = 0;
public SigninActivity(Context context,TextView resultField,int flag) {
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
String myResult = null; //initiate;
if(byGetOrPost == 0){ //means by Get Method
Log.d("flag","0");
try {
URL url = new URL("http://http://localhost/phptest/newfile.php");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
Log.d("where","http connect");
http.setDefaultUseCaches(false);
http.setDoInput(true);
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
Log.d("where","property");
//--------------------------
InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR");
BufferedReader reader = new BufferedReader(tmp);
StringBuilder builder = new StringBuilder();
String str;
Log.d("where","inputstream");
while ((str = reader.readLine()) != null) {
builder.append(str + "\n");
}
myResult = builder.toString();
Log.d("myresult",myResult);
return myResult;
} catch (MalformedURLException e) {
//
} catch (IOException e) {
//
} // try
}
else{
}
return myResult;
}
#Override
protected void onPostExecute(String result){
if(result != null)
this.resultField.setText(result);
else
Log.d("failed", "postfailed");
}
}
This is all of my log. only one error when open but i think that AVD is connect well so it is not important.
A curious thing is that I can't find "input stream" with tag "where" in SigninActivity.java;
08-16 07:31:48.603: E/Trace(772): error opening trace file: No such file or directory (2)
08-16 07:31:49.753: D/gralloc_goldfish(772): Emulator without GPU emulation detected.
08-16 07:32:55.214: D/flag(772): 0
08-16 07:32:55.224: D/where(772): http connect
08-16 07:32:55.224: D/where(772): property
08-16 07:32:55.417: D/failed(772): postfailed
no error with application starting. If click the button 'list', no error, no stop also but no any change view. just white blank screen.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="26dp"
android:layout_toLeftOf="#+id/button2"
android:onClick="Show_list"
android:text="#string/Show_List" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1" >
<TextView
android:id="#+id/text_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp" />
</LinearLayout>
you are not directly talking to mysql , your android app will receive a response from the webserver and so you need to call the webserver accessible url .
If you are in a local network give the webserver local address in
URL url = new URL("http://{webserverURL}/phptest/newfile.php");
You can get the IP from apache installed machine using ipconfig (Windows), ifconfig (linux).
I am developing an application in which first I have to search available Bluetooth devices and make connection. I have done this task. After this, one new Activity opens in which there is one Edittext and one Button. I have developed the below code. It is not giving any output.
I am passing data using MAC address of connected device.
java file...
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint("NewApi")
public class NewMessage extends Activity {
Button btn;
EditText et;
String message1="Hello";//on button click by default
BluetoothAdapter mBluetoothAdapter1 = null;;
// BluetoothAdapter mBluetoothAdapter;
public static String MacAddress;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
setContentView(R.layout.message);
btn = (Button) findViewById(R.id.btn);
et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
Toast.makeText(getBaseContext(), MacAddress, 10000).show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/*private void sendDataToPairedDevice(String message ,BluetoothDevice device){
byte[] toSend = message.getBytes();
try
{
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
// Your Data is sent to BT connected paired device ENJOY.
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint">
<requestFocus />
</EditText>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send" />
</LinearLayout>
Please do help me...
Here is my code, which has the problem..
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This doesn't answer your question directly but one thing I am noticing is that you have 10000 as your duration parameter for Toast.makeText(), which is invalid. It only accepts Toast.LENGTH_SHORT or Toast.LENGTH_LONG, which are actually just 0 or 1. Check the docs: http://developer.android.com/reference/android/widget/Toast.html
[EDIT]
Another error I see in your code is you pass an empty String to getRemoteDevice. Try doing getRemoteDevice("00001101-0000-1000-8000-00805F9B34FB") and see what happens. Again, read the docs: http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getRemoteDevice(java.lang.String)
Include the connect function.
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
socket.connect(); // here
OutputStream mmout=socket.getOutputStream();
I have the follwing code to establish a TCP connection between a C server and an android client. The c server works fine. But the following code shows errors on building in eclipse.
package com.app.client.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class my_activity extends Activity
{
private TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
connectSocket("Hello");
}
});
}
private void connectSocket(String a){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 4444);
message = "1";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
while ((in.readLine()) != null) {
txt.append(in.readLine());
}
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
}
}
The errors shown on building is:
main cannot be resolved or is not a field my_activity.java /Androidclient/src/com/app/client/app line 29 Java Problem
What can I do so as to resolve this problem? Thanks in advance.
You need to set up your AndroidManifest.xml within your activity. Find it and add your main activity to it like this:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="my_activity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This will tell the android system that this is your main activity and it should be launched on application start.
If you're new to android, i suggest that you read this