I have written code for the client and server which will be connected over wifi and client will send string to server, but the problem is even though I think I have implemented the code correctly it doesn't seem to work. Even the logcat is not showing any errors while I run the code on android device. Can someone help please?
Here's the client code.
public class ControlActivity extends Activity {
WifiManager wifi=null;
WifiInfo winfo=null;
Socket ssocket=null;
String sstr=null;
String ipadd=null;
Integer ip;
TextView text;
Integer k=0;
Handler handler;
Boolean pdown=false;
InetAddress seraddr;
public String intToIp(int i) {
return ( i & 0xFF) + "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ((i >> 24 ) & 0xFF );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_control);
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
winfo = wifi.getConnectionInfo();
ip = winfo.getIpAddress();
ipadd = intToIp(ip);
try {
seraddr = InetAddress.getByName(ipadd);
} catch (UnknownHostException e) {
e.printStackTrace();
}
text = (TextView)findViewById(R.id.textView1);
text.setText(ipadd);
handler = new Handler(){
#Override
public void handleMessage(Message msg1){
Bundle bundle = msg1.getData();
String str = bundle.getString("key");
text.setText(str);
}
};
ImageButton butup = (ImageButton)findViewById(R.id.buttonup);
butup.setOnTouchListener(new View.OnTouchListener() {
private Thread touchthread;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pdown==false)
pdown=true;
sstr = "up";
this.touchthread = new Thread(new OnTouchClientThread());
this.touchthread.start();
break;
case MotionEvent.ACTION_UP:
pdown=false;
}
return true;
}
});
ImageButton butdown = (ImageButton)findViewById(R.id.buttondown);
butdown.setOnTouchListener(new View.OnTouchListener() {
private Thread touchthread;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pdown==false)
pdown=true;
sstr = "down";
this.touchthread = new Thread(new OnTouchClientThread());
this.touchthread.start();
break;
case MotionEvent.ACTION_UP:
pdown=false;
}
return true;
}
});
}
public class OnTouchClientThread implements Runnable{
#Override
public void run() {
try {
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
ssocket = new Socket(seraddr,5479);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ssocket.getOutputStream())),true);
while(pdown==true){
k=k+1;
bundle.putString("key",k.toString());
msg.setData(bundle);
handler.sendMessage(msg);
out.println(sstr);
}
out.flush();
out.close();
ssocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
here's the server
public class FInterActivity extends Activity {
WifiManager wifi=null;
Socket ssocket=null;
String sstr=null;
Thread recithrd;
TextView testing;
ServerSocket ss;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finter);
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
testing = (TextView)findViewById(R.id.testtext);
testing.setText("Starting thread");
this.recithrd = new Thread(new ServerThread());
this.recithrd.start();
handler = new Handler(){
#Override
public void handleMessage(Message msg1){
Bundle bundle = msg1.getData();
String str = bundle.getString("key");
testing.setText(str);
}
};
}
public class ServerThread implements Runnable{
#Override
public void run() {
try {
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
ss = new ServerSocket(5479);
ssocket = ss.accept();
while(true){
BufferedReader input = new BufferedReader(new InputStreamReader(ssocket.getInputStream()));
sstr=null;
sstr = input.readLine();
if(sstr!=null){
bundle.putString("key", sstr);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
handler.post(new Runnable(){
#Override
public void run() {
testing.setText("unknown host");
}
});
} catch (IOException e) {
e.printStackTrace();
handler.post(new Runnable(){
#Override
public void run() {
testing.setText("Io exception");
}
});
}
}
}
and yes i have provided all the permissions required. please help. i am stuck on this for days.
Your code seems to be wrong in more than one place.
1) The client seems to be getting its own address, putting it into seraddr, and trying to connect to itself! Certainly the server has a different address, unless you are doing a local connection and in this case you should just use 127.0.0.1.
2) At server side, you are accept()ing only once, handling the connection and exiting the thread. This means that your server will accept only one connection and no more. Is this what you wanted?
Related
I have an application that get user input(name and number) , then scanning QR code , and on a press of a button it send the data to my server and get replay from it.
everything is working now as it should.(I can see the message for the server as string when I'm in debug mode).
but I can't see the toast - it doesn't shown
why?
this is the class I have in the ScanActivity.java
public class ScannedBarcodeActivity extends AppCompatActivity {
SurfaceView surfaceView;
TextView txtBarcodeValue;
private BarcodeDetector barcodeDetector;
private CameraSource cameraSource;
private static final int REQUEST_CAMERA_PERMISSION = 201;
Button btnAction;
String intentData = "";
String ServerReply;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_barcode);
initViews();
}
private void initViews() {
txtBarcodeValue = findViewById(R.id.txtBarcodeValue);
surfaceView = findViewById(R.id.surfaceView);
btnAction = findViewById(R.id.btnAction);
btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (intentData.length() > 0) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String server_ip = "My.Server.Public.IP";
int server_port = 9999;
String messageStr = intentData + "!" + phone +"!"+ name+"!##";
Socket clientSocket = new Socket(server_ip, server_port);
PrintWriter mBufferOut = new PrintWriter((new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))), true);
BufferedReader mBufferIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
mBufferOut.println(messageStr);
ServerReply = mBufferIn.readLine();
mBufferIn.close();
//see why this is not working - can;t see the toast
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_LONG).show();
clientSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
// Toast.makeText(getApplicationContext(),ServerReply,Toast.LENGTH_LONG).show();
thread.start();
}
Toast.makeText(getApplicationContext(),ServerReply,Toast.LENGTH_LONG).show();
SystemClock.sleep(1000); //ms
Toast.makeText(getApplicationContext(),"Going to Main Page now",Toast.LENGTH_LONG).show();
finish();
}
// }
});
}
this is the how it's look after what you told me to do :(still doesn't work , and for some reason it "skip" the toast part)
public class ScannedBarcodeActivity extends AppCompatActivity {
SurfaceView surfaceView;
TextView txtBarcodeValue;
private BarcodeDetector barcodeDetector;
private CameraSource cameraSource;
private static final int REQUEST_CAMERA_PERMISSION = 201;
Button btnAction;
String intentData = "";
boolean isEmail = false;
String ServerReply;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_barcode);
initViews();
}
private void initViews() {
txtBarcodeValue = findViewById(R.id.txtBarcodeValue);
surfaceView = findViewById(R.id.surfaceView);
btnAction = findViewById(R.id.btnAction);
;
btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (intentData.length() > 0) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String server_ip = "My.Server.IP";
int server_port = 9999;
String messageStr = intentData + "!" + phone +"!"+ name+"!##";
Socket clientSocket = new Socket(server_ip, server_port);
PrintWriter mBufferOut = new PrintWriter((new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))), true);
BufferedReader mBufferIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
mBufferOut.println(messageStr);
ServerReply = mBufferIn.readLine();
mBufferIn.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_SHORT).show();
}
});
clientSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
SystemClock.sleep(1000); //ms
finish();
}
// }
});
}
All the UI rendering should be done on main thread, you can use view handler to do that
v.post(new Runnable(){
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_LONG).show();
});
This will execute on UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_SHORT).show();
}
});
Your toast is coming from a background thread, it needs to be executed on the main/UI thread
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_LONG).show();
}
});
1) You have to write toast in UI thread. like blow
// you can write toast in UI thread like this
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_LONG).show();
}
});
2) You have to make sure intentData.length() is not 0 ( if your intentData is empty then your thread will never execute, be sure about that.)
if (intentData.length() > 0) {...}
3) And also make sure your code not given any exception before showing your toast message [handle your exception in catch block like following]
catch (Exception e){
Log.e("Exception","your exception is "+e.toString());
}
Hope it helps you.
Toast can't be run on other than the UI thread, you can use
runOnUiThread(new Runnable() {
#Override
public void run() {
//see why this is not working - can;t see the toast
Toast.makeText(getApplicationContext(),"inside the thread",Toast.LENGTH_LONG).show();
}
});
I'm work on crate server and android client
but thread doesn't interrupted by android client
My android Client has request for the RoomList from server
and Server receive, Client Accept
and fill in my ListView used the Adapter
here's problem if Click backButton,
than RoomListAcitivity was close and thread was stop
but thread dosen't stop just alive in my app
first Enter has work on sucessfully
but Press BackButton on and re-Enter this Activity
MyApp just White, No Action
how can i stop this thread?
(and sorry for my English skill...)
i tried .interrupt() method , and handler.removeMessages(0)
but failed thread keep alive
upload this full java code just in case...
ListView roomList;
RoomAdapter roomAdapter;
Socketservice ss;
String msg,rtitle;
String msgs[];
String list[];
Thread listthread,EnterRoomThread,removeV;
boolean staterun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_room);
roomList = findViewById(R.id.roomList);
roomAdapter = new RoomAdapter();
listthread = new Thread() {
public void run(){
ss.out.println("163|");
ss.out.println("100|");
try {
while (staterun == true) {
msg = ss.in.readLine();
handler.post(new Runnable() {
public void run() {
msgs = msg.split("\\|");
String protocol = msgs[0];
switch (protocol) {
case "163":
list = msgs[1].split(",");
for (int i = 0; i < list.length; i++) {
String list1[] = list[i].split("-");
String listT = list1[0];
int listC = Integer.parseInt(list1[1]);
int listI = Integer.parseInt(list1[2]);
roomAdapter.CreateRoom(listI, listT, listC);
}
roomList.setAdapter(roomAdapter);
msg = "";
msgs = null;
break;
case "200":
Intent i = new Intent(getApplicationContext(), GameWaitingActivity.class);
i.putExtra("tname", rtitle);
staterun = !staterun;
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
startActivity(i);
finish();
break;
case "201":
Toast.makeText(getApplicationContext(), "방이 꽉 찼습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
} catch (IOException e) {
}
}
};
listthread.start();
roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Room item = (Room) roomList.getItemAtPosition(position);
rtitle=item.getTitle();
EnterRoomThread = new Thread() {
public void run() {
ss.out.println("200|" + rtitle);
EnterRoomThread.interrupt();
}
};
EnterRoomThread.start();
}
});
}
Handler handler = new Handler();
#Override
public void onBackPressed() {
removeV = new Thread() {
public void run(){
ss.out.println("101|");
removeV.interrupt();
}
};
removeV.start();
handler.removeMessages(0);
staterun = false;
listthread.interrupt();
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
finish();
}
}
Go ahead with this, write this inside run() method
//use this boolean value to keep track.
boolean shouldRunFlag = true;
while (shouldRunFlag) {
try {
Thread.sleep(10);
//Do your work............
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Interrupted Exception caught");
// change the flag, so that while loop can be broken.
shouldRunFlag = false;
Log.v(TAG, "run: breaking the loop");
break;
}
}
and this is how you interrupt and clean the thread
private void interrupt(Thread currentThread) {
Log.i(TAG, "interrupt");
if (currentThread != null) {
Thread dummyThread = currentThread;
dummyThread.interrupt();
currentThread = null;
}
}
We have an main activity with a Text View which is requested to auto-retrieve data from TCP server in LAN.
We enabled AsyncTask in updateData() to call Connect to call Handler to update TextView named mTvVoc, and refresh connection by beginConnect().
The problem is the mTvVoc is not updated, it seems the AsyncTask does not function as expected?
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateData();
}
public void updateData(final String order) {
Connect(HOST, PORT, order);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
System.out.println("get data from order--->" + order);
beginConnect(HOST, PORT, order);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
}
public String Connect(final String HOST, final int PORT, final String OderType) {
new Thread(new Runnable() {
#Override
public void run() {
try {
socket = new Socket(HOST, PORT);
bufferedInputStream = new BufferedInputStream(socket.getInputStream());
System.out.println("bufferedInputStream--->" + bufferedInputStream);
printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
printWriter.println(Integer.toHexString(Integer
.parseInt(OderType)));
}
}
while (true) {
if (!socket.isClosed() && socket.isConnected() && !socket.isInputShutdown()) {
int temp = 0;
byte[] buf = new byte[1024];
while ((temp = bufferedInputStream.read(buf)) != -1) {
isConn(socket);
Log.d("Data received", new String(buf, 0, temp));
acceptinfo = new String(buf, 0, temp);
System.out.println("Data received====》" + acceptinfo);
Message message = new Message();
message.what = 1;
message.obj = acceptinfo;
handler.sendMessage(message);
}
}
}
} catch (UnknownHostException e) {
System.out.println("UnknownHostException-->connection failed");
stopConnect();
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException-->connection failed");
stopConnect();
e.printStackTrace();
}
}
}).start();
return acceptinfo;
}
public String beginConnect(final String HOST, final int PORT, final String OderType) {
new Thread(new Runnable() {
#Override
public void run() {
try {
socket = new Socket(HOST, PORT);
bufferedInputStream = new BufferedInputStream(socket.getInputStream());
System.out.println("bufferedInputStream--->" + bufferedInputStream);
printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
printWriter.println(Integer.toHexString(Integer.parseInt(OderType)));
}
}
} catch (UnknownHostException e) {
System.out.println("UnknownHostException-->connection failed");
stopConnect();
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException-->connection failed");
stopConnect();
e.printStackTrace();
}
}
}).start();
return acceptinfo;
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i("message", msg.obj.toString());
if (msg.what == 0) {
mIvContent.setImageResource(R.drawable.wangluo_gray);
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_SHORT).show();
reGetData();
}
if (msg.what == 1) {
String info = msg.obj.toString();
if (info.length() != 18) {
mIvContent.setImageResource(R.drawable.wangluo_gray);
System.out.println("data verification failed");
reGetData();
return;
}
String iszeroupString = info.substring(1, 3);
String temperature = Integer.toString(Integer.parseInt(info.substring(3, 5), 16));
String vocValue = Integer.toString(Integer.parseInt(info.substring(7, 9), 16));
mTvVoc.setText(getVOC((Integer.valueOf(vocValue ) / 100.00)));
}
}
}
You cannot directly communicate from background thread to UI thread to
update any UI components.
Use this in your background thread to update textview from AsyncTask.
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d("UI thread", "I am the UI thread");
// update your text here
}
});
To update on UI, you need to run the codes in UIThread. See code below and put in your handler:
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("message", msg.obj.toString());
if (msg.what == 0) {
mIvContent.setImageResource(R.drawable.wangluo_gray);
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_SHORT).show();
reGetData();
}
if (msg.what == 1) {
String info = msg.obj.toString();
if (info.length() != 18) {
mIvContent.setImageResource(R.drawable.wangluo_gray);
System.out.println("data verification failed");
reGetData();
return;
}
String iszeroupString = info.substring(1, 3);
String temperature = Integer.toString(Integer.parseInt(info.substring(3, 5), 16));
String vocValue = Integer.toString(Integer.parseInt(info.substring(7, 9), 16));
mTvVoc.setText(getVOC((Integer.valueOf(vocValue ) / 100.00)));
}
}
});
Pretty bad to code that handler to update the gui. Do away with it as AsyncTask provides already the functionality to do so.
You should have looked better at the many examples.
Use publishProgress() and onProgressUpdate() to update a progress bar and/or other gui elements.
And do not wrap your code in a thread if it has to be executed in doInBackground().
I want to call non static method in my Activity A from Activity B
like
class A extend Activity(){ public void c(){}}
class B extend Activity(){ A.C(); }
How I could do this in android Activity help me.
public class Voice extends Activity {
TextView resultTEXT ;
MediaPlayer mp;
ImageView view;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
int page;
// SPP UUID service
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
private static String status;
BluetoothDevice device;
private ConnectedThread mConnectedThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice);
//get the stored mac address of the device
SharedPreferences shared = getSharedPreferences("BtAddress", MODE_PRIVATE);
address = (shared.getString("btAddress", ""));
status = (shared.getString("connect", ""));
btAdapter = BluetoothAdapter.getDefaultAdapter();
//create device and set the MAC address
device = btAdapter.getRemoteDevice(address);
checkBTState();
if(status=="true")
{
new CountDownTimer(1000, 10000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mp = MediaPlayer.create(Voice.this, R.drawable.onload);
mp.setLooping(false);
mp.start();
}
}.start();
}
view=(ImageView)findViewById(R.id.imageButton);
view.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_DOWN:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
//handle double tap
Toast.makeText(Voice.this, "Help", Toast.LENGTH_LONG).show();
mp = MediaPlayer.create(Voice.this, R.drawable.help);
mp.setLooping(false);
mp.start();
}
}, ViewConfiguration.getDoubleTapTimeout());
}
else if(numberOfTaps== 1)
{
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(Voice.this, "proceed",Toast.LENGTH_LONG).show();
Intent intent=new Intent(Voice.this,ChangeSpeed.class);
startActivity(intent);
}
}, ViewConfiguration.getTapTimeout());
}
}
return true;
}
});
}
public void onActivityResult(int request_result, int result_code, Intent i)
{
super.onActivityResult(result_code, result_code, i);
switch (result_code)
{
case 100: if(result_code == RESULT_OK && i != null)
{
ArrayList<String> result = i.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
resultTEXT.setText(result.get(0));
}
break;
}
}
#Override
public void onResume() {
super.onResume();
try
{
btSocket = createBluetoothSocket(device);
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
}
catch (IOException e)
{
try
{
btSocket.close();
}
catch (IOException e2)
{
Log.e("",""+e2);
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
// send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
#Override
public void onPause()
{
super.onPause();
try
{
// Bluetooth sockets close when leaving activity
btSocket.close();
} catch (IOException e2)
{
Log.e("",""+e2);
}
}
/*
//Checks that the Android device Bluetooth is available turned on if off automatically
*/
private void checkBTState()
{
if(btAdapter==null)
{
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else
{
if (btAdapter.isEnabled())
{
}
else
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private class ConnectedThread extends Thread {
// private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket)
{
// InputStream tmpIn = null;
OutputStream tmpOut = null;
try
{
//Create I/O streams for connection
// tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e)
{
}
//mmInStream = tmpIn;
mmOutStream = tmpOut;
}
//write method
public void write(String input)
{
byte[] msgBuffer = input.getBytes();
//converts entered String into bytes
try
{
mmOutStream.write(msgBuffer);
} catch (IOException e)
{
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
/*
method to on the Fan
*/
public void functionFanOn()
{
mConnectedThread.write("1");
// Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on Fan", Toast.LENGTH_SHORT).show();
Log.e("", "On");
}
functionFanOn() is the method that I want to call in B
You have a problem with the structure of your code. The function in Activity A, which establishes a connection to the Arduino, should be move in another class. Lets say an Utils class.
Refactoring your common code to an new class, so that you can manager it by single instance
This lib EventBus may solve your issue
Another Way is Create Seprate class and use all method of seprate class
class Utils
{
public void c(Context context)
{
//put your code
}
}
And Activity class Like this
class MyActivity extends Activity
{
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.main);
//method calling
Utils utils=new utils();
utils.c(MyActivity.this);
}
}
Please read my sample code
Is this one activity class like this and contain c(); method
class A extend Activity
{
public void c()
{
}
}
And This is your Second activity class
class B extend Activity
{
A a=new A();
a.c();
}
i hope this help you
why UDP Android just once send [Please Help]
name class MainActivity
public class MainActivity extends Activity implements
android.view.View.OnClickListener {
public static final String SERVERIP = "192.168.5.255";
public static final int SERVERPORT = 4444;
public TextView text1;
public EditText input;
public Button btn;
public boolean start;
public Handler Handler;
conntection with pc
this method on create
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.textView1);
input = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
start = false;
new Thread(new Server()).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
new Thread(new Client()).start();
Handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
text1.append(text);
}
};
}
this class Client
#SuppressLint("NewApi")
public class Client implements Runnable {
#Override
public void run() {
while (start == false) {
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
updatetrack("Client: Start connecting\n");
DatagramSocket socket = new DatagramSocket();
byte[] buf;
if (!input.getText().toString().isEmpty()) {
buf = input.getText().toString().getBytes();
} else {
buf = ("Default message").getBytes();
}
DatagramPacket packet = new DatagramPacket(buf, buf.length,
serverAddr, SERVERPORT);
updatetrack("Client: Sending ‘" + new String(buf) + "’\n");
socket.send(packet);
updatetrack("Client: Message sent\n");
updatetrack("Client: Succeed!\n");
} catch (Exception e) {
updatetrack("Client: Error!\n");
}
}
}
this class Client
public class Server implements Runnable {
#Override
public void run() {
while (start = false) {
try {
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT,
serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:"
+ new String(packet.getData()) + "'n");
updatetrack("Server : Succed!n");
} catch (Exception e) {
updatetrack("Server: Error!n" + e.getMessage());
}
}
}
}
public void updatetrack(String s) {
Message msg = new Message();
String textTochange = s;
msg.obj = textTochange;
Handler.sendMessage(msg);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button1)
start = true;
}
}
if i make my class server with
while (true){
application is error
help me please ? why just once send message Thanks before
For Client class, you have nothing in the loop:
while (start == false) {
}
And then outside of it, you call send only once -- that is why it is sending only once.
socket.send(packet);
If you want to call send continuously, then one way to do is to keep it in a loop. Of course, you would need to terminate the loop once the task is done but that would be driven by your application logic.