I am trying to sending and receiving image to display in ImageView using Server-socket, I want to decrypt image using server-socket but its not working.
Image url like this :
http://localhost:4545/sdcard0/emulated/test.img;
Service :
public class ImageDecrptService extends Service {
private ServerSocket serverSocket;
private Socket socket;
void acceptRequestNDecryptFile() {
try {
try {
serverSocket = new ServerSocket(4545);
} catch (Exception e) {
}
while (true) {
Log.e("", "thread called true");
socket = serverSocket.accept();
//some thing code
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
acceptRequestNDecryptFile();
Log.e("", "thread called ");
} catch (Exception e) {
e.printStackTrace();
}
}
});
#Override
public void onCreate() {
super.onCreate();
try {
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
How can pass image url to server socket?
Note : I do not want use Bitmap to display image.
If you have a http url of an image on a webserver then you would need a client to grab the image.
So your ServerSocket is of no use.
Also a client-Socket would not be the right way to go.
You need to use a http component or library to download the image.
Or invoke the DownloadManager.
Related
I have IntentService that need to wait in method a() for results of onReceive() of BroadcastReceiver().
For now i use lmao wait(5000)... so it's not too elegant
IntentService:
private boolean methodA() {
try {
synchronized (mLocalBroadcastReceiver) {
mLocalBroadcastReceiver.wait(3000);
}
} catch (InterruptedException e) {
Log.e(TAG,"error, thread interrupted");
e.printStackTrace();
}
if(CONSTANT == true){
return true;
else
return false;
}
BroadCastRecievier:
#Override
public void onReceive(Context context, Intent intent) {
CONSTANT = true //changes somehow between true/false
}
In other words: return value of methodA depends on results of onReceive(). How to synchronize two threads?
Finally i used thread like that:
private void waitForResponse() {
//wait for response
thread = new WaitForStatus();
thread.run();
try {
synchronized (thread) {
thread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class WaitForAppStatus implements Runnable {
#Override
public void run() {
while (true) {
if (CONSTANT != -1) {
break;
} else {
try {
wait(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Android file upload not working and not showing any error or any exception.
I want to add up some thing like check the internet connection when it is working only then it tries to upload the file and also want to add up one more thing that it makes a sync between server and application that this code will be called automatically after regular interval of time when the internet connection is working.
I have tried many jar files to upload the file and make an ftp connection but nothing works. jar file link http://www.jibble.org/files/simpleftp.jar
import org.jibble.simpleftp.SimpleFTP;
File file = new File("/sdcard/CreativeDroid/test.txt");
this way I am calling MyAsyncTask class to upload a txt file
new MyAsyncTask().execute(file.toString());
private class MyAsyncTask extends AsyncTask <String, Integer, Double> {
protected Double doInBackground(String... params) {
try {
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("www.creativetabs.co", 21, "username", "password");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
//ftp.cwd("web");
// Upload some files.
ftp.stor(new File(params[0]));
// Quit from the FTP server.
ftp.disconnect();
} catch (IOException e) {
Log.d("error", e.toString());
// TODO Auto-generated catch block
}
return null;
}
}
Try using ftp4j:
http://www.sauronsoftware.it/projects/ftp4j/
I have been using this since 3 years and it works flawless.
private int uploadFile() throws Exception {
long fileSize = 0;
boolean supported = ftp.isResumeSupported();
String fileName = getFileName(file_path);
String server_path = data.getServer_folder() + fileName;
try {
fileSize = ftp.fileSize(server_path);
} catch (Exception e) {
fileSize = 0;
}
if (fileSize == 0) {
ftp.upload(new java.io.File(file_path), new FTPDataTransferListener() {
#Override
public void transferred(int arg0) {
uploaded = uploaded + arg0;
Utilities.showDLog(Tag, "uploaded: " + uploaded);
}
#Override
public void started() {
Utilities.showDLog(Tag, "uplaod started");
}
#Override
public void failed() {
Utilities.showDLog(Tag, "upload failed");
disconnectFTP();
outputCode = FTPOutputCodes.FAILED;
}
#Override
public void completed() {
outputCode = FTPOutputCodes.SUCCESSFULLY_UPLOADED;
Utilities.showDLog(Tag, "upload completed");
}
#Override
public void aborted() {
outputCode = FTPOutputCodes.ABORTED;
disconnectFTP();
Utilities.showDLog(Tag, "upload aborted");
}
});
} else if (supported) { // resume file upload
ftp.upload(new java.io.File(file_path), fileSize, new FTPDataTransferListener() {
#Override
public void transferred(int arg0) {
Utilities.showDLog(Tag, "Resume data transfered: " + arg0);
}
#Override
public void started() {
Utilities.showDLog(Tag, "Resume started");
}
#Override
public void failed() {
outputCode = FTPOutputCodes.FAILED;
disconnectFTP();
Utilities.showDLog(Tag, "Resume failed");
}
#Override
public void completed() {
outputCode = FTPOutputCodes.SUCCESSFULLY_UPLOADED;
}
#Override
public void aborted() {
outputCode = FTPOutputCodes.ABORTED;
disconnectFTP();
Utilities.showDLog(Tag, "resume aborted");
}
});
}
return outputCode;
}
protected void disconnectFTP() {
try {
ftp.disconnect(true);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
e.printStackTrace();
} catch (FTPException e) {
e.printStackTrace();
}
}
I'm writing a library project for multiple APPs to use. And for some reason, I must make a function mutual exclusion for different APPs, so I need a cross-process lock. But as far as I know, in android APPs can only write to it's own file's directory in internal storage, and external storage is unreliable because some device don't have one. So file lock seems not applicable for me, so is there any other way to implement cross-process lock?
thanks~
If you do not want to (or you can not) use flock or fcntl, maybe you can use LocalServerSocket to implement a spinlock.
For example:
public class SocketLock {
public SocketLock(String name) {
mName = name;
}
public final synchronized void tryLock() throws IOException {
if (mServer == null) {
mServer = new LocalServerSocket(mName);
} else {
throw new IllegalStateException("tryLock but has locked");
}
}
public final synchronized boolean timedLock(int ms) {
long expiredTime = System.currentTimeMillis() + ms;
while (true) {
if (System.currentTimeMillis() > expiredTime) {
return false;
}
try {
try {
tryLock();
return true;
} catch (IOException e) {
// ignore the exception
}
Thread.sleep(10, 0);
} catch (InterruptedException e) {
continue;
}
}
}
public final synchronized void lock() {
while (true) {
try {
try {
tryLock();
return;
} catch (IOException e) {
// ignore the exception
}
Thread.sleep(10, 0);
} catch (InterruptedException e) {
continue;
}
}
}
public final synchronized void release() {
if (mServer != null) {
try {
mServer.close();
} catch (IOException e) {
// ignore the exception
}
}
}
private final String mName;
private LocalServerSocket mServer;
}
I'm trying to develop an Android application which transfers images from one device to another. The received image would then be shown on the ImageView inside my application. To achieve my task, I thought to send a byte array of the bitmap. I'm able to get the first image on the imageview. But, as soon as I click on the button to send another image the application fails to send the bitmap. It shows me an exception "java.io.IOException: Service fiscovery failed." To send any image successfully I need to restart my application on the receiving/remote device. Can anyone please suggest a solution to mu problem. The logcat has also been included below.
Code to establish the connection:
private class StartConnectionThread extends Thread{
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public StartConnectionThread(BluetoothDevice device){
BluetoothSocket tempBluetoothSocket=null;
bluetoothDevice=device;
try
{
System.out.println(uuid);
tempBluetoothSocket=device.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException ioException)
{
}
bluetoothSocket=tempBluetoothSocket;
}
#Override
public void run() {
// TODO Auto-generated method stub
bluetoothAdapter.cancelDiscovery();
try
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bluetoothSocket.connect();
}
catch(IOException ioException)
{
System.out.println("bluetoothSocketInThread failed");
try
{
bluetoothSocket.close();
}
catch(IOException cancelIOException)
{
}
return;
}
manageConnectedSocket(bluetoothSocket);
}
public void cancel()
{
try
{
bluetoothSocket.close();
}
catch(IOException ioException)
{
}
}
}
Code to accept the connection:
private class AcceptConnectionThread extends Thread
{
private final BluetoothServerSocket bluetoothServerSocket;
public AcceptConnectionThread() {
// TODO Auto-generated constructor stub
System.out.println("constructor");
BluetoothServerSocket tempBluetoothServerSocket=null;
try
{
tempBluetoothServerSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord("My Souvenirs", uuid);
}
catch(IOException ioException)
{
}
bluetoothServerSocket=tempBluetoothServerSocket;
}
#Override
public void run() {
// TODO Auto-generated method stub
BluetoothSocket bluetoothSocket=null;
while(true)
{
try
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(bluetoothServerSocket);
if(bluetoothServerSocket!=null)
{
bluetoothSocket=bluetoothServerSocket.accept();
}
System.out.println("accept");
}
catch(IOException ioException){
break;
}
if(bluetoothSocket!=null)
{
manageConnectedSocket(bluetoothSocket);
try {
bluetoothServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
public void cancel()
{
try{
bluetoothServerSocket.close();
}
catch(IOException ioException){
}
}
}
Code to manage the connection:
private class ManageConnectedDevicesThread extends Thread
{
private final BluetoothSocket connectedBluetoothSocket;
public ManageConnectedDevicesThread(BluetoothSocket socket) {
// TODO Auto-generated constructor stub
connectedBluetoothSocket=socket;
InputStream tempInputStream=null;
OutputStream tempOutputStream=null;
try
{
tempInputStream=socket.getInputStream();
tempOutputStream=socket.getOutputStream();
}
catch(IOException ioException)
{
}
inputStream=tempInputStream;
outputStream=tempOutputStream;
}
#Override
public void run() {
// TODO Auto-generated method stub
byte[] buffer=new byte[1024*8];
int bytes;
while(true)
{
try
{
bytes=inputStream.read(buffer);
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
System.out.println("handler");
}
catch(IOException ioException)
{
System.out.println("for handler:" +ioException);
break;
}
}
}
public void write(byte[] bytes)
{
try
{
outputStream.write(bytes);
}
catch(IOException ioException){
System.out.println("exception in wrie tatement of managing connections");
}
}
public void close()
{
try {
connectedBluetoothSocket.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}
Code to reset the connection:
void resetConnection()
{
if(inputStream!=null)
{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(outputStream!=null)
{
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(startConnectionThread!=null)
{
System.out.println("start wala active tha");
startConnectionThread.cancel();
}
if(acceptConnectionThread!=null)
{
System.out.println("accept wala active tha");
acceptConnectionThread.cancel();
}
if(manageConnectedDevicesThread!=null)
{
System.out.println("manage wala active tha");
manageConnectedDevicesThread.close();
}
}
}
code for handler is shown below:
private final Handler handler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
System.out.println("MESSAGE_READ");
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
byte[] b=readMessage.getBytes();
Bitmap bitmap1=BitmapFactory.decodeByteArray(readBuf, 0, readBuf.length);
imageView.setImageBitmap(bitmap1);
break;
}
};
The logcat shows the following:
01-25 14:49:31.800: D/dalvikvm(9451): Debugger has detached; object registry had 1 entries
01-25 14:49:38.380: V/BluetoothSocket.cpp(9451): initSocketNative
01-25 14:49:38.380: V/BluetoothSocket.cpp(9451): ...fd 40 created (RFCOMM, lm = 26)
01-25 14:49:38.380: V/BluetoothSocket.cpp(9451): initSocketFromFdNative
01-25 14:49:40.420: D/BluetoothUtils(9451): isSocketAllowedBySecurityPolicy start : device null
01-25 14:49:41.680: I/System.out(9451): bluetoothSocketInThread failed
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): abortNative
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): ...asocket_abort(40) complete
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): destroyNative
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): ...asocket_destroy(40) complete
Thanks in advance.
Maybe you can try adding thread.sleep for a second? See this discussion:
"The only way I've been able to fix the problem is by adding a
thread.sleep for a second before closing the connection."
also see dan's two consecutive comments on this thread:
"I was able to get this to run only after separating the calls to
findBT(); openBT();
Otherwise, mmSocket.connect(); throws an exception, “Service discovery
failed”
but if I put findBT() in onCreate() and just use the button for
openBT(); it works fine.
Or, if I make a second button, one for each, it works fine.
Suggestions?"
the excerpts from the second comment:
Set pairedDevices = mBluetoothAdapter.getBondedDevices();
mmDevice = mBluetoothAdapter.getRemoteDevice(“00:06:66:46:5A:91″);
if (pairedDevices.contains(mmDevice))
{
statusText.setText(“Bluetooth Device Found, address: ” + mmDevice.getAddress() );
Log.d(“ArduinoBT”, “BT is paired”);
}
where I entered the address of my Bluetooth device. The original code
finds the device and returns the correct address, but
mmSocket.connect(); generates an exception “java.io.IOException:
Service discovery failed”
Suggestions?
At first, my android device scans for bluetooth devices and then displays them in a listview. I select one of them and a new screen appears. How to return to the main screen when the connection is lost. Following is the code for selected device screen.
public class devicefound extends Activity implements OnClickListener {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button b1;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.b1).setOnClickListener(this);
b1 = (Button) findViewById(R.id.b1);
}
#Override
public void onStart() {
super.onStart();
String address = getIntent().getStringExtra("address");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
run();
}
public void run(){
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) { }
return;
}
}
public void onClick(View v){
String message1 = "1";
byte[] msgBuffer1 = message1.getBytes();
try{
outStream = btSocket.getOutputStream();
} catch (IOException e){ }
try {
outStream.write(msgBuffer1);
} catch (IOException e) {
}
}
}
#Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) { }
}
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
As I know you should use BroadcastReceiver in a such situation.
Something like this http://android-er.blogspot.com/2011/05/start-bluetooth-discoverable-and.html
If you want to return to the previous screen, then you can call the finish method which your devicefound class inherits from Activity.