I use the following code to receive the data using UDP. When I click the back button my screen visual is closed and it shows the home screen. But a thread is working in the background (it receives the data from the UDP server). When I close the application I also need to stop the thread. How to stop a thread?
public void onClick(View view) {
port=Integer.parseInt(etd_port.getText().toString());
etd_port.setCursorVisible(false);
Thread fst = new Thread(new Server());
fst.start();
}
public class Server implements Runnable {
private String tagid="",roomid="";
public final int SERVERPORT = port;
private DatagramSocket ds;
private String recdata;
#Override
public void run() {
int buffer_size = 1024;
byte buffer[] = new byte[buffer_size];
try {
ds = new DatagramSocket(SERVERPORT);
while (true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
Log.d("MY UDP ","After Receive");
recdata=new String(p.getData(),0,p.getLength());
Log.d("Receive data ",recdata);
}
} catch(Exception e){
Log.e("MY UDP ", " Error", e);
}
}
}
......
#Override
protected void onStop() {
finish();
fst.stop();
super.onStop();
}
You have to change while condition:
class Server implements Runnable {
private boolean running;
public void run() {
running = true;
while (running) {
// do stuff here
}
}
public stop() {
running = false
}
}
protected void onStop() {
fst.stop()
}
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 am building an application that starts a Connection via a Thread but when i initialize the Connection the Application doesn't connect and stops (it continues to work but it does nothing).
1 week ago it did work without any troubles, but when i updated Android Studio it started causing me this problem.
This is the abstract class of the Connection:
public abstract class Connection implements Runnable{
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private Semaphore semaphore;
private ArrayList<String> messageQueue;
private Thread connection;
//private String state; // CONNECTED,RUNNING,STOPPED,RESTARTED,CLOSED
Connection(InetAddress address, int port) {
try {
socket = new Socket(address,port);
onConnectionEstablished(socket);
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
semaphore = new Semaphore(1);
messageQueue = new ArrayList<>();
} catch (Exception e) {
close();
}
}
#Override
public void run() {
connection = Thread.currentThread();
while(!connection.isInterrupted()){
this.read();
}
}
// Checks if connection is established
boolean isConnectionEstablished(){
return socket != null && !socket.isClosed();
}
public abstract Socket onConnectionEstablished(Socket socket);
// Restarts the connection
public abstract void onConnectionClose();
// Launched when message is received
public abstract String onMessageReceived(String message);
// Launched when message is posted
public abstract String onMessagePosted(String message);
// Launched when message is sent
public abstract String onMessageSent(String message);
// Post message
public void postMessage(String message){
messageQueue.add(message);
sendMessage();
}
// Send Message
private void sendMessage() {
final String message = messageQueue.get(0);
onMessagePosted(message);
new Thread(new Runnable() {
#Override
public void run() {
try {
semaphore.acquire();
System.out.println(Colors.color("[*] Sending: \'"+message+"\' [*]","blue"));
writer.print(message);
writer.flush();
messageQueue.remove(0);
semaphore.release();
} catch (Exception e) {
close();
}
}
}).start();
onMessageSent(message);
}
// Read messages
private void read(){
try {
String message = reader.readLine();
if(message != null && message.length() > 0)
onMessageReceived(message);
else
throw new Exception();
} catch (Exception e) {
close();
}
}
// Close the connection
private void close(){
try{
connection.interrupt();
this.writer.close();
this.reader.close();
this.socket.close();
}catch(Exception e){
System.out.println(Colors.color("[X] Error while closing [X]","red"));
}
onConnectionClose();
}
// Restart the connection
void restart(){
new Thread(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
System.out.println(Colors.color("[X] Error while restarting [X]","red"));
}
new Thread(new ConnectionInitializer()).start();
}
}).start();
}
}
While doing some debugging i found out that it apparently blocks when the socket is instantiated.
I'm trying to get working a Service that hosts a server, and whenever it receives data from it's one client it sends the data off to another server. Both of which are connected by a tcp socket that remains open indefinitely. I'm having trouble implementing single tcp sockets that both read and write correctly.
I'm receiving XML from both ends, and they're well defined. Some processing is done on the xml received and it needs to be added to a queue that handles it's order.
Ideally the connection going in either direction should remain open indefinitely.
But so far I'm seeing the Sockets just keep closing both this Service and the ServerCode are getting closed sockets and I'm not sure why.
Is there a way to establish connections to my two endpoints and keep the sockets open indefinitely?
public class routing extends Service {
private static final String TAG = "[RoutingService]";
private final IBinder mBinder = new RoutingBinder();
private final ScheduledThreadPoolExecutor mRoutingThreadPool = new ScheduledThreadPoolExecutor(2);
private boolean running = false;
private URI serverAddress;
private URI clientAddress;
private Thread serverServiceThread = new ClientService();
private Thread clientServiceThread = new ServerService();
private PriorityBlockingQueue<String> clientQueue;
private PriorityBlockingQueue<String> serverQueue;
public void setClientAddress(URI testServer) {
this.serverAddress = testServer;
this.mRoutingThreadPool.remove(clientServiceThread);
this.mRoutingThreadPool.scheduleWithFixedDelay(clientServiceThread, 0, 100, TimeUnit.MILLISECONDS);
}
public URI getServerAddress() {
return serverAddress;
}
public void setServerAddress(URI testServer) {
startRunning();
this.serverAddress = testServer;
this.mRoutingThreadPool.remove(serverServiceThread);
this.mRoutingThreadPool.scheduleWithFixedDelay(serverServiceThread, 0, 100, TimeUnit.MILLISECONDS);
}
public void startRunning() {
running = true;
}
public void stopRunning() {
running = false;
}
#Override
public void onCreate() {
super.onCreate();
serverQueue = new PriorityBlockingQueue<>();
clientQueue = new PriorityBlockingQueue<>();
}
#Override
public void onDestroy() {
stopRunning();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
clientAddress = URI.create("127.0.0.1:8054");
serverAddress = URI.create("192.168.2.1:7087");
startRunning();
setClientAddress(clientAddress);
setServerAddress(serverAddress);
return Service.START_STICKY;
}
public class RoutingBinder extends Binder {
public routing getService() {
return routing.this;
}
}
class ClientService extends Thread {
private Socket socket;
private Runnable ClientReader = new Runnable() {
#Override
public void run() {
if (socket != null && socket.isConnected()) {
try (InputStreamReader sr = new InputStreamReader(socket.getInputStream())) {
StringBuilder xml = new StringBuilder();
char[] buffer = new char[8192];
String content = "";
int read;
while ((read = sr.read(buffer, 0, buffer.length)) != -1) {
serverQueue.add(new String(buffer));
}
} catch (IOException e) {
Log.e("clientReader", "Error in testReading Thread.", e);
}
}
}
};
private Runnable ClientWriter = new Runnable() {
#Override
public void run() {
if (socket != null && socket.isConnected()) {
while (serverQueue != null && !serverQueue.isEmpty()) {
try (OutputStream os = socket.getOutputStream()) {
String xml = serverQueue.poll();
os.write(xml.getBytes());
os.flush();
} catch (IOException e) {
Log.e("clientWriter", "Error in testReading Thread.", e);
}
}
}
}
};
#Override
public void run() {
try (ServerSocket server = new ServerSocket(clientAddress.getPort())) {
try (Socket socket = server.accept()) {
socket.setSoTimeout(0);
Log.d("SOCKET", String.format("Local Port: %s. Remote Port: %s", socket.getLocalPort(), socket.getPort()));
this.socket = socket;
//Make the Threads
Thread reader = new Thread(ClientReader);
Thread writer = new Thread(ClientWriter);
//Start the Threads
reader.start();
writer.start();
//Start the Server
startRunning();
//Join on the Threads so this driver thread will wait until they finish.
reader.join();
writer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
stopRunning();
}
}
class ServerService extends Thread {
private Socket socket;
private Runnable ServerReader = new Runnable() {
#Override
public void run() {
if (socket != null && !socket.isClosed()) {
try (InputStreamReader sr = new InputStreamReader(socket.getInputStream())) {
StringBuilder xml = new StringBuilder();
char[] buffer = new char[8192];
String content = "";
int read;
while ((read = sr.read(buffer, 0, buffer.length)) != -1) {
clientQueue.add(new String(buffer));
}
} catch (IOException e) {
Log.e("ServerReader", "Error in testReading Thread.", e);
}
}
}
};
private Runnable ServerWriter = new Runnable() {
#Override
public void run() {
if (socket != null && socket.isConnected()) {
try (OutputStream os = socket.getOutputStream()) {
while (clientQueue != null && !clientQueue.isEmpty()) {
String xml = clientQueue.poll();
os.write(xml.getBytes());
os.flush();
}
} catch (IOException e) {
Log.e("ServerWriter", "Error in testReading Thread.", e);
}
}
}
};
#Override
public void run() {
if (running) { //Service will keep spinning unti the testService ends the loop
try (Socket socket = new Socket(serverAddress.getHost(), serverAddress.getPort())) {
socket.setSoTimeout(0);
Log.d("SOCKET", String.format("Local test Port: %s. Remote test Port: %s", socket.getLocalPort(), socket.getPort()));
this.socket = socket;
//Make the Threads
final Thread writer = new Thread(ServerWriter);
final Thread reader = new Thread(ServerReader);
//Start the Threads
writer.start();
reader.start();
//Join on the Threads so this driver thread will wait until they finish.
writer.join();
reader.join();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Closing the input or output stream of a socket closes the other stream and the socket.
I'm trying to make an app reading a string coming from a socket connection, but after a few hours the app stops talking (without exceptions). I'm sure the app is still running because the server sending the string continues to detect the response echo after sending it.
public class MainActivity extends AppCompatActivity {
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ITALY);
}
}
});
Thread socketT = new Thread(new SocketThread());
socketT.start();
}
#Override
public void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
private class SocketThread extends Thread {
static final int socketPort = 3333;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(socketPort);
try {
while(true) {
Socket clientSocket = serverSocket.accept();
try {
new ServerThread(clientSocket);
} catch(IOException e) {
clientSocket.close();
} }
}
catch (IOException e) {
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread extends Thread {
private int counter = 0;
private int id = ++counter;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServerThread(Socket s) throws IOException {
socket = s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
out = new PrintWriter(new BufferedWriter(osw), true);
start();
}
public void run() {
try {
while (true) {
String str = in.readLine();
textToSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
} catch (IOException e) {}
try {
socket.close();
} catch(IOException e) {}
}
}
}
}
TextToSpeech instance will be available after connect to system service, not after invoke constructor.
So, your plan need to edit like this:
Call TextToSpeech constructor.
Check your TextToSpeech instance is finish to connect to system service through TextToSpeech.OnInitListener.onInit().
Then, connect to your custom service.
Try this as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
int res = textToSpeech.setLanguage(Locale.ITALY);
if (res >= TextToSpeech.LANG_AVAILABLE) {
// TextToSpeech instance is available after connect to system service!
Thread socketT = new Thread(new SocketThread());
socketT.start();
}
}
}
});
// At this time, your TextToSpeech instance may be not available yet.
//Thread socketT = new Thread(new SocketThread());
//socketT.start();
}
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