The APP works in emulator but not in real phone - android

my APP is voice chat between server and client. client side works well. but server side doesn't work on real phone but in emulator.
it shows no error sometimes.
whats wrong with my code?
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD) #SuppressLint("NewApi") public class MainActivity extends Activity {
private Button receiveButton,stopButton;
private TextView receive_label;
private EditText port;
public static DatagramSocket socket;
private AudioTrack speaker;
private int port_num=50005;
//private int sampleRate =8000;//Integer.parseInt(audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
private int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int minBufSize=4096;
private boolean status = true;
#SuppressLint("NewApi") #TargetApi(Build.VERSION_CODES.GINGERBREAD) #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
receiveButton = (Button) findViewById (R.id.receive_button);
stopButton = (Button) findViewById (R.id.stop_button);
receive_label= (TextView) findViewById(R.id.receive_label);
receiveButton.setOnClickListener(receiveListener);
stopButton.setOnClickListener(stopListener);
port=(EditText) findViewById(R.id.editText1);
//AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// sampleRate =Integer.parseInt( audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
}
private final OnClickListener stopListener = new OnClickListener() {
#Override
public void onClick(View v) {
status = false;
speaker.release();
Log.d("VR","Speaker released");
}
};
private final OnClickListener receiveListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
status = true;
receive_label.setText("socket...1");
startReceiving();
}
};
public void startReceiving() {
Thread receiveThread = new Thread (new Runnable() {
#Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(50005);
Log.d("VR", "Socket Created");
byte[] buffer = new byte[1024];
for (int sampleRate : new int[] {8000, 11025, 16000, 22050,
32000, 37800, 44056, 44100}) { // add the rates you wish to check against
minBufSize = 4096;//AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
if (minBufSize != AudioRecord.ERROR_BAD_VALUE) {
speaker = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,channelConfig,audioFormat,minBufSize,AudioTrack.MODE_STREAM);
speaker.play();
}
}
//minimum buffer size. need to be careful. might cause problems. try setting manually if any problems faced
// int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
while(status == true) {
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
Log.d("VR", "Packet Received");
//reading content from packet
buffer=packet.getData();
Log.d("VR", "Packet data read into buffer");
//sending data to the Audiotrack obj i.e. speaker
speaker.write(buffer, 0, minBufSize);
Log.d("VR", "Writing buffer content to speaker");
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
receiveThread.start();
}}
give me your best help

you need to run both apps in same local network

Related

Send Video file from Android to Arduino

From the below code I can convert a image file to byte array in my mobile app.But I cannot Convert a video file since OutOfMemoryError exception comes. I want to send a video file to a arduino board. Since I can send a string from android app to arduino, I am trying to send a video file like that. But it fails. I there any other solution to solve my problem?please help.
Code for converting image to byte array
package com.example.krishan.detectusbplugin;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory() + "/Output/" +"My.mp4");
// convertFileToByteArray(file);
System.out.println(Arrays.toString(convertFileToByteArray(file)));
try {
System.out.write(convertFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}
Code for sending a string to arduino through usb cable
package com.hariharan.arduinousb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.hariharan.arduinousb.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView, "Serial Connection Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
Toast.makeText(getApplicationContext(), "SERIAL , PORT NOT OPEN", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PORT IS NULLPORT IS NULL");
Toast.makeText(getApplicationContext(), "SERIAL , PORT IS NULL", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
Toast.makeText(getApplicationContext(), "SERIAL , PERM NOT GRANTED", Toast.LENGTH_LONG).show();
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int devicePID = device.getProductId();
if (devicePID == 0x0043)//Arduino Product ID in Hexa
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
Toast.makeText(getApplicationContext(), "PID does not match", Toast.LENGTH_LONG).show();
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView, "\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}

Multicast Socket Android Error On Data Recieving?

I am new in socket programming. i am using Multicast socket for broadcasting through wifi hotspot network.But i am facing problem at the reciver side.
Here is my code
Server Side
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class SenderService extends Service
{
SenderThread currentSender;
public class SenderThread extends Thread
{
public void run()
{
Log.d("in thread","in service");
try
{
InetAddress group = InetAddress.getByName("224.0.0.3");
int port=10000;
DatagramSocket sock=new DatagramSocket();
sock.setBroadcast(true);
String msg="hello";
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
while (true)
{
try
{
packet = new DatagramPacket(b3, b3.length,group, port);
sock.send(packet);
Log.d("MSG:", "sent");
} catch (IOException e)
{
Log.d("Send Excp:", e+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
sock.close();
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new SenderThread().start();
return Service.START_STICKY;
}
}
Client Side Code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ReceiverActivity extends Activity
{
Button b;
Handler h;
class MyRTh extends Thread
{
InetAddress group=null ;
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("HelloAndroid");
public void run()
{
try
{
lock.acquire();
}
catch (Exception e) {
// TODO: handle exception
Log.d("lock",e+"");
}
try
{
final MulticastSocket sock=new MulticastSocket(10000);
group= InetAddress.getByName("224.0.0.3");
//sock.setSoTimeout(15000);
try
{
sock.joinGroup(group);
}
catch(Exception e)
{
Log.d("join",""+e.toString());
}
while(true)
{
try
{
Log.d("in try","l4");
byte[] data = new byte[1024];
// TODO Auto-generated method stub
DatagramPacket packet = new DatagramPacket(data, data.length);
Log.d("in run","l4");
try {
sock.receive(packet);
String s = new String(packet.getData());
Log.e("MSG:", "Received");
Log.d("msg",s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("err",e.toString());
}
}
catch (Exception e)
{
Log.d("Excp", e.toString()+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Toast.makeText(getApplicationContext(), "Receiving", Toast.LENGTH_SHORT).show();
Log.d("1","l1");
b=(Button)findViewById(R.id.buttonr);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
MyRTh th=new MyRTh();
th.start();
}
});
}
}
My problem is my client side code stuck when it goes to socket.receive() method. I started my mobile data at both sides. Started Hotspot at server side and connected to it from client.
My problem is my client side code stuck when it goes to socket.receive() method
It blocks.
InetAddress group = InetAddress.getByName("224.0.0.3");
The problem is here. Multicast addresses in the range 224.0.0.0 to 224.0.0.255 are reserved for low-level multicast support operations. Use an address in the range 224.0.1.0 to 239.255.255.255, but see also RFC 2365.
sock.setBroadcast(true);
Unnecessary. Remove. You aren't broadcasting, you are multicasting.
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
You don't need to initialize b3 when you reassign it two lines later.
finally
{
sock.close();
}
You are closing the socket inside the while (true) loop. So it will send one multicast and then exit with a 'socket closed' exception, which you haven't reported here. Remove.
String s = new String(packet.getData());
That should be new String(packet.getData(), packet.getOffset(), packet.getLength().
try to set able this enable socket.setBroadcast(true);
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.setBroadcast(true);
socket.receive(packet);

Streaming voice between server and client in android

I'm developing a voice chat between two android device. Client side works very well but server side is crashing.
I've changed sample rate array size but it's still crashing. As soon as client connects to server,server crashes.
client :
package com.example.client;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD) #SuppressLint("NewApi") public class MainActivity extends Activity {
private EditText target,target_port;
private TextView streamingLabel;
private Button startButton,stopButton;
public byte[] buffer;
public static DatagramSocket socket;
private int port=50005;
AudioRecord recorder;
//AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
private int sampleRate =8000;//Integer.parseInt(audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
private boolean status = true;
#SuppressLint("NewApi") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
target = (EditText) findViewById (R.id.target_IP);
streamingLabel = (TextView) findViewById(R.id.streaming_label);
startButton = (Button) findViewById (R.id.start_button);
stopButton = (Button) findViewById (R.id.stop_button);
target_port=(EditText) findViewById(R.id.target_Port);
streamingLabel.setText("Press Start! to begin");
startButton.setOnClickListener (startListener);
stopButton.setOnClickListener (stopListener);
target.setText("192.168.1.100");
target_port.setText("50005");
// AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// String rate = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
// String size = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
// Log.d("Buffer Size and sample rate", "Size :" + size + " & Rate: " + rate);
}
private final OnClickListener stopListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
status = false;
recorder.release();
Log.d("VS","Recorder released");
}
};
private final OnClickListener startListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
status = true;
startStreaming();
}
};
public void startStreaming() {
Thread streamThread = new Thread(new Runnable() {
#Override
public void run() {
try {
int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
DatagramSocket socket = new DatagramSocket();
Log.d("VS", "Socket Created");
byte[] buffer = new byte[512];
Log.d("VS","Buffer created of size " + minBufSize);
DatagramPacket packet;
final InetAddress destination = InetAddress.getByName(target.getText().toString());
Log.d("VS", "Address retrieved");
if (minBufSize != AudioRecord.ERROR_BAD_VALUE) {
recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT,sampleRate,channelConfig,audioFormat,minBufSize);
Log.d("VS", "Recorder initialized");
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
recorder.startRecording();}
while(status == true) {
//reading data from MIC into buffer
minBufSize = recorder.read(buffer, 0, buffer.length);
//encoding to base64
// String buffer1= Base64.encodeToString(buffer, Base64.DEFAULT);
//putting buffer in the packet
port=Integer.parseInt(target_port.getText().toString());
packet = new DatagramPacket (buffer,buffer.length,destination,port);
System.out.print(buffer);
Log.d("", "BUFERRRR");
socket.send(packet);
}
} catch(UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("IOException message:",e.getMessage().toString());
}
}
});
streamThread.start();
}
}
Server :
package com.example.server;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD) #SuppressLint("NewApi") public class MainActivity extends Activity {
private Button receiveButton,stopButton;
private TextView recive;
private EditText port;
public static DatagramSocket socket;
private AudioTrack speaker;
private int port_num=50005;
private int sampleRate =44100;//Integer.parseInt(audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
private int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int minBufSize =AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
byte[] buffer; //256
private boolean status = true;
#SuppressLint("NewApi") #TargetApi(Build.VERSION_CODES.GINGERBREAD) #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
receiveButton = (Button) findViewById (R.id.receive_button);
stopButton = (Button) findViewById (R.id.stop_button);
recive= (TextView) findViewById(R.id.receive_label);
receiveButton.setOnClickListener(receiveListener);
stopButton.setOnClickListener(stopListener);
port=(EditText) findViewById(R.id.editText1);
//AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// sampleRate =Integer.parseInt( audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
}
private final OnClickListener stopListener = new OnClickListener() {
#Override
public void onClick(View v) {
status = false;
speaker.release();
Log.d("VR","Speaker released");
}
};
private final OnClickListener receiveListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
status = true;
startReceiving();
}
};
public void startReceiving() {
Thread receiveThread = new Thread (new Runnable() {
#Override
public void run() {
buffer= new byte[1024];
DatagramSocket socket = null;
try {
socket = new DatagramSocket(50005);
Log.d("VR", "Socket Created");
if (minBufSize != AudioRecord.ERROR_BAD_VALUE) {
speaker = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,channelConfig,audioFormat,1024,AudioTrack.MODE_STREAM);
if (speaker.getState() == AudioRecord.STATE_INITIALIZED)
speaker.play();}
while(status == true) {
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
Log.d("VR", "Packet Received");
buffer=packet.getData();
Log.d("VR", "Packet data read into buffer");
buffer= Base64.decode(buffer, Base64.DEFAULT);
speaker.write(buffer, 0, minBufSize);
Log.d("VR", "Writing buffer content to speaker");
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
receiveThread.start();
}}
Please help me to resolve this.
cheek the while loop and the flag

Trying to import a sample project, but every import has the following error import name cannot be resolved

I'm trying to learn NFC and download the sample project at
http://www.framentos.com/en/android-tutorial/2012/07/31/write-hello-world-into-a-nfc-tag-with-a/
I selected import from the file menu then choose existing project into workspace and select the corresponding zip file.
The new project appeared in my eclipse workspace and all the files where there, but on the source file it had a error for every import saying import name cannot be resolved, example
import java.io cannot be resolved.
I have the source code below, but I'm assuming its some setting in eclipse?
package com.framentos.hellonfc;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint({ "ParserError", "ParserError" })
public class MainActivity extends Activity{
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
boolean writeMode;
Tag mytag;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ctx=this;
Button btnWrite = (Button) findViewById(R.id.button);
final TextView message = (TextView)findViewById(R.id.edit_message);
btnWrite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
try {
if(mytag==null){
Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG ).show();
}else{
write(message.getText().toString(),mytag);
Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
}
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.error_writing), Toast.LENGTH_LONG ).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(ctx, ctx.getString(R.string.error_writing) , Toast.LENGTH_LONG ).show();
e.printStackTrace();
}
}
});
adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };
}
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
// Get an instance of Ndef for the tag.
Ndef ndef = Ndef.get(tag);
// Enable I/O
ndef.connect();
// Write the message
ndef.writeNdefMessage(message);
// Close the connection
ndef.close();
}
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte[1 + langLength + textLength];
// set status byte (see NDEF spec for actual bits)
payload[0] = (byte) langLength;
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
#Override
protected void onNewIntent(Intent intent){
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this, this.getString(R.string.ok_detection) + mytag.toString(), Toast.LENGTH_LONG ).show();
}
}
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
private void WriteModeOn(){
writeMode = true;
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
private void WriteModeOff(){
writeMode = false;
adapter.disableForegroundDispatch(this);
}
}

Accessing functions inside a thread withing a service from an activity (socket communication)

i'm trying to get the communication between activities and a service to work.
i am pretty new to android and java, learned it my self through youtube :D, but cant find or solve this one.
at first i made an activity with a class thread which handles an ethernet socket. but i discovered when i leave the activity and switch to another the thread is destroyed. to preserve the thread i included the thread inside an service. but now i cant use the functions inside the thread (like sending/getting status). how can i get the instance of my ethernet class back to all of my activities. below i clipped my code.
the code works and run. but when i want to call my send() function or getConStatus() it crashed.
working on a client server communication for home domotics.
// my main activity
import java.io.IOException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
//UI declerations
Button button1, button2;
EditText text1,text2;
ProgressBar waiter;
Ethernets eth;
house house;
Toast message;
ProgressTask Task;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
text1 = (EditText)findViewById(R.id.editText1);
text2 = (EditText)findViewById(R.id.editText2);
waiter = (ProgressBar)findViewById(R.id.Waiter);
}
protected void onStop()
{
Intent intent = new Intent(this, Ethernet_Service.class);
stopService(intent);
}
public void start(View view)
{
eth.send("Turn ON"); // i cant USE this !!
}
public void connect(View view) throws UnknownHostException, IOException
{
String ip = null;
int port = 0;
ip = text1.getText().toString();
port = Integer.parseInt(text2.getText().toString());
Intent intent = new Intent(this, Ethernet_Service.class);
startService(intent);
}
}
// my service
package com.example.homeapp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class Ethernet_Service extends Service{
public Ethernet_Service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Ethernets eth = new Ethernets("I9001", "192.168.1.101", 4000);
eth.start();
return startid;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
// my ethernet thread class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import android.util.Log;
public class Ethernets extends Thread {
Thread ethernetThread, recieveThread;
Socket ethernetSocket;
PrintStream PW;
String IP;
int PORT;
boolean connect_status = false;
String Client_Name;
public Ethernets(String name, String ip, int port)
{
Client_Name = name;
PORT = port;
IP = ip;
}
public void run()
{
try
{
ethernetSocket = new Socket(IP,PORT);
if(ethernetSocket.isConnected() == true)
{
connect_status = true;
}
else{connect_status = false;}
PW = new PrintStream(ethernetSocket.getOutputStream(),true);
}catch(Exception ex){}
recieveThread = new Thread(new Runnable() {
#Override
public void run() {
String message;
try
{
BufferedReader BR = new BufferedReader(new InputStreamReader(ethernetSocket.getInputStream()));
while((message = BR.readLine()) != null)
{
System.out.println("message: "+message);
}
} catch (IOException e) {e.printStackTrace();}
}
});
recieveThread.start();
}
public void send(String msg)
{
//protocol description
byte[] buffer = {(byte) 0x02, (byte) 0x04, (byte) 'B', (byte) 0x02, 0x00, 0x00, (byte) 0x46 };
try
{
Log.i("hi","hi");
PW.write(buffer);
PW.flush();
} catch (IOException e) {e.printStackTrace();}
}
public boolean getconStatus()
{
return connect_status;
}
}

Categories

Resources