How to receive an incoming mms and write into android database - android

I am trying to make my own messaging application.I am able to send sms and mms I am able to write incoming sms into android database. I have made my app default messaging app. But how to show incoming mms into my inbox with images and text. I am using https://github.com/klinker41/android-smsmms as a library.

You should use MmsReceivedReceiver class of that library. Take a look on it implementation:
public class MmsReceivedReceiver extends BroadcastReceiver {
private static final String TAG = "MmsReceivedReceiver";
public static final String MMS_RECEIVED = "com.klinker.android.messaging.MMS_RECEIVED";
public static final String EXTRA_FILE_PATH = "file_path";
public static final String EXTRA_LOCATION_URL = "location_url";
private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "MMS has finished downloading, persisting it to the database");
String path = intent.getStringExtra(EXTRA_FILE_PATH);
Log.v(TAG, path);
FileInputStream reader = null;
try {
File mDownloadFile = new File(path);
final int nBytes = (int) mDownloadFile.length();
reader = new FileInputStream(mDownloadFile);
final byte[] response = new byte[nBytes];
reader.read(response, 0, nBytes);
DownloadRequest.persist(context, response,
new MmsConfig.Overridden(new MmsConfig(context), null),
intent.getStringExtra(EXTRA_LOCATION_URL),
Utils.getDefaultSubscriptionId(), null);
Log.v(TAG, "response saved successfully");
Log.v(TAG, "response length: " + response.length);
mDownloadFile.delete();
} catch (FileNotFoundException e) {
Log.e(TAG, "MMS received, file not found exception", e);
} catch (IOException e) {
Log.e(TAG, "MMS received, io exception", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, "MMS received, io exception", e);
}
}
}
handleHttpError(context, intent);
DownloadManager.finishDownload(intent.getStringExtra(EXTRA_LOCATION_URL));
}
private void handleHttpError(Context context, Intent intent) {
final int httpError = intent.getIntExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, 0);
if (httpError == 404 ||
httpError == 400) {
// Delete the corresponding NotificationInd
SqliteWrapper.delete(context,
context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
intent.getStringExtra(EXTRA_LOCATION_URL)
});
}
}
}
and implement something like SmsReceiver from example of library.

Related

AndroidThings UsbToUart cannot Rx data when run long times [close]

Hello I use android thing on raspberry pi 3, I have a problem my app use UsbToSerial and then my app can Tx but cannot Rx data when app run longtime but in first period of work my app can Rx data and app can Tx alway times
How can I fix the problem?
And this is my code
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UartService uart_api = new UartService();
uart_api.UartInit("USB1-1.2:1.0", 9600);
}
UartService.java
public class UartService extends Activity {
private static final String TAG = "LoopbackActivity";
// UART Configuration Parameters
private static final int DATA_BITS = 8;
private static final int STOP_BITS = 1;
private static final int CHUNK_SIZE = 512;
private UartDevice mLoopbackDevice;
private void openUart(String name, int baudRate) throws IOException {
mLoopbackDevice = PeripheralManager.getInstance().openUartDevice(name);
// Configure the UART
mLoopbackDevice.setBaudrate(baudRate);
mLoopbackDevice.setDataSize(DATA_BITS);
mLoopbackDevice.setParity(UartDevice.PARITY_NONE);
mLoopbackDevice.setStopBits(STOP_BITS);
}
public void UartInit(String UartName, int baudrate){
PeripheralManager manager = PeripheralManager.getInstance();
List<String> deviceList = manager.getUartDeviceList();
if (deviceList.isEmpty()) {
Log.i(TAG, "No UART port available on this device.");
} else {
Log.i(TAG, "List of available devices: " + deviceList);
}
// Attempt to access the UART device
try {
openUart(UartName, baudrate);
// Read any initially buffered data
Thread thread_read = new Thread(new ThreadUart(123));
thread_read.start();
} catch (IOException e) {
Log.e(TAG, "Unable to open UART device", e);
}
}
public class ThreadUart implements Runnable {
private int data_in;
public ThreadUart(int in) {
this.data_in = in;
}
#Override
public void run() {
while(true){
///////// Test Rx //////
if (mLoopbackDevice != null) {
// Loop until there is no more data in the RX buffer.
try {
byte[] buffer = new byte[CHUNK_SIZE];
int read;
while ((read = mLoopbackDevice.read(buffer, buffer.length)) > 0) { // <<<< when run long time this cannot Rx data
mLoopbackDevice.write(buffer, read);
}
} catch (IOException e) {
Log.w(TAG, "Unable to transfer data over UART", e);
}
}
// sleep 1 sec.
///////// Test Tx //////
String string = "Hello\r\n";
byte[] b = string.getBytes(StandardCharsets.UTF_8);
try {
mLoopbackDevice.write(b, b.length); // <<<< can Tx work!! always time
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
finarly I follow Example example, It work !! in example use felHR85’s USBSerial library
however I don't know cause of Rx lost when use UART API and then run long time

IntentService lost work in executor

I have a classe for download files by an executor :
this.getFreshGoolgletoken(new CallBackTokenRefresh() {
#Override
public void getFreshGoogleToken(String token,String userEmail) {
ArrayList<ExecuteSynchroneRequest> mesRequetes = new ArrayList<>();
Intent mServiceIntent = new Intent(context, TraitementPermisLoaded.class);
for (CollectionPermis permis : collectionPermis){
// stocker les permis + les s3Key
int revision = permis.revision;
final String uuid = permis.uuid;
Log.i(LOG_TAG,"synchro OnLoop permis num & revision :"+uuid+"/"+revision);
Map<String,String> params = new HashMap<>();
params.put("uuid",uuid);
params.put("revision",String.valueOf(revision));
mesRequetes.add(new ExecuteSynchroneRequest(AwsEworkPermitsRoutes.PERMITS,params,context,token,apiClient,uuid,handler,mServiceIntent,callBack));
}
ExecutorService execute = Executors.newSingleThreadExecutor();
for(Runnable r : mesRequetes){
execute.execute(r);
}
execute.shutdown();
}
In this methode i have an IntentService(mServiceIntent) for handle a long treatement on my download. My executor class handle intentService like this in switch command :
case PERMITS:
if(mServiceIntent == null) break;
mServiceIntent.setData(Uri.parse(responseData));
mServiceIntent.putExtra("myHandler", new Messenger(handler));
mServiceIntent.putExtra("ptUuid", uuid);
context.startService(mServiceIntent);
break;
mServiceIntent Class is :
public class TraitementPermisLoaded extends IntentService {
static final String LOG_TAG = "ewp-executor ";
SharedPreferences sharedPreferences;
Handler handler;
public TraitementPermisLoaded() {
super("TraitementPermisLoaded");
setIntentRedelivery(true);
Log.i(LOG_TAG," service traitement permis called 2 ");
}
#Override
protected void onHandleIntent(Intent workIntent) {
this.sharedPreferences = getApplicationContext().getSharedPreferences("DATA", Context.MODE_PRIVATE);
// Gets data from the incoming Intent
String responseData = workIntent.getDataString();
Messenger messenger = null;
String ptUuid = "";
Bundle extras=workIntent.getExtras();
if (extras!=null) {
messenger=(Messenger)extras.get("myHandler");
ptUuid = extras.getString("ptUuid");
}
String permisUuid = "";
PtWrapper pt = null;
try {
ObjectMapper mapper = new ObjectMapper();
pt = mapper.readValue(responseData, PtWrapper.class);
HandleJson handleJson = HandleJson.getInstance(getApplicationContext());
permisUuid = pt.getPermisTravailFormContext().permisTravail.uuid;
if (permisUuid != null) {
handleJson.writeInInterneFileSysteme(sharedPreferences.getString("email",null),pt, permisUuid);
} else {
throw new HandleJsonNoPermisException("le UUID est null on ne peut pas enregistrer ce permis");
}
handleJson.setKpi(pt);
Message message = Message.obtain();
Bundle bundle= new Bundle();
bundle.putString("myevent", "un permis ok");
message.setData(bundle);
messenger.send(message);
} catch (IOException e) {
Log.i(LOG_TAG, e.getMessage());
e.printStackTrace();
Message message = Message.obtain();
Bundle bundle= new Bundle();
bundle.putString("error", ErrorsCodes.CODE_40.toString()+" / permit uuid : "+ptUuid);
message.setData(bundle);
try {
messenger.send(message);
} catch (RemoteException e1) {
e1.printStackTrace();
Log.i(LOG_TAG,"erreur messager : "+e1.getMessage());
}
} catch (HandleJsonNoPermisException e) {
Log.i(LOG_TAG, e.getMessage());
e.printStackTrace();
} catch (RemoteException e) {
Log.i(LOG_TAG,e.getMessage());
e.printStackTrace();
}catch(Exception e){
Log.i(LOG_TAG,e.getMessage());
e.printStackTrace();
}
}
}
I load 27 files but only 14 get a treatment, the Intentservice stop to work, it'seems to be after activity change but not sure. After loaded files, I change my activity by another, but intentService get all request in the queue. I have use IntentService because it will finish working all process before stopping?
What did I do wrong?
Thanks
the error source is the size of data in myService.setData(mydata>250ko). For all data more than 250 ko the service stop with this error message :
A/ActivityManager: Service done with onDestroy, but executeNesting=2:
ServiceRecord{5c8e958 u0
com.alit.aws.android.eworkpermit/.lib.TraitementPermisLoaded
There is another way to pass large data more than 250 k to my intentService ? I have tried :
->mServiceIntent.setData(Uri.parse(responseData));
->mServiceIntent.putExtra("myData",responseData);
I have found a solution, remove the "setData(responseData)" and replace it by a globalHasMap. After the end of treatment I remove item in hashMap.
May be it's not awesome but i have not found a better solution.
If someone can show me a better way, do it ;-)
Thanks

Logs don't get printed in the logcat

I'm having a weird problem. I already lost a lot of time trying to understand
and solve this but nothing works.
I have an app that communicates with another device across bluetooth connection
to receive some sensor data. In that point, everything works fine, I can connect
to the device, receive and treat the messages.
But yesterday, I decided to create some kind of log file to directly save in the
internal memory the data received from the device without any kind of transformation from my app.
To receive the data from the device, I have a background thread:
public class CommunicationThread extends Thread {
private static final UUID UUID_DEVICE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = CommunicationThread.class.getSimpleName();
private CommunicationListener mListener;
private boolean mRunning;
private BluetoothSocket mBluetoothSocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
public interface CommunicationListener {
void onMessageReceived(String msg);
}
public CommunicationThread(
#NonNull BluetoothDevice device,
#Nullable CommunicationListener listener) throws IOException {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID_DEVICE);
socket.connect();
this.mBluetoothSocket = socket;
this.mInputStream = socket.getInputStream();
this.mOutputStream = socket.getOutputStream();
this.mListener = listener;
}
#Override
public void run() {
mRunning = true;
byte[] bytes = new byte[1024];
int length;
while (mRunning) {
try {
Log.d(TAG, "Waiting for message");
// read the message (block until receive)
length = mInputStream.read(bytes);
String msg = new String(bytes, 0, length);
Log.d(TAG, "Message: " + msg);
// Message received, inform the listener
if (mListener != null)
mListener.onMessageReceived(msg);
} catch (Exception e) {
Log.e(TAG, "Error reading the message", e);
}
}
}
public void sendCommand(String msg) {
try {
mOutputStream.write((msg).getBytes());
} catch (Exception e) {
Log.e(TAG, "Error to send message", e);
}
}
public void stopCommunication() {
mRunning = false;
mListener = null;
try {
if (mBluetoothSocket != null) {
mBluetoothSocket.close();
}
if (mInputStream != null) {
mInputStream.close();
}
if (mOutputStream != null) {
mOutputStream.close();
}
} catch (IOException e) {
Log.e(TAG, "Error to stop communication", e);
}
}
}
This thread works pretty fine and when a message is received, it informs the listener,
my Controller class. The first thing that I try to do when a message comes, is save it:
public class Controller implements CommunicationThread.CommunicationListener
...
#Override
public void onMessageReceived(final String msg) {
Log.d(TAG, "onMessageReceived(msg): " + msg);
mLogCreator.saveThis(msg);
....
}
}
Here is the LogCreator class:
public class LogCreator {
private static final String TAG = LogCreator.class.getSimpleName();
public static final String LOG_FILE_NAME = "log.txt";
private final Context mContext;
private volatile String mTempFullLog;
public LogCreator(Context context) {
mContext = context.getApplicationContext();
File dir = new File(mContext.getFilesDir(), "log_folder");
if (!dir.exists()) {
dir.mkdirs();
File file = new File(dir, LOG_FILE_NAME);
writeString(file, "");
Log.d(TAG, "empty file created");
}
}
public void saveThis(final String data) {
mTempFullLog += "\n" + data;
Log.d(TAG, "New log: " + data);
}
public void start() {
File dir = new File(mContext.getFilesDir(), "log_folder");
File file = new File(dir, LOG_FILE_NAME);
mTempFullLog = readString(file);
Log.d(TAG, "File: " + file);
Log.d(TAG, "Temp full log: " + mTempFullLog);
}
public void stop() {
File dir = new File(mContext.getFilesDir(), "log_folder");
File file = new File(dir, LOG_FILE_NAME);
writeString(file, mTempFullLog);
Log.d(TAG, "log saved: " + mTempFullLog);
}
}
The LogCreator class is already initialized and it works properly, because
if I try to read the file later, everything is there.
The real problem is the following: there is a lot of calls to Log.d during
this execution flow, and this makes very easy to me to understand the all process.
But, the logs are only printed in the logcat until this Log.d call, in the
CommunicationThread class:
Log.d(TAG, "Waiting for message);
After the message received, all code executes normally, but no logs are printed in
the logcat and I really dont know why.
Logs not printed:
CommunicationThread:
Log.d(TAG, "Message: " + msg);
Controller:
Log.d(TAG, "onMessageReceived(msg): " + msg);
LogCreator:
Log.d(TAG, "New log: " + data);
Like I said, I know that everything is working fine with the code because the log
file is created in internal memory even without the logcat prints. It cost me
some hours to realize that the problem is only with the log and not really in
my code.
For testing purpose, if I add this code in the saveThis method of LogCreator,
it executes normally:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, data, Toast.LENGTH_SHORT).show();
}
});
This makes me think that everything could be a thread problem, because the start
and stop methods of LogCreator are both called from the main thread not the CommunicationThread and both methods have their logs printed. Because of this, in the onMessageReceived method
of the Controller class, I tried this:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mLogCreator.saveThis(msg);
}
});
But, unfortunately, the logs don't get printed in the logcat. The toast is still
executed and the data are still saved to the file.
If anyone has any idea of what might be causing this, I really want to know, thanks.
I finally find the solution myself. The reason why the following not work is not clear for me, and IMO it should be treated like a bug.
I compile the app in debug mode and discover that the string received from the device has a "\r" in the end.
Example: "15.50\r"
So, for some strange reason, if I try to do this:
Log.d(TAG, "New log: " + data);
Nothing prints and we don't receive no warnings at all.
But, if I do this instead:
Log.d(TAG, "New log: " + data.replace("\r", ""));
Where data is: "15.50\r"
Everything works and the logcat prints the message.

Can't create handler inside thread that has not called Looper.prepare(). RuntimeExcetion while uploading file to DropBox

I m getting exception "Can't create handler inside thread that has not called Looper.prepare()
in the function doFirstTime().
I m trying to upload my data at Dropbox using Dropbox API
Can you tell me how to fix it?
public class DownloadFile extends AsyncTask<Void, Long, Boolean>
`{
private Context mContext;
private DropboxAPI<?> mApi;
private String mPath;
private FileOutputStream mFos;
private String mErrorMsg;
private StringBuilder xmlcode,newXMLCode;
private final static String FILE_NAME = "fuelrecords.xml";
private final static String ZIP_FILE_NAME = "fuelpad.zip";
private String dropbox_xml_records[];
private ArrayList<ArrayList<String>> dropbox_records;
private ArrayList<ArrayList<String>> database_records;
private ExpenseOperations eop;
private UploadFile up;
private boolean no_file;
public DownloadFile(Context context, DropboxAPI<?> api,String dropboxPath)
{
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mApi = api;
mPath = dropboxPath;
dropbox_records = new ArrayList<ArrayList<String>>();
database_records = new ArrayList<ArrayList<String>>();
eop = new ExpenseOperations(mContext);
xmlcode=new StringBuilder("");
newXMLCode=new StringBuilder("");
no_file = false;
}
#Override
protected Boolean doInBackground(Void... params)
{
Log.d("yes1", " in do in back of download..");
try
{
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null)
{
// It's not a directory, or there's nothing in it
mErrorMsg = "Could not locate the file...";
return false;
}
String cachefilePath = mContext.getCacheDir().getAbsolutePath() + "/" + FILE_NAME;
String cachezipPath = mContext.getCacheDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
try
{
mFos = new FileOutputStream(cachezipPath);
}
catch (FileNotFoundException e)
{
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
Notification("SmartExpense", "Now syncing to dropbox");
mApi.getFile("/SmartExpenses.zip",null,mFos,null);
try
{
FileInputStream fin = new FileInputStream(cachezipPath);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
if((ze = zin.getNextEntry()) != null)
{
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory())
{
}
else
{
FileOutputStream fout = new FileOutputStream(cachefilePath);
for (int c = zin.read(); c != -1; c = zin.read())
{
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
}
catch(Exception ee)
{
Log.d("In unzip:", ""+ee);
}
try
{
FileInputStream fs =new FileInputStream(cachefilePath);
byte buff[] =new byte[1024];
while(fs.read(buff)>0)
{
xmlcode.append(new String(buff));
}
fs.close();
Log.d("Hhhhhhhhhhhaaaaaaaaaaaaa : ",""+xmlcode);
Looper.prepare();
if(!(xmlcode.toString().contains("<expenserecord>")) && getDBRecords())
{
doFirstTime();
Log.d("1","1");
}
else if((xmlcode.toString().contains("<expenserecord>")) && getDBRecords())
{
Log.d("2","2");
makeDropboxRecordArray();
performSync();
}
else if((xmlcode.toString().contains("<expenserecord>")) && !getDBRecords())
{
Log.d("3","3");
makeDropboxRecordArray();
fillDBwithDropboxRecords();
}
else if(!(xmlcode.toString().contains("<expenserecord>")) && !getDBRecords())
{
Log.d("4","4");
mErrorMsg ="No records exist to sync";
}
}
catch (Exception e)
{
Log.d("Exception in doback: ",""+e);
}
return true;
}
catch (DropboxUnlinkedException e)
{
mErrorMsg = "Error :Dropbox unliked";
// The AuthSession wasn't properly authenticated or user unlinked.
}
catch (DropboxPartialFileException e)
{
// We canceled the operation
mErrorMsg = "Download canceled";
}
catch (DropboxServerException e)
{
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED)
{
mErrorMsg = "Server Error.....";
// won't happen since we don't pass in revision with metadata
}
else if (e.error == DropboxServerException._401_UNAUTHORIZED)
{
mErrorMsg = "Server Error : Unautherized user...";
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
}
else if (e.error == DropboxServerException._403_FORBIDDEN)
{
mErrorMsg = "Server Error : Access denied";
// Not allowed to access this
}
else if (e.error == DropboxServerException._404_NOT_FOUND)
{
no_file = true;
doFirstTime();
// path not found
}
else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE)
{
mErrorMsg = "Server Error : Congestion...";
// too many entries to return
}
else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE)
{
// user is over quota
mErrorMsg = "Server Error : Insufficient Storage...";
}
else
{
// Something else
mErrorMsg = "Server Error...";
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null)
{
mErrorMsg = e.body.error;
}
}
catch (DropboxIOException e)
{
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
}
catch (DropboxParseException e)
{
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
}
catch (DropboxException e)
{
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
public void fillDBwithDropboxRecords()
{
Log.d("In fill db","yetoy");
try
{
for(int i=0 ; i<dropbox_records.size()-1 ; i++)
{
{
eop.addRecord(Integer.parseInt(dropbox_records.get(i).get(0)), dropbox_records.get(i).get(1), dropbox_records.get(i).get(2), Integer.parseInt(dropbox_records.get(i).get(3)));
}
}
}
catch (Exception e)
{
Log.d("In fill db", ""+e);
}
}
private void doFirstTime()
{
Log.d("yes2", " in do first time of download..");
try
{
if(!getDBRecords())
{
mErrorMsg = "No records exist to sync";
return;
}
newXMLCode.append("<smartexpense>");
for(int i=0 ; i<database_records.size() ; i++)
{
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+database_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+database_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+database_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+database_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}//for
newXMLCode.append("</smartexpense>");
up = new UploadFile(mContext,mApi,newXMLCode.toString());
up.execute();
}
catch(Exception e)
{
Log.d("Exception in doFirtstTime : ",""+e);
}
}//doFirstTime
public void makeDropboxRecordArray()
{
Log.d("yes3", " in make record array of download..");
try
{
dropbox_xml_records = (xmlcode.toString()).split("</expenserecord>");
for(int i=0 ; i< dropbox_xml_records.length ; i++)
{
dropbox_records.add(new ArrayList<String>());
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<c_id>"))+
("<c_id>".length())),
dropbox_xml_records[i].indexOf("</c_id>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<title>"))+
("<title>".length())),
dropbox_xml_records[i].indexOf("</title>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<date>"))+
("<date>".length())),
dropbox_xml_records[i].indexOf("</date>")
));
dropbox_records.get(i).add(dropbox_xml_records[i].substring(
((dropbox_xml_records[i].indexOf("<amount>"))+
("<amount>".length())),
dropbox_xml_records[i].indexOf("</amount>")
));
}
}
catch (Exception e)
{
Toast.makeText(mContext,"In fill records :"+e , 2000).show();
}
}
public boolean getDBRecords()
{
Log.d("yes4", " in get dbrecords of download..");
try
{
Cursor cc = eop.getRecords();
if(cc.getCount() == 0)
return false;
int i=0;
if(cc.moveToFirst())
{
do
{
database_records.add(new ArrayList<String>());
database_records.get(i).add(cc.getString(cc.getColumnIndex("c_id")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("title")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("date")));
database_records.get(i).add(cc.getString(cc.getColumnIndex("amount")));
i++;
}while(cc.moveToNext());
}
cc.close();
}
catch(Exception ee)
{
Toast.makeText(mContext,"getDBRecords :"+ee , 2000).show();
}
return true;
}
public void performSync()
{
try
{
//compare database records with dropbox records
newXMLCode.append("<smartexpense>");
for(int i=0 ; i<database_records.size() ; i++)
{
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+database_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+database_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+database_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+database_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}
for(int i=0 ; i<dropbox_records.size()-1 ; i++)
{
eop.addRecord(Integer.parseInt(dropbox_records.get(i).get(0)),
dropbox_records.get(i).get(1),
dropbox_records.get(i).get(2),
Integer.parseInt(dropbox_records.get(i).get(3)));
newXMLCode.append("<expenserecord>");
newXMLCode.append("<c_id>"+dropbox_records.get(i).get(0)+"</c_id>");
newXMLCode.append("<title>"+dropbox_records.get(i).get(1)+"</title>");
newXMLCode.append("<date>"+dropbox_records.get(i).get(2)+"</date>");
newXMLCode.append("<amount>"+dropbox_records.get(i).get(3)+"</amount>");
newXMLCode.append("</expenserecord>");
}
//}
newXMLCode.append("</smartexpense>");
Log.d("Comming : ","yetoy..");
up = new UploadFile(mContext,mApi,newXMLCode.toString());
up.execute();
}
catch (Exception e)
{
Log.d("Perform sync: ",""+e);
}
}
#Override
protected void onPostExecute(Boolean result)
{
//mDbHelper.close();
if (result)
{
//showToast("File successfully downloaded");
}
else
{
if(!no_file)
{
// Couldn't download it, so show an error
showToast("Error in sync.Check notification.");
Notification("SmartExpense", mErrorMsg);
}
}
}
private void showToast(String msg)
{
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
// Notification Function
private void Notification(String notificationTitle, String notificationMessage)
{
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(android.R.drawable.ic_menu_save, "Dropbox Sync", System.currentTimeMillis());
Intent notificationIntent = new Intent(mContext, UploadFile.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
notification.setLatestEventInfo(mContext, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
}
This error is received while you try and update your UI from a background thread. In your case the doInBackground method.
It appears that you are trying to post a notification from doInBackground from the following line.
Notification("SmartExpense", "Now syncing to dropbox");
This might be causing the issue. Try commenting this and any other UI updates you might be doing in doInBackground
This Exception indicates that you are trying to access UI elements in a non UI thread. From your code probably the problem is caused by these two lines inside your doInBackground method (you are accessing the Activity's context):
String cachefilePath = mContext.getCacheDir().getAbsolutePath() + "/" + FILE_NAME;
String cachezipPath = mContext.getCacheDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
If you declare this two variables outside the doInBackgroud method and instatiate them in your constructor, you should be ok. Also, remove the lines in your code that you are calling Looper.prepare() since they will not fix the problem.

Android XMPP File Transfer

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 .

Categories

Resources