Android XMPP File Transfer - android

I'm newbie to Android programming. I'm trying to develop messenger application with file transfer feature. But having difficulties reagrding file transfer.
viewer.java**
Button transfer = (Button) findViewById(R.id.btnimage);
transfer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
XMPPClient.getInstance().SendFile(to, selectedImagePath);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and then i Have XMPPCLIENT.java
public void ReceiveFile() {
Thread thread = new Thread() {
public void run() {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(getConnection());
if (sdm == null)
sdm = new ServiceDiscoveryManager(getConnection());
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
final FileTransferManager managerListner = new FileTransferManager(
getConnection());
FileTransferNegotiator.setServiceEnabled(getConnection(), true);
Log.i("File transfere manager", "created");
// Create the listener
managerListner
.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(
final FileTransferRequest request) {
Log.i("Recieve File",
"new file transfere request new file transfere request new file transfere request");
Log.i("file request",
"from" + request.getRequestor());
IncomingFileTransfer transfer = request
.accept();
Log.i("Recieve File alert dialog", "accepted");
try {
transfer.recieveFile(new File("/sdcard/"
+ request.getFileName()));
while (!transfer.isDone()
|| (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Recieve File alert dialog",
"still receiving : "
+ (transfer
.getProgress())
+ " status "
+ transfer.getStatus());
if (transfer.getStatus().equals(
Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Recieve File alert dialog",
"cancelling still receiving : "
+ (transfer
.getProgress())
+ " status "
+ transfer
.getStatus());
transfer.cancel();
break;
}
}
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thread.start();
}
public void SendFile(final String Receiver, final String Directory) {
Thread thread = new Thread() {
public void run() {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(getConnection());
if (sdm == null)
sdm = new ServiceDiscoveryManager(getConnection());
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(
mConnection);
FileTransferNegotiator
.setServiceEnabled(getConnection(), true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager
.createOutgoingFileTransfer(getJIDofUserID(Receiver));
sendMessage(getJIDofUserID(Receiver), "image");
Log.i("transfere file", "outgoingfiletransfere is created");
try {
OutgoingFileTransfer.setResponseTimeout(30000);
transfer.sendFile(new File(Directory), "Description");
Log.i("transfere file", "sending file");
while (!transfer.isDone()) {
try {
Thread.sleep(1000);
Log.i("transfere file", "sending file status "
+ transfer.getStatus() + "progress: "
+ transfer.getProgress());
if (transfer.getStatus() == org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error) {
transfer.cancel();
Log.e("",transfer.getError()+" error");
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("aaaaaaaaaaaaaaa","aaaa"+e);
e.printStackTrace();
}
}
}
catch (XMPPException e) {
// TODO Auto-generated catch block
Log.e("aaaaaaaaaaaaaaa","aaaa"+e);
e.printStackTrace();
}
Log.i("transfere file", "sending file done");
}
};
thread.start();
}
So my questions are:
Is connection that i use is the same connection as chatting (default port: 5222)?
When I trigger sendfile(final String Receiver, final String Directory) function, when and how the receiver get any notification?

To answer your questions:
That depends on which method is used for file transfer. XMPP knows several. You can read more about it here https://github.com/igniterealtime/Smack/wiki/Smack-XMPP-File-Transfer and http://xmpp.org/xmpp-protocols/xmpp-extensions/
The receiving entity always has to confirm the file transfer first. But it depends on the other client how this is implemented e.g. if there is a pop-up windows saying that there is an incoming file transfer. It is also possible that the client on the other side is configured to auto-accept all requests.

First add following configuration in to your xmpp configuration class.
ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/bytestreams', new BytestreamsProvider());
2
ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#items', new DiscoverItemsProvider());
3
ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#info', new DiscoverInfoProvider());
Then add or edit following three properties in open fire server.
xmpp.proxy.enabled – true
xmpp.proxy.port – 7777
xmpp.proxy.externalip – [publicly accessible host or ip]
please make these changes and try again .

Related

Programmatically Downloading and Installing APK [duplicate]

This question already has answers here:
Android: install .apk programmatically [duplicate]
(4 answers)
Closed 5 years ago.
I've seen a few answers related to this but can't quite seem to find what I'm looking for. Say I have a self hosted app. Now say I've made some changes to that app and would like to let the user know within the app that there is an update available. I can get the app to successfully download the apk file and begin installing it. After the installation is "finished" the app closes out. When I restart the app none of the changes I've made have been applied. So it appears the installation has failed, but there was no apparent crash. However, when I install the apk that was downloaded from the Downloads manager it installs just fine and the changes I have made are applied. Any ideas? Here is the section of code I use to download and install programmatically:
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "TheApp.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
String url = "myapplocation";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading necessary update files.");
request.setTitle("Updating The App");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
startActivityForResult(install, 0);
unregisterReceiver(this);
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Get VersionName and VersionCode for current Running application.
code:
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
Common.VersionName = pInfo.versionName;
Common.VersionCode = pInfo.versionCode;
Log.e("VersionCode", ">>>>>>>>>>" + Common.VersionCode + Common.VersionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
**Check the Version Names**
if (!Common.VersionName.equals(Common.VersionNamefromWebApi)) {
AlertDialogUpdate(MakeTransactionActivity.this, Common.AppUpdateTitle, "YokoYepi Version" + Common.VersionNamefromWebApi + " available.");
}
**Alert Dialog Box**
public void AlertDialogUpdate(Activity activity, String title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setCancelable(false);
if (title != null) builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new DownloadNewVersion().execute();
dialog.dismiss();
}
});
builder.show();
}
**Download and Install the .apk file from URL**
class DownloadNewVersion extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar = new ProgressDialog(MakeTransactionActivity.this);
bar.setCancelable(false);
bar.setMessage("Downloading...");
bar.setIndeterminate(true);
bar.setCanceledOnTouchOutside(false);
bar.show();
stoptimertask();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
bar.setIndeterminate(false);
bar.setMax(100);
bar.setProgress(progress[0]);
String msg = "";
if (progress[0] > 99) {
msg = "Finishing... ";
} else {
msg = "Downloading... " + progress[0] + "%";
}
bar.setMessage(msg);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
startTimer();
bar.dismiss();
if (result) {
Toast.makeText(getApplicationContext(), "Update Done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error: Try Again",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected Boolean doInBackground(String... arg0) {
Boolean flag = false;
try {
String PATH;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
PATH = Environment.getExternalStorageDirectory() + "/Download/";
} else {
PATH = Environment.getDataDirectory() + "/Download/";
}
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yokoyepi.apk");
if (outputFile.exists()) {
outputFile.delete();
}
// Download File from url
URL u = new URL(Common.AppUpdateURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
// Install dowloaded Apk file from Devive----------------
OpenNewVersion(PATH);
flag = true;
} catch (MalformedURLException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (IOException e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
} catch (Exception e) {
Log.e(TAG, "Update Error: " + e.getMessage());
flag = false;
}
return flag;
}
}
void OpenNewVersion(String location) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(location + "yokoyepi.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
// if your not install u should call the function in onResume().
// again it will check whether apk updated or not.

android how to send and receive image and location (using map ) in group chat using xmpp-smack

i developing group chat app using android-xmpp, in that i don't know how to send and recive pics-image or location (using map).
So any one one can please give me way to do these.
currently , i got text message and add to list view , like following ,
Message msg = new Message(to, Message.Type.groupchat);
msg.setBody(text);
if (Constants.connection != null) {
try {
Constants.connection.sendPacket(msg);
Log.d("Send to room : Name : ", to);
Log.d("store", "store data to db");
//DBAdapter.addUserData(new UserData(text, "", "1" ,beam_id));
} catch (Exception e) {
Log.d("ooo", "msg exception" + e.getMessage());
}
messages.add(text);
runOnUiThread(new Runnable() {
public void run() {
// set to listview
setMyChatAdapter();
}
});
}
and receive using StanzaTypeFilter. So how for image and location sharing ?
I try following code for image using FileTransferManager , using smack-extensions-4.1.3-sources.jar .
private void sendImage()
{
FileTransferManager mg=new FileTransferManager(Constants.connection);
OutgoingFileTransfer transfer = mg.createOutgoingFileTransfer(beam_id+"#"+Constants.conference_name + "/" + Constants.resources);
File file = new File(selectedImagePath);
try {
transfer.sendFile(file, "test_file");
} catch (Exception e) {
e.printStackTrace();
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(FileTransfer.Status.error)) {
System.out.println("ERROR!!! " + transfer.getError());
} else if (transfer.getStatus().equals(FileTransfer.Status.cancelled)
|| transfer.getStatus().equals(FileTransfer.Status.refused)) {
System.out.println("Cancelled!!! "+ transfer.getError());
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(transfer.getStatus().equals(FileTransfer.Status.refused) || transfer.getStatus().equals(FileTransfer.Status.error)
|| transfer.getStatus().equals(FileTransfer.Status.cancelled)){
System.out.println("refused cancelled error"+ transfer.getError());
} else {
System.out.println("Success");
}
}
But when i access that file using following ,
FileTransferManager mg=new FileTransferManager(Constants.connection);
it give me error ... has a private access of ... So , i find constructor of that file is private , this is jar file so i can not change it to public .
So, how can i access that file-class into my class ?
So, how can i share(send-receive) image and location message in chat ?
Please help me as soon as possible.
Thanks in advance.
try this link: reference
For File send
FileTransferManager manager = new FileTransferManager(connection);
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer('usre2#myHost/Smack');
File file = new File(filenameWithPath);
try {
transfer.sendFile(file, 'test_file');
} catch (XMPPException e) {
e.printStackTrace();
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(Status.error)) {
System.out.println('ERROR!!! ' + transfer.getError());
} else if (transfer.getStatus().equals(Status.cancelled)
|| transfer.getStatus().equals(Status.refused)) {
System.out.println('Cancelled!!! ' + transfer.getError());
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
System.out.println('refused cancelled error ' + transfer.getError());
} else {
System.out.println('Success');
}
File Receive:
FileTransferManager manager = new FileTransferManager(connection);
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread(){
#Override
public void run() {
IncomingFileTransfer transfer = request.accept();
File mf = Environment.getExternalStorageDirectory();
File file = new File(mf.getAbsoluteFile()+'/DCIM/Camera/' + transfer.getFileName());
try{
transfer.recieveFile(file);
while(!transfer.isDone()) {
try{
Thread.sleep(1000L);
}catch (Exception e) {
Log.e('', e.getMessage());
}
if(transfer.getStatus().equals(Status.error)) {
Log.e('ERROR!!! ', transfer.getError() + '');
}
if(transfer.getException() != null) {
transfer.getException().printStackTrace();
}
}
}catch (Exception e) {
Log.e('', e.getMessage());
}
};
}.start();
}
});
The FileTransferManager class have getInstanceFor(XMPPConnection connection) to get the instance of the FileTransferManager. Just provide a valid XMPPConnecton. e.g.
FileTransferManager ftm = FileTransferManager.getInstanceFor(connection)
See this link FileTransferManager too.
Hope this helps you.

Error code 503 on transferring file using xmpp

I am trying to send an image file using smack and openfire xmpp. For this I am using FileTransferManager class. To use FileTransferManager class I am using asmack-android-6.jar. I followed this link to do file sharing. This issue is also shared in comments below on this tutorial but no good resolution is given to this issue. Then I searched over stack overflow, Many Developers have asked this question but only 1-2 have got replies that they have accepted, others not.
I studied all the answers that I found, tried all the ways that google gave me but still unable to solve this problem.
The code I used is:
d.findViewById(R.id.btnsendphoto).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!filepath.equals("")) {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null) {
sdm = new ServiceDiscoveryManager(
connection);
Log.e("service discovery", "SDM");
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
}
mFileTransferManager = new FileTransferManager(
connection);
/*
* OutgoingFileTransfer transfer =
* mFileTransferManager
* .createOutgoingFileTransfer
* ("98c6d889473a6fae#pc/Smack");
*/
String to = connection.getRoster()
.getPresence("98c6d889473a6fae#pc")
.getFrom();
OutgoingFileTransfer transfer = mFileTransferManager
.createOutgoingFileTransfer(to);
File file = new File(filepath);
try {
//[configureProviderManager](http://paste.ubuntu.com/9932239/)
configureProviderManager(connection);
transfer.sendFile(file, "test_file");
} catch (XMPPException e) {
e.printStackTrace();
}
while(!transfer.isDone()) {
Log.d("status", transfer.getStatus().toString());
Log.d("percent", new Long(transfer.getBytesSent()).toString());
if (transfer.getStatus() == Status.error) {
Log.e("percent", "Error " + new Long(transfer.getBytesSent()).toString() + " " + transfer.getError() + " " + transfer.getException());
transfer.cancel();
}
if(transfer.getStatus().equals(Status.refused))
System.out.println("refused " + transfer.getError());
else if( transfer.getStatus().equals(Status.error))
System.out.println(" error " + transfer.getError());
else if(transfer.getStatus().equals(Status.cancelled))
System.out.println(" cancelled " + transfer.getError());
else
System.out.println("Success");
}
}
d.dismiss();
}
});
The logcat I got is very big, so I gave link of that. So can anyone tell what mistake I am making or can suggest what amendment I make to achieve task
This problem got solved using this link answer don't know why its downvoted. Lemme share answer here also
d.findViewById(R.id.btnsendphoto).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!filepath.equals("")) {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null) {
sdm = new ServiceDiscoveryManager(
connection);
Log.e("service discovery", "SDM");
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
}
configureProviderManager(connection);
FileTransferNegotiator.IBB_ONLY = true;
FileTransferNegotiator.setServiceEnabled(connection, true);
mFileTransferManager = new FileTransferManager(
connection);
/*
* OutgoingFileTransfer transfer =
* mFileTransferManager
* .createOutgoingFileTransfer
* ("98c6d889473a6fae#pc/Smack");
*/
String to = connection.getRoster()
.getPresence("98c6d889473a6fae#pc")
.getFrom();
final OutgoingFileTransfer transfer = mFileTransferManager
.createOutgoingFileTransfer(to);
File file = new File(filepath);
try {
configureProviderManager(connection);
transfer.sendFile(file, "test_file");
} catch (XMPPException e) {
e.printStackTrace();
}
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
while (!transfer.isDone()) {
if (transfer.getStatus().equals("Error")) {
Log.d("file transfer",
"ERROR!!! " + transfer.getError());
} else if (transfer.getStatus().equals("Cancelled")
|| transfer.getStatus().equals("Refused")) {
Log.d("file transfer",
"Cancelled!!! " + transfer.getError());
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
};
protected void onPostExecute(Void result) {
if (transfer.getStatus().equals("Refused")
|| transfer.getStatus().equals("Error")
|| transfer.getStatus().equals("Cancelled")) {
Log.i("file transfer", "refused cancelled error "
+ transfer.getError());
} else {
Log.i("file transfer", "Success: " + transfer.getFileName());
}
};
}.execute();
}
d.dismiss();
}
});
I had same problem, I investigated the stanza and solved it this way.
Many people use "/Smack" or "/Resource" as resource part in jid, but it can be configured also the another way.
Resource path is changing with every presence changed of user. Lets say we want to send image to this user:
"user1#mydomain"
You must add "/Resource" part to this jid and it become this:
user1#mydomain/Resource
But /Resource path is changing with presence so you must follow every presence change to update resource path.
Best way is to get user presence is in roster listener and in presencheChanged() method you get last user resource part like this:
Roster roster=getRoster();
roster.addRosterListener(new RosterListener() {
#Override
public void entriesAdded(Collection<Jid> addresses) {
Log.d("entriesAdded", "ug");
context.sendBroadcast(new Intent("ENTRIES_ADDED"));
}
#Override
public void entriesUpdated(Collection<Jid> addresses) {
Log.d("entriesUpdated", "ug");
}
#Override
public void entriesDeleted(Collection<Jid> addresses) {
Log.d("entriesDeleted", "ug");
}
#Override
public void presenceChanged(Presence presence) {
Log.d("presenceChanged", "ug");
//Resource from presence
String resource = presence.getFrom().getResourceOrEmpty().toString();
//Update resource part for user in DB or preferences
//...
}
});
}
Resource string will be some generated string like "6u1613j3kv" and jid will become:
user1#mydomain/6u1613j3kv
That means that you must create your outgoing transfer like this:
EntityFullJid jid = JidCreate.entityFullFrom("user1#mydomain/6u1613j3kv");
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(jid)
transfer.sendFile(new File("DirectoryPath"), "Description");
And that is how i have solved my problem with file transfer on smack and Openfire.
In your case form jid like this:
String to = connection.getRoster().getPresence("98c6d889473a6fae#pc").getFrom();
String Resource = connection.getRoster().getPresence("98c6d889473a6fae#pc").getFrom().getResourceOrEmpty().toString();
OutgoingFileTransfer transfer = mFileTransferManager.createOutgoingFileTransfer(to + "/" + resource);
Also to mention you must add following properties in your Openfire server:
xmpp.proxy.enabled - true
xmpp.proxy.externalip - MY_IP_ADDRESS
xmpp.proxy.port - 7777
Just to mention, I am using Openfire 4.0.2 and Smack 4.2.2.
Also this can be configured the easy way, just set the resource on
XMPPTCPConnectionConfiguration.Builder .
like
XMPPTCPConnectionConfiguration.Builder configurationBuilder =
XMPPTCPConnectionConfiguration.builder();
configurationBuilder.setResource("yourResourceName");

How to receive files in Smack in Android?

How to receive transfered file using Smack with Openserver in Android? Here following is a code which I have used to receive a file. But getting error and can not rec any file.
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
if(sdm == null)
{
sdm = new ServiceDiscoveryManager(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("http://jabber.org/protocol/disco#item");
sdm.addFeature("jabber:iq:privacy");
XMPPConnection.DEBUG_ENABLED = true;
}
FileTransferManager manager=new FileTransferManager(connection);
FileTransferNegotiator.setServiceEnabled(connection, true);
manager.addFileTransferListener(new FileTransferListener()
{
#Override
public void fileTransferRequest(final FileTransferRequest request)
{
Log.i("Recieve File","new file transfere request new file transfere request new file transfere request");
Log.i("file request","from" + request.getRequestor());
// TODO Auto-generated method stub
new Thread()
{
#Override
public void run()
{
IncomingFileTransfer transfer = request.accept();
File mf = Environment.getExternalStorageDirectory();
File file = new File(mf.getAbsoluteFile()+"/DCIM/Camera/" + transfer.getFileName());
try
{
System.out.println("<====== Receives ======>");
transfer.recieveFile(file);
while (!transfer.isDone()|| (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Recieve File alert dialog","still receiving : "+ (transfer.getProgress()) + " status " + transfer.getStatus());
if (transfer.getStatus().equals("error")) {
Log.i("Recieve File alert dialog", "cancelling still receiving : "+ (transfer.getProgress())+ " status "+ transfer.getStatus());
transfer.cancel();
break;
}
}
}catch (Exception e){
Log.e("", e.getMessage());
}
}
}.start();
}
});
I got following error during sending a file.
02:48:58 PM RCV (1079277904): <iq type="error" id="6gQg0-6" to="admin-pc/cc4dd310" from="2222222222#admin-pc/Smack"><si xmlns="http://jabber.org/protocol/si" id="jsi_3030055238839806007" profile="http://jabber.org/protocol/si/profile/file-transfer"><file xmlns="http://jabber.org/protocol/si/profile/file-transfer" name="sdcard"><desc>test</desc></file><feature xmlns="http://jabber.org/protocol/feature-neg"><x xmlns="jabber:x:data" type="form"><field var="stream-method" type="list-single"><option><value>http://jabber.org/protocol/bytestreams</value></option><option><value>http://jabber.org/protocol/ibb</value></option></field></x></feature></si><error code="405" type="cancel"><not-allowed xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>
First off, you need to use version 3.1 or 3.3 as there is a known issue with 3.2. then check out this article or this one for guidance on coding the said transfer. Hope this helps.

android file transfer using smack

I am working on chatting application and i have to implement file transfer using smack api.
I am able to Connect to the open fire server and can also chat with another client.But i dont know how to implement file transfer..I have found a code snippet but i am not ableto send it using that also.Following is the code snippet i am using:
public void SendFile(final String Receiver, final String Directory) {
Thread thread = new Thread() {
public void run() {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null)
sdm = new ServiceDiscoveryManager(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(
connection);
FileTransferNegotiator
.setServiceEnabled(connection, true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager
.createOutgoingFileTransfer("alok#chd-akumar4" );
Log.i("transfere file", "outgoingfiletransfere is created");
try {
OutgoingFileTransfer.setResponseTimeout(30000);
transfer.sendFile(new File(Directory), "Description");
Log.i("transfere file", "sending file");
while (!transfer.isDone()) {
try {
Thread.sleep(1000);
Log.i("transfere file", "sending file status "
+ transfer.getStatus() + "progress: "
+ transfer.getProgress());
if (transfer.getStatus() == org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error) {
transfer.cancel();
Log.e("","EEEEEERRRRRRRROOORRRRR");
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("aaaaaaaaaaaaaaa","aaaa"+e);
e.printStackTrace();
}
}
}
catch (XMPPException e) {
// TODO Auto-generated catch block
Log.e("aaaaaaaaaaaaaaa","aaaa"+e);
e.printStackTrace();
}
Log.i("transfere file", "sending file done");
}
};
thread.start();
}
can any one help me finding the solution..
If you are using version 3.2.x, there is a known problem with file transfer. Try using 3.1 to see if it fixes your problem.
Now we have 4.1.0 with updated API's.
FileTransferRequest and StreamInitiation makes it more easy now.
Please check with latest Smack version.
https://www.igniterealtime.org/builds/smack/docs/4.1.0/documentation/extensions/filetransfer.html

Categories

Resources