i am trying to send any text or image/audio file over bluetooth using RFCOM server socket.i used the following code
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkBTPermissions();
// byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
// mBluetoothConnection.write(bytes);
file_permission();
// byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
File myfile = new File("/sdcard/bluetooth/tom.txt");
byte[] bytes= new byte[(int)myfile.length()];
Log.d(TAG,"file length() =" + (int)myfile.length());
try {
FileInputStream fis = new FileInputStream(myfile);
BufferedInputStream bis = new BufferedInputStream(fis,(int)myfile.length());
//bis.read(bytes,0,bytes.length);
Log.d(TAG,"fis created");
// FileInputStream
mBluetoothConnection.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
here i am able to send the contents of my text file and even able to receive.
receiver code:
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
My question how i can send my file as a whole to the receiver and receive it and save it ?.Among various tutorials i only find how to send text over bluetooth. please help.
Related
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 2 years ago.
I am making an app with socket in which i want to share data from two devices in the same wifi. With my code i can share the file successfully between two devices with the exact size of the file and saves into the device storage with a specific name but when i try to open it fails to open in the file manager. I have tried this with mp4 file and apk files
Here is the sender's code
#Override
public void run() {
//File file = new File(src);
File file = new File(Environment.getExternalStorageDirectory() + "/c.mp4");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("anything");
dos.writeLong(bytes.length);
int read;
while ((read = dis.read(bytes)) != -1){
dos.write(bytes,0,read);
}
//os.write(bytes, 0, bytes.length); //commented
//os.flush(); //commented
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, sentMsg, Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And here is the receiver
#Override
public void run() {
Socket socket = null;
int bytesRead;
InputStream in; //changed
int bufferSize=0;
try {
socket = new Socket(dstAddress, dstPort);
bufferSize = socket.getReceiveBufferSize();
in = socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
File file = new File(Environment.getExternalStorageDirectory(), "c.mp4");
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = clientData.read(buffer)) != -1){
output.write(buffer, 0 , read);
}
//bos.close(); //commented
socket.close();
MainActivity2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity2.this, "Finished", Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity2.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to read the clientData (DataInputStream) in the same way you write it to the output stream of the socket.
uft-8 string,
long value,
seq. of bytes
Your mp4 file content will prefixed with "anything" and length. so it will be considered as corrupted file.
save the file without ("anything" and length)
I am using socket to send image from server to multiple client but after sending one image to every client again when i try to send another image it say socket is close but i didn't even close the socket as well.
So i want to keep my server and client socket is alive until the activity is visible.
I am using service to run socket server after that i am getting all socket list to activity so below is my code for server side
if (mSocketArraylist != null) {
for (int i = 0; i < mSocketArraylist.size(); i++) {
Socket mSocket = mSocketArraylist.get(i);
try {
DataOutputStream out = new DataOutputStream(mSocket.getOutputStream());
ContentResolver cr = mContext.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(data.getData().toString()));
} catch (FileNotFoundException e) {
Log.d(TAG, e.toString());
}
copyFile(is, out);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.e("Socket value", "Socket is null");
}
For client also i am using service below its implementation
class clientThread implements Runnable {
#Override
public void run() {
if (wifiInfo != null) {
if (!wifiInfo.isGroupOwner) {
String host = wifiInfo.groupOwnerAddress.getHostAddress();
Socket clientSocket = new Socket();
OutputStream os = null;
try {
clientSocket.bind(null);
clientSocket.setKeepAlive(true);
clientSocket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
os = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ SocketClientService.this.getPackageName() + "/VR-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
while (true) {
Log.d(TAG, "server: copying files " + f.toString());
InputStream inputstream = clientSocket.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
break;
}
signalActivity(f.getAbsolutePath());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
} else {
Log.e(TAG, "This device is a group owner, therefore the IP address of the " +
"target device cannot be determined. File transfer cannot continue");
}
}
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[8192 * 8192];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
} catch (IOException e) {
Log.d(TAG, e.toString());
return false;
}
return true;
}
So any one can help me out in this , help would be appreciated.
signalActivity method implementation
public void signalActivity(String message) {
Bundle b = new Bundle();
b.putString("message", message);
clientResult.send(port, b);
}
I want to add a feature to my app in which the users can upload files (PDF files) from their mobile to the database, then download this file back to the app and display it.
I have no idea how to start doing this and what is the right code to use.
I tried using this code,
ParseObject pObject = new ParseObject("ExampleObject");
pObject.put("myNumber", number);
pObject.put("myString", name);
pObject.saveInBackground(); // asynchronous, no callback
- EDIT -
I tried this code but the app crashes when I click the button:
public class Test extends Activity {
Button btn;
File PDFFile;
ParseObject po;
String userPDFFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
po = new ParseObject("pdfFilesUser");
btn = (Button) findViewById(R.id.button);
PDFFile = new File("res/raw/test.pdf");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadPDFToParse(PDFFile, po, userPDFFile);
}
});
}
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
}
You can upload a file manually via REST API. Take a look at this docs here
Can try this code:
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
For more details check this
I would strongly suggest you quickly get up to speed with the Parse Java development wiki.
To answer your question. You want to be using:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground();
First declare your file etc then save it using that. But once again, first read the guidelines to better understand the framework you working with.
https://parseplatform.github.io/docs/android/guide/
I'm downloading a file that is stored on a remote server, I try to decrypt it using JNCryptor, and all goes well except that the file I have downloaded and store in the phone external storage is corrupted and I cannot open it. Can anyone tell me where im going wrong?
Im trying to get the InputStream from the file, decrypt it, and save the file on external storage.
Thanks
Here is my code:
private void downloadFile() {
final String FILE_URL = "https://www.google.com";
final String PASS = "password";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
Log.d(TAG, "starting");
JNCryptor cryptor = new AES256JNCryptor();
int count;
try {
URL url = new URL(FILE_URL);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
//decrypt istream
byte[] b = null;
byte[] data = null;
try {
b = new byte[input.available()];
input.read(b);
} catch (IOException e) {
Log.i("decrypt error", e.toString());
}
AES256JNCryptorOutputStream cryptorStream = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
cryptorStream = new AES256JNCryptorOutputStream(byteStream,
PASS.toCharArray());
} catch (CryptorException e) {
e.printStackTrace();
}
try {
cryptorStream.write(b);
cryptorStream.flush();
cryptorStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] encrypted = byteStream.toByteArray();
try {
data = cryptor.decryptData(encrypted, PASS.toCharArray());
Log.d(TAG, "decrypted");
} catch (InvalidHMACException e) {
e.printStackTrace();
} catch (CryptorException e) {
e.printStackTrace();
}
if (data != null) {
Log.d(TAG, "data is ok");
}
//end decryption
// Output stream
//test
FileOutputStream fos = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/temp.zip");
fos.write(data);
fos.close();
Log.d(TAG, "file saved ");
input.close();
Log.d(TAG, "done");
} catch (Exception e) {
Log.d(TAG, "Error: " + e.getMessage());
}
return null;
}
}.execute();
}
P.S. Im not getting any error or warning in logCat.
following is my code,
From Activity class
Intent intent = new Intent(this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.abc.ezy.asia/E-MobApps/op.apk"));
intent.putExtra("urlpath", "http://www.abc.ezy.asia/E-MobApps/op.apk");
startService(intent);
I have overrided Service Class method onHandle Event
// DownloadService Class
#Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
fos = new FileOutputStream(output.getPath());
byte dataB[] = new byte[1024];
InputStreamReader reader = new InputStreamReader(stream);
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
fos.flush();
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}
In above code I used File Streams & Input stream reader for downloading
when tried to download html file then complete file was downloaded to my sdcard.But when I tried for APK. The File downloaded of 2.2 mb instead of 2.4 mb Parsing problem is there. Kindly help me to resolve the issue.
try this piece of code :
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(output.getPath());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
input.close();
result = Activity.RESULT_OK;