I am developing an SMS-MMS vault application for android. Its purpose will be to correct a couple of vulnerabilities existing in Android, as well as creating a "safe" communication space between certain contacts (Encrypted SMS and MMS).
I have implemented all the intended functionalities, except the functionality to receive MMS. I have found out no documentation on this matter. I have been reading a lot of code from other apps that implement this functionality and all of them wait for the stock application to receive the MMS and then retrieve it, which is not what I'm looking for, for my application is meant to be the default one.
So, here begs my question:
After receiving the MMS intent, how do I parse the Image and the Text?
So what you can do to get pictures is go I get the MMS's id and go through ("content://mms/part")
do a type check:
String type = cursor.getString(cursor.getColumnIndex("ct"));
String partId = cursor.getString(cursor.getColumnIndex("_id"));
//is type a picture
if ("image/jpeg".equals(type) || "image/bmp".equals(type)
|| "image/gif".equals(type) || "image/jpg".equals(type)
|| "image/png".equals(type)) {
getMmsImage(partId); // load in your picture
}
Now you that you have the part ID you know the picture's location so you can load it in using anything you want for example if you just want it as a bitmap you can do:
public Bitmap getMmsImage(String _id, Context context) {
Uri partURI = Uri.parse("content://mms/part/" + _id);
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {// probably should do an ioException around here}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
}
}
return bitmap;
}
Now I would like to point out that if you wanted animated gifs this would not work, it would load the gifs but they would be still images. if you want them animated you could use something like Glide and give it the path location for the uri. Glide takes a while to load gifs though, just fair warning.
As for Receiving MMS, you could always use an Observer and load in the added message whenever the observer say there was a change... Or use a broadcast receiver if you want it to be the default messenger.
Related
I am working on one application, where I am using IPFS for storing and getting files.
I am using the following API for Android,
https://github.com/ligi/ipfs-api-kotlin
As per the doc, I can get data from IPFS using following code,
ipfs.get.cat("hash code of IPFS file")
but here it returns everything in string format, even if the uploaded file is Image.
How Can I know the content type of the file and download the same format?
IPFS doesn't allow to store metadata such as the content type alongside the content itself.
Something you could do in Java that worked for me:
private static String guessContentType(InputStream content) {
try {
String guessedContentType = URLConnection.guessContentTypeFromStream(content);
if (!StringUtils.isEmpty(guessedContentType)) {
return guessedContentType;
} else {
return MediaType.APPLICATION_OCTET_STREAM_VALUE;
}
} catch (IOException e) {
throw new RuntimeException("Unable to guess content type", e);
}
}
I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?
You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish
To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}
I have a image save in me phone with android 4.4 .
In properties (of the image) says location:"/storage/emulated/0/bluetooth/p.png".
Now, the problem is, I wanna uploading this image (p.png) by my android applicacion to a remote mysql database. It has a field calls photos and is definied as blob.
I´m trying this code. but i dont works. it doesnt give me an error, but the phono never appears in the table of my database. (the coneccion with database is OK).
public void setImage() throws Exception
{
crearConexion();
System.out.println("Entre");
String q="insert into clientes(imagen) values (?) where id_cliente=1;";
try {
String filePath = "/storage/emulated/0/bluetooth/p.png";
InputStream inputStream = new FileInputStream(new File(filePath));
PreparedStatement statement = con.prepareStatement(q);
statement.setBlob(1, inputStream);
statement.executeUpdate();
System.out.println("Terminee");}
catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("ERROR SQLlogHA");
} finally {
}
}
So please give an example of how upload a photo in my phone and save ir in mysql remote data base with a blob fild.
I think you should use web services to link your application with the database.
M aybe this could help you https://stackoverflow.com/a/15173589/4364031
Previously I've asked some questions regarding what method I should use to save some data from my app to retrieve at a later time after it's been closed/stopped. I got the answers I was looking for, I think. But since then, my efforts to implement such a feature has fallen way short. I've researched various questions I've had, for which I thought I found answers. But it seems that the answers, while maybe correct, are not a match necessarily for each other. What I mean, is they might work separately, but coming from various sources, they don't work together as a whole, and for me they don't work at all. I'm led to believe I want to use SharedPreferences. That may or may not be the case, but that has been the direction of my efforts lately.
So I'll ask this multi-part question.
How would you go about saving an array of integers(or boolean values)?
Before loading that saved array, how would I check if it exists?
How would I load the array to use its values again?
Those are the basis of my issues right now. Even at this point, as frustrated as I may be, I don't mind doing more research if someone can point me in the right direction, but everywhere I've looked seems to be missing information and I'm unable to really understand/see how to code what I want to do.
If you REALLY want to see some code, I can show you all my broken pieces at the moment (what I haven't deleted), but I don't see it doing you any good. That said, I'll answer any questions you may need to help me out.
Thanks in advance.
EDIT: The array will change very little from app version to version. It should be about 500-2000 integers or boolean values (either/or will work the same for me). The array is basically a set of flags that tells the app to do one thing or another depending on the value. The size will only change if I add or remove items between versions. For this reason, after checking if the file/array exists, I'll compare the saved array with one in the app and act accordingly.
I've had similar issues with data that has to be preserved through a reboot. I found two ways to do it.
1) Data is seldom accessed.
Store data in .../files in some format that can be easily saved/retrieved. I used JSONArrays to hold the data. mContext.getFilesDir() will get you the path, and you can simply see if your file.exists() to determine if the data exists.
You will need to create an object that will:
1) convert your data to the stored format
for(int i = 0; i < mArray.size(); i++ )
{
JSONObject jo = new JSONObject();
jo.put("THINGY", mArray[i]);
ja.put(jo);
}
2) retrieve your data from the store
String js = readFromFile(fileName);
if( !js.isEmpty() )
ja = new JSONArray( js );
for( int i = 0; i < ja.length(); i++
{
// CONVERT THIS ARRAY TO YOUR INT...
}
3) read/write files like this:
private void writeToFile(String fileName, String data)
{
try
{
FileOutputStream fOut = openFileOutput( fileName, MODE_PRIVATE );
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Log.d(TAG, "Writing output log...");
osw.write(data);
osw.flush();
osw.close();
}
catch( Exception e )
{
Log.e(TAG, "Cannot create " + fileName );
}
}
private String readFromFile(String fileName)
{
String ret = "";
try
{
InputStream inputStream = openFileInput(fileName);
if ( inputStream != null )
{
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null )
{
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e)
{
Log.e(TAG, "File not found: " + e.toString());
}
catch (IOException e)
{
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
JSON works well in this case because there are easy methods to convert to/from strings.
2) Frequent Access
I used SQLiteDatabase. I use a Singlton and DBHelper.getInstance() to get access to it. This seems like overkill, but it is a good solution if the amount of data you are saving is increasing beyond a simple array of Integers.
A really basic (but sound) place to start is: http://www.vogella.com/tutorials/AndroidSQLite/article.html. Note his page was written for 4.3.
HTH.
I'm new to Android development and I will appreciate any help I can get.
I'm designing an app that at some point needs to ask user for his Friends' names in order to work with those names later on, i.e those names will be used in drop-down lists and will be displayed at a separate View.
My question is: what is the best way to efficiently store those names and then be able to get access to them for reading, editing and deleting? The amount of names will not be big (at most 20 items).
In response to the comment about adding more info:
I need a user to specify list of names (strings) that will be used in 2 different Android Activities:
1) This list of names will be used in a Spinner that is a part of an application form
2) This list of names will be used on a separate Activity designed for Manipulating (Editing and Deleting) of existing items and adding new ones.
I also need that after manipulations (editing, deleting and creating new items) with this list changes took place in Both Activities. This list should be available after user exits the app, so as I understand it should be stored somewhere in Internal Storage.
I hate when people answer a question by just posting the link to the docs, so I won't do that.
I will post the link to the docs AND provide an answer:
DOCS: http://developer.android.com/guide/topics/data/data-storage.html
(it is actually a good read, not too long, and good to know what your options are).
It looks to me you need to save an ArrayList or something, and you are saying 20 names would be the maximum amount, so I would say you have 3 viable options, which I present here, ordered in ascending order of simplicity using my humble opinion as a comparator:
1- InternalStorage
2- SharedPreferences
3- Very interesting way I just found while researching one of the options to help you, and I will definatelly use this when I need to save a small array of data...
So the steps I would recomend are: put the names in your favourite collection object (ArrayList, HashSet, etc), then refer to those examples for the methods cited above, respectivelly:
1- https://stackoverflow.com/a/22234324/367342 (YES, this a link to a answer given on this thread, I voted it up, I feel better for cheating now).
2- Save ArrayList to SharedPreferences
3- https://stackoverflow.com/a/5703738/367342 <- this
- Convert your data to a JSONObject
- Convert it to a string
- Save this string using shared preferences
- Read it later as a jsonobject
Example on 3 (untested, sorry):
//Convert the ArrayList to json:
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
//Make it into a string
String myLittleJason = json.toString();
//save it to the shared preferences
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", myLittleJason).commit();
//Loading it back from the preferences
String loadedJsonString = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", "I have no friends, this is the default string returned if the key was not found, so, jokes aside, better make this a empty JSON string");
//making it into a JSON again
JSONObject loadedJson = new JSONObject(loadedJsonString);
//Converting the Json back into a ArrayList
ArrayList items = loadedJson.optJSONArray("uniqueArrays");
I loved that JSON approach, if you like it too, upvote the original (too ;) ) https://stackoverflow.com/a/5703738/367342
If you are going to store only 20 items, maybe the best way is to write and read a file.
public void writeItems(String fileName) {
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer =
new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,
Context.MODE_PRIVATE)));
writer.write("Item 1" + ls);
writer.write("Item 2" + ls);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void readItems(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
String line;
while ((line = input.readLine()) != null) {
//do something
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
openFileInput and openFileOutput reference : http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
You have many options but I will give you two options:
SharedPreferences
SQLLite
If it's temporary and doesn't require intense data manipulation, I would go with SharedPreferences as it's easier to setup and easy to use and recycle.