Sensor Thread and Handler Thread Problems - android

I'm working on an app for a Sony Smarthwatch 3.
It records audio and sensor values after a command from another device that is connected by Bluetooth.
I try to be more clear.
The problems
The Handler doesn't update the associated TextView (also the Button isn't set properly). The handler attached to "log" TextView just update the view in the end of execution with the last text sent.
The sensor doesn't update the field as required. The sensors and related listeners are poperly instantiated but i can't save the values associated to events they are ispecting. The string where i should save the values will never been changed, it's like listeners never find related events. I've already tested sensors on this device and they work normally.
The chronometer doesn't work. Thenever start his count. it's not realy important but i wonna understand why. I'm thinking about some issue related to threads but i don't know how manage it.
The main code
public class MainActivity extends Activity implements OnRequestPermissionsResultCallback{
//GUI Elements
Chronometer chrono;
TextView log;
Button button;
MyHandlerThread update;
Handler myHandler;
boolean ready;
//Bluetooth Connection
BluetoothAdapter adapter;
BluetoothServerSocket serverSocket;
BluetoothDevice clientDevice;
BluetoothSocket clientSocket;
final UUID id = UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00");
InputStream in;
/*Sensors*/
SensorManager manager;
Sensor acc, gyr, mag;
SensorEventListener accEvent, gyrEvent, magEvent;
/*Microphone*/
MediaRecorder medRec;
/*File Data*/
File data;
FileWriter writer;
long time;
Thread writing;
String accValues="", gyrValues="", magValues="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
//GUI Elements
chrono = (Chronometer)findViewById(R.id.chrono);
log = (TextView) findViewById(R.id.logger);
button = (Button) findViewById(R.id.start);
myHandler= new MyHandler();
update = new MyHandlerThread(myHandler);
update.start();
ready=true;
writing=null;
//Listner
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//flag di stato
//boolean ready = (button.getText().equals("Start"));
audioInit(); //Audio Init, defined below
fileInit(); //File Init, defined below
if(ready){
try {
bluetoothInit(); //Bluetooth Init, defined below
} catch (Exception e) {/**/}
if (!adapter.isEnabled()){
update.setMessage("please, Turn Bluetooth On");
}
else{
try {
update.setMessage("Waiting Device...");
bluetoothConnect();
if(clientSocket!=null && in != null) {
update.setMessage("Connected:\n"+ clientDevice.getName());
}
while(ready){
int cmd = in.read(); //1 = start, 0 = stop
if(cmd == 1){
update.setMessage("Should be Ready");
time=SystemClock.elapsedRealtime();
update.setMessage("Recording...");
button.setText("Stop");
try {
if(writing==null)
writing = new Thread(new Runnable() {
#Override
public void run() {
while(ready){
try {
stopSensor(); //Defined Below
writer.flush(); //Clear Stream
writer.append((SystemClock.elapsedRealtime()-time)+";"); //Writing Record in CSV
writer.append(accValues+gyrValues+magValues+"\n");
sensorInit(); //Sensor Init, defined Below
wait(250);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
sensorInit();
writing.start(); //Start Thread Reading/Writing for Sensor values
startRecord(); //Audio and Chrono Start
} catch (Exception e) {
e.printStackTrace();
}
}
else if (cmd==0){
//log.setText("Should be Stopped");
update.setMessage("Should be Stopped");
ready=false;
writing=null;
stopRecord();
update.setMessage("Stopped");
button.setText("Start");
}
}
} catch (Exception e) {
//log.setText("Bluetooth Problem");
update.setMessage("Bluetooth Problem");
}
}
}
}
}); //fine Listner
}
});
}
/*Handler for Log TextView*/
private class MyHandler extends Handler {
public MyHandler(){
super(Looper.getMainLooper());
}
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if(bundle.containsKey("refresh")) {
String value = bundle.getString("refresh");
log.setText(value);
}
}
}
/*Bluetooth Init*/
void bluetoothInit(){
try {
adapter = BluetoothAdapter.getDefaultAdapter();
serverSocket = adapter.listenUsingRfcommWithServiceRecord("TennisRecord",id);
clientSocket=null;
clientDevice=null;
in=null;
} catch (Exception e) {
e.printStackTrace();
}
}
/*Bluetooth Connection*/
void bluetoothConnect() throws IOException {
clientSocket = serverSocket.accept();
clientDevice = clientSocket.getRemoteDevice();
in=clientSocket.getInputStream();
}
/*Audio Init*/
void audioInit(){
medRec = new MediaRecorder();
medRec.setAudioSource(MediaRecorder.AudioSource.MIC);
medRec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
medRec.setOutputFile(Environment.getExternalStorageDirectory()+"/tennis_record.3gp");
medRec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
medRec.setAudioSamplingRate(44100);
medRec.setAudioChannels(1);
}
/*File Init*/
void fileInit(){
try {
data=new File(Environment.getExternalStorageDirectory(),"/data.csv");
writer = new FileWriter(data);
} catch (IOException e) {
e.printStackTrace();
}
}
/*Sensors Init*/
void sensorInit(){
manager = (SensorManager) getSystemService(SENSOR_SERVICE);
acc = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyr = manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mag = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
accEvent = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
accValues=event.values[0]+";"+event.values[1]+";"+event.values[2]+";";
log.setText((int) event.values[0]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
gyrEvent = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
gyrValues=event.values[0]+";"+event.values[1]+";"+event.values[2]+";";
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
magEvent = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
magValues=event.values[0]+";"+event.values[1]+";"+event.values[2]+";";
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
manager.registerListener(accEvent,acc,SensorManager.SENSOR_DELAY_NORMAL);
manager.registerListener(gyrEvent,gyr,SensorManager.SENSOR_DELAY_NORMAL);
manager.registerListener(magEvent,mag,SensorManager.SENSOR_DELAY_NORMAL);
}
/*Start Records*/
void startRecord() throws IOException {
/*Microfono*/
medRec.prepare();
medRec.start();
/*Cronometro*/
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
}
/*Close Record*/
void stopRecord(){
/*Microfono*/
medRec.stop();
medRec.release();
medRec=null;
/*Cronometro*/
chrono.setBase(SystemClock.elapsedRealtime());
chrono.stop();
/*File*/
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*Stop Senors*/
void stopSensor(){
/*Sensori*/
manager.unregisterListener(accEvent);
manager.unregisterListener(gyrEvent);
manager.unregisterListener(magEvent);
}
}
The Handler thread in another class
public class MyHandlerThread extends Thread {
private Handler handler;
Queue<String> text;
public MyHandlerThread(Handler handler) {
this.handler = handler;
text=new ArrayDeque<String>();
}
public void run() {
try {
while(true) {
if(!text.isEmpty()){
notifyMessage(text.remove());
Thread.sleep(1000);
}
}
}catch(Exception ex) {}
}
public void setMessage(String str){
text.add(str);
}
private void notifyMessage(String str) {
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("refresh", ""+str);
msg.setData(b);
handler.sendMessage(msg);
}
}
Any solutions?

Related

TextToSpeech stops working after a few hours

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();
}

Socket closing during lifecycle changes

I'm trying to keep a socket open during lifecycle changes in a headless fragment with setRetainInstance(true); in onCreate. However, when my app comes back the following exception occurs.
E/Client: Receiving thread loop error
java.net.SocketException: Socket closed
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:189)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:250)
at libcore.io.IoBridge.recvfrom(IoBridge.java:549)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:481)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
at java.io.InputStreamReader.read(InputStreamReader.java:233)
at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
at java.io.BufferedReader.readLine(BufferedReader.java:397)
at com.gm.popper_6.ConnectionFragment$Client$ReceivingThread.run(ConnectionFragment.java:183)
at java.lang.Thread.run(Thread.java:818)
Here's the code for the fragment
public class ConnectionFragment extends Fragment {
private InetAddress mGoAddress;
private int mGoPort;
private Client mClient;
private static final String TAG = "Connection";
private Server mServer;
private Socket mSocket;
private ConnectionFragmentListener listener;
private String mMessage;
public static ConnectionFragment newInstance(InetAddress address, int port){
Bundle bundle = new Bundle();
bundle.putSerializable("GoAddress", address);
bundle.putInt("GoPort", port);
ConnectionFragment fragment = new ConnectionFragment();
fragment.setArguments(bundle);
return fragment;
}
public interface ConnectionFragmentListener{
void onMessageRcvd(String message);
}
public void setConnectionFragmentListener(ConnectionFragmentListener listener){
this.listener = listener;
}
private void readBundle(Bundle bundle){
if (bundle != null){
mGoAddress = (InetAddress)bundle.getSerializable("GoAddress");
mGoPort = bundle.getInt("GoPort");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
readBundle(getArguments());
mGoAddress = (InetAddress) getArguments().getSerializable("GoAddress");
mGoPort = getArguments().getInt("GoPort");
mServer = new Server();
}
#Override
public void onStart() {
super.onStart();
}
// THE SERVER CLASS
private class Server{ //DECLARATION
ServerSocket mServerSocket = null;
Thread mThread = null;
public Server(){ //CONSTRUCTOR
mThread = new Thread(new ServerThread());
mThread.start();
}
public void tearDown(){
mThread.interrupt();
try {
mServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error closing server socket");
}
}
class ServerThread implements Runnable{
#Override
public void run() {
//REMOVE OR COMMENT OUT FOR FINAL
//android.os.Debug.waitForDebugger();
try {
mServerSocket = new ServerSocket(mGoPort, 50, mGoAddress);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()){
try {
mSocket = mServerSocket.accept();
Log.d(TAG, "Connected");
if (mClient == null){
mClient = new Client();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
}
//THE CLIENT CLASS
private class Client { //DECLARATION
private final String CLIENT_TAG = "Client";
private Thread mSendThread;
private Thread mRecThread;
public Client() { //CONSTRUCTOR
Log.d(CLIENT_TAG, "Creating Client");
mSendThread = new Thread(new SendingThread());
mSendThread.start();
}
class SendingThread implements Runnable { //an inner class of Client
BlockingQueue<String> mMessageQueue;
private int QUEUE_CAPACITY = 10;
public SendingThread() {
mMessageQueue = new ArrayBlockingQueue<String>(QUEUE_CAPACITY);
}
#Override
public void run() {
mRecThread = new Thread(new ReceivingThread());
mRecThread.start();
while (true){
try {
String msg = mMessageQueue.take();
sendMessage(msg);
} catch (InterruptedException e) {
Log.d(CLIENT_TAG, "Sending loop interrupted, exiting");
}
}
}
} //closes SendingThread, an inner class of Client
class ReceivingThread implements Runnable{ //an inner class of Client
#Override
public void run() {
BufferedReader input;
try {
//android.os.Debug.waitForDebugger();
input = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
while (!Thread.currentThread().isInterrupted()){
String messageStr = null;
messageStr = input.readLine(); //Line 183
if (messageStr!= null){
Log.d(CLIENT_TAG, "Read from the stream: " + messageStr);
mMessage = messageStr;
updateMessages(false);
}
else{
Log.d(CLIENT_TAG, "The null!!!");
}
}
input.close();
} catch (IOException e) {
Log.e(CLIENT_TAG, "Receiving thread loop error", e);
e.printStackTrace();
}
} //closes run method
} //closes ReceivingThread, an inner class of Client
public void tearDown(){ //a method of Client
try {
getSocket().close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String msg){ //a method of Client
try {
Socket socket = getSocket(); //should return mSocket
if (socket == null) {
Log.d(CLIENT_TAG, "Socket is null");
} else if (socket.getOutputStream() == null) {
Log.d(CLIENT_TAG, "Socket output stream in null");
}
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(getSocket().getOutputStream())), true);
out.println(msg);
out.flush();
mMessage = msg;
updateMessages(true);
} catch (UnknownHostException e){
Log.d(CLIENT_TAG, "Unkown host", e);
} catch (IOException e) {
Log.d(CLIENT_TAG, "I/O exception", e);
} catch (Exception e){
Log.d(CLIENT_TAG, "Error 3", e);
}
Log.d(CLIENT_TAG, "Message sent: " + msg);
} //closes sendMessage, a method of the inner Client class
} //closes Client class, an inner class of Connection
private Socket getSocket() {
return mSocket;
}
public synchronized void updateMessages(boolean local){
Log.i(TAG, "Updating message: " + mMessage);
if (local){
mMessage = "me: " + mMessage;
}
else{
mMessage = "them: " + mMessage;
}
if (listener!= null){
listener.onMessageRcvd(mMessage);
}
} //closes updateMessages
public void sendMessage(String msg){ //CALL FROM MAIN ACTIVITY
if(mClient != null){ //TO SEND A STRING MESSAGE
mClient.sendMessage(msg);
}
}
public void tearDown(){
mServer.tearDown();
mClient.tearDown();
}
#Override
public void onDestroy() {
tearDown();
super.onDestroy();
}
} //closes class declaration
And here's the main activity
public class MainActivity extends Activity implements ChannelListener, DeviceActionListener,
ConnectionInfoListener, ConnectionFragment.ConnectionFragmentListener{
//CLASS DECLARATIONS
public static final String TAG = "Popper";
private WifiP2pManager manager;
private Boolean isWifiP2pEnabled = false;
ArrayList<Target> mTargets = new ArrayList<Target>(0);
Target mTarget;
TextView rcvd;
TextView ip;
EditText mssg;
String goAddress = "";
InetAddress goInetAddress;
int prefixedPort;
//declare and initialize an intent filter
private final IntentFilter intentFilter = new IntentFilter();
//private final IntentFilter serverFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
private ConnectionInfoListener infoListener;
private Intent serverServiceIntent;
ConnectionFragment mConnection;
//????
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//register app w/p2p framework with call to initialize
//channel is my apps connection to the p2p framework
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
receiver = new P2pReceiver(manager, channel, this);
rcvd = (TextView)findViewById(R.id.rcvd);
rcvd.setMovementMethod(new ScrollingMovementMethod());
//initialize filter and setup to listen for the following broadcast intents
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
Resources res = getResources();
prefixedPort = res.getInteger(R.integer.GOport);
}
#Override
public void onMessageRcvd(String message) {
addLine(message);
}
#Override
protected void onResume() {
super.onResume();
receiver = new P2pReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_items, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.atn_direct_discover:
if (!isWifiP2pEnabled) {
NotificationToast.showToast(MainActivity.this, "Enable P2P!!!");
return true;
}
final TargetListFragment fragment = (TargetListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
NotificationToast.showToast(MainActivity.this, "Discovery initiated");
}
#Override
public void onFailure(int reason) {
NotificationToast.showToast(MainActivity.this, "Discovery failed");
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override //this is associated with ChannelListener
public void onChannelDisconnected() { //removal causes error.
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
goAddress = info.groupOwnerAddress.getHostAddress(); //this returns a string rep of add.
goInetAddress = info.groupOwnerAddress; //this returns actual inet add.
ip = (TextView) findViewById(R.id.ip);
mssg = (EditText) findViewById(R.id.mssg);
ip.setText(goAddress + ":" + "8080"); //display GO address and IP
startConnectionFragment();
}
//this override method is triggered by TargetListFragment's DeviceActionListener
#Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
//maybe use this to gray out and disable the listview object that connected
}
#Override
public void onFailure(int reason) {
}
});}
public void startConnectionFragment(){
mConnection = ConnectionFragment.newInstance(goInetAddress, prefixedPort);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(mConnection, "TAG_1");
ft.commit();
mConnection.setConnectionFragmentListener(this);
}
public void addLine(String line){
final String msg = line;
runOnUiThread(new Runnable(){
#Override
public void run() {
rcvd.append("\n" + msg);
}
});
}
#Override
public void onTargetListClick(Target target) {
mTarget = target;
}
public void stopServer() {
if(serverServiceIntent != null)
{
stopService(serverServiceIntent);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mConnection != null){
//mConnection.tearDown();
}
stopServer();
}
public void SendMessage(View v){
EditText txt = (EditText) this.findViewById(R.id.mssg);
String str = txt.getText().toString();
mConnection.sendMessage(str);
txt.getText().clear();
}
}
Could this have something to do with detaching when the app goes on pause or stop and not re-attaching when it comes back to life? Are there other things I should be considering?
Ultimately the app needs to keep communication open to about 5 or 6 devices over p2p. if there is a better strategy I'm open to suggestions. Thanks.
Update - So I've confirmed that both the onDestroy and onDetach methods of the fragment are firing when the main activity goes onStop. Since I have a method to close the sockets on death of the fragment they are getting closed. The big question now is how to keep the fragment alive?
You should maybe create a helper class that will open/close sockets on behalf of other classes, such as that fragment, that helper class won't be subjected to any life cycle events, and can be kept running as long as the Application process is alive

Calling non static method in Activity from another Activity

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

Android:How to make all activity can use socket connections

I had to establish a socket in ActivityA in normal and ready to send data,
but now I want to also be able to use the same socket connection to transmit the data in ActivityB.I have looked for information on the Internet, it seems can use the singleton.I studied for a few days, I still don't know how to start, even find some examples of exercises too, but still do not know how to use my original program.
I want to first establish between ActivityA and SERVER connection, and to pass a value to the SERVER, then press the button to switch to ActivityB, and also transmit values to SERVER
Give me some advice or teaching sites can be, so that I can continue to study it, thank you very much
Establish socket methods:
public class MainActivity extends Activity {
Button Btn_Wifi,Btn_Power,Btn_Flame;
Boolean connected=false;
Boolean powerstatus=false;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null ;
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView();
setListensers();
setButtonStatus();
}
private void mainView(){
Btn_Wifi = (Button) findViewById(R.id.Btn_Wifi);
Btn_Power = (Button) findViewById(R.id.Btn_Power);
Btn_Flame = (Button) findViewById(R.id.Btn_Flame);
}
private void setListensers(){
Btn_Wifi.setOnClickListener(BtnWifiOnClickListener);
Btn_Power.setOnClickListener(BtnPowerOnClickListener);
Btn_Flame.setOnClickListener(BtnFlameOnClickListener);
}
private void setButtonStatus(){
Btn_Power.setEnabled(false);
Btn_Flame.setEnabled(false);
}
Button.OnClickListener BtnWifiOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!connected){
try {
socket = new Socket("IP", PORT);
dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
changeConnectionStatus(true);//change the connection status
}catch (UnknownHostException e) {
changeConnectionStatus(false);
}catch (IOException e) {
changeConnectionStatus(false);
}
}else{
try {//try to close the socket
socket.close();
changeConnectionStatus(false);//change the connection status
} catch (UnknownHostException e) {//catch and
changeConnectionStatus(false);
} catch (IOException e) {//catch and
changeConnectionStatus(false);
}
}
}
};
Button.OnClickListener BtnPowerOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!powerstatus){
try {
byte[] pon ={(byte) 0x10,(byte) 0x10};
dataOutputStream.write(pon);
dataOutputStream.flush();
PowerStatus(true);
}catch(Exception obj){
PowerStatus(false);
}
}else{
try {
byte[] poff ={(byte) 0x11,(byte) 0x11};
dataOutputStream.write(poff); //writeBytes(String str)
dataOutputStream.flush();
PowerStatus(false);
}catch(Exception obj){
PowerStatus(true);
}
PowerStatus(false);
}
}
};
Button.OnClickListener BtnFlameOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, FlameActivity.class);
startActivity(intent);
}
};
public void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
if(isConnected){//if connection established
Btn_Wifi.setText("CONNECTED");
Btn_Power.setEnabled(true);
}else{
Btn_Wifi.setText("NOT WIFI");
Btn_Power.setText("POWER OFF");
Btn_Power.setEnabled(false);
PowerStatus(false);
}
}
public void PowerStatus(Boolean isPowerOn) {
powerstatus=isPowerOn;//change variable
if(isPowerOn){//if connection established
Btn_Power.setText("POWER ON");
Btn_Flame.setText("SET FLAME");
Btn_Flame.setEnabled(true);
}else{
Btn_Power.setText("POWER OFF");
Btn_Flame.setText("CANT SET FLAME");
Btn_Flame.setEnabled(false);
}
}
}
You can certainly use it by declaring,i.e: in MainActivity which creates socket connection,static YourSocketClass objSocket // which creates connection and to use it in another Activity just called it as follow i.e:MainActivity.objSocket.yourMethod(any_param). by declaring static you can access it.
public static CommunicationClient objCommunicationClient;
public boolean setConnection(final String ipAddress, final Context context,
final boolean isFromSearch) {
class EstablishConnection extends AsyncTask<Void, Void, Boolean> {
ProgressDialog objDialog;
#Override
protected void onPreExecute() {
objDialog = new ProgressDialog(context);
objDialog.setMessage(context.getResources().getString(
R.string.strConnecting));
objDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
objDialog.show();
objDialog.setCancelable(false);
objDialog.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean isConnected = false;
boolean isValid = false;
StrictMode.setThreadPolicy(policy);
objCommunicationClient = new CommunicationClient(ipAddress);
isSocketInitiated = objCommunicationClient.initSocket();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
CommonUtils.SSID = info.getSSID();
if (!isSocketInitiated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.strCantConnect),
Toast.LENGTH_LONG).show();
}
});
} else {
isConnected = true;
if (!isFromSearch) {
CommonUtils.IP = ipAddress;
try {
objCommunicationClient.sendRequest(context,
"<APP_SPECIFIC>");
} catch (Exception e) {
e.printStackTrace();
}
} else {
isValid = isFromSearch;
}
if (isValid) {
final Intent objIntentToGraph = new Intent(context,
GraphDataActivity.class);
objIntentToGraph
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(objIntentToGraph);
overridePendingTransition(
R.anim.slide_in_right,
R.anim.slide_out_left);
finish();
}
});
}
}
return isConnected;
}
#Override
protected void onPostExecute(Boolean result) {
try {
objDialog.cancel();
} catch (Exception err) {
err.printStackTrace();
}
super.onPostExecute(result);
}
}
boolean status = false;
try {
status = new EstablishConnection().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return status;
}
}
// and in my other Activity i called it as
MainActivity_HomePage.objCommunicationClient.sendRequest(
context, CommonUtils.STOP_COMMAND); //send request is method which send message to server.

Discovering local server connection via LAN using Android

I am trying to discover local server(apache tomcat) running on http://localhost:8080 through my android device.To achieve that i thought of using jmdns library from heere
but i am really confused about how to proceed with as i don't understand the networking much.
here is the codei have written with little googling but any help would a be a great help.
public class DnssdDiscovery extends Activity {
protected static final String TAG = DnssdDiscovery.class.getSimpleName();
android.net.wifi.WifiManager.MulticastLock lock;
android.os.Handler handler = new android.os.Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);
} /** Called when the activity is first created. */
// private String type = "_workstation._tcp.local.";_http._tcp.local.
private String type = "_http._tcp.local.";
private JmDNS jmdns = null;
private ServiceListener listener = null;
private ServiceInfo serviceInfo;
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
InetAddress Address = InetAddress.getLocalHost();
Log.e("Local :", Address.getHostName());
jmdns = JmDNS.create(Address);
jmdns.addServiceListener(type, listener = new ServiceListener() {
#Override
public void serviceResolved(ServiceEvent ev) {
notifyUser("Service resolved: " + ev.getInfo().getQualifiedName() + " port:" + ev.getInfo().getPort());
}
#Override
public void serviceRemoved(ServiceEvent ev) {
notifyUser("Service removed: " + ev.getName());
}
#Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_http._tcp.local.", "AndroidTest", 8080, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
private void notifyUser(final String msg) {
handler.postDelayed(new Runnable() {
public void run() {
TextView t = (TextView)findViewById(R.id.text);
t.setText(msg+"\n=== "+t.getText());
}
}, 1);
}
#Override
protected void onStart() {
super.onStart();
//new Thread(){public void run() {setUp();}}.start();
}
#Override
protected void onStop() {
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
//repo.stop();
//s.stop();
lock.release();
super.onStop();
}
}

Categories

Resources