I want to get an int with the number of unread emails in the accounts of the device. I have seen that there is a new way to do this using the "Gmail Labels Public API"
http://android-developers.blogspot.in/2012/04/gmail-public-labels-api.html
I have read the documentation and downloaded the sample application and it really works. But I have two problems: (
My intention is to get an int with the number of unread conversations, i try this:
public static int getUnreadGmailCount(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(GmailContract.Labels.getLabelsUri("ensisinfo102#gmail.com"),
null,
null, null,
null);
if (cursor == null || cursor.isAfterLast()) {
Log.d(TAG, "No Gmail inbox information found for account.");
if (cursor != null) {
cursor.close();
}
return 0;
}
int count = 0;
while (cursor.moveToNext()) {
if (CANONICAL_NAME_INBOX_CATEGORY_PRIMARY.equals(cursor.getString(cursor.getColumnIndex(CANONICAL_NAME)))) {
count = cursor.getInt(cursor.getColumnIndex(NUM_UNREAD_CONVERSATIONS));
System.out.println("count is====>"+count);
break;
}
}
cursor.close();
return count;
}
but not works, always returns "0",But in gmail i have 3 unread messages
really appreciate any help
thanks and regards
You can get a label and check the messagesUnread. The INBOX label is probably what you want:
Request
GET https://www.googleapis.com/gmail/v1/users/me/labels/INBOX?access_token={ACCESS_TOKEN}
Response
{
"id": "INBOX",
"name": "INBOX",
"messageListVisibility": "hide",
"labelListVisibility": "labelShow",
"type": "system",
"messagesTotal": 4527,
"messagesUnread": 4498,
"threadsTotal": 4168,
"threadsUnread": 4154
}
Please read carefully this document and also check this one
Related
I want to retrieve a user's profile and it's image, but this is not working. I always get an empty cursor (cursor.getCount() == 0). Can someone help?
I have a profile with an image and a phone number on my phone but I can't read it. Permissions (read and write contacts permissions) are granted and I can retrieve all my phone contacts, but not the own profile.
Any ideas?
Code
void loadUser() {
Uri dataUri = Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
String[] selection = new String[]
{
ContactsContract.Data.RAW_CONTACT_ID,
ContactsContract.Data._ID,
ContactsContract.Profile.DISPLAY_NAME,
ContactsContract.Profile.PHOTO_URI,
ContactsContract.Profile.LOOKUP_KEY,
ContactsContract.Data.DATA_VERSION
};
Cursor cursor = MainApp.get().getContentResolver().query(
dataUri,
selection,
null,
null,
null);
if (cursor != null) {
L.d("MY PROFILE - cursor size: %d", cursor.getCount());
int rawId = cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
int id = cursor.getColumnIndex(ContactsContract.Data._ID);
int name = cursor.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME);
int photoUri = cursor.getColumnIndex(ContactsContract.Profile.PHOTO_URI);
int lookupKey = cursor.getColumnIndex(ContactsContract.Profile.LOOKUP_KEY);
int version = cursor.getColumnIndex(ContactsContract.Data.DATA_VERSION);
try {
if (cursor.moveToFirst()) {
long phRawId = cursor.getLong(rawId);
int phId = cursor.getInt(id);
String phName = cursor.getString(name);
String phImageUri = cursor.getString(photoUri);
String phLookupKey = cursor.getString(lookupKey);
int phVersion = cursor.getInt(version);
boolean phExists = true;
L.d("MY PROFILE - RawID: %d, ID: %d", phRawId, phId);
// ... profile successfully retrieved
} else {
L.d("MY PROFILE - cursor is EMPTY");
}
} finally {
cursor.close();
}
} else {
L.d("MY PROFILE - cursor = NULL");
}
}
Additional info
I think this code worked on my S6 with android 7 but it's not working on my new S9 with android 8 on it (can't test it on my old phone anymore as it's not working anymore). So this may be an android version specific problem...
This appears to be bad implementation of Samsung's Contacts app, I've opened a bug report on their developer's forum here: https://developer.samsung.com/forum/thread/contacts-app-profile-is-not-accessible-via-contactscontractprofile-api/201/354874
I have setup a background service to registerContentObserver to get notified whenever an SMS is sent. Upon receiving this event, I would increment a variable to know the count of messages sent. This is working as expected.
When someone sends SMS with more than 140 characters, the mobile carrier would treat this as multiple SMS, but it seems that I get only 1 callback for the sent message. This is causing my app to miss counting some messages.
Is there any proper way to know how many messages were actually sent?
When an app is responsible for writing its own messages to the Provider, it's most likely going to write the whole message in one go, regardless of whether the message must be sent as multipart. This would be why your Observer is often firing only once for each complete message, no matter how big.
Since KitKat, the system will automatically save the outgoing messages for any non-default apps, and for multipart messages, each part will be saved individually, firing your Observer each time. Of course, this doesn't help for anything prior to KitKat, or if a default app saves its own messages on later versions.
One possibility is to fetch the message body in your ContentObserver, and determine how many message parts it would've been split into. The SmsMessage.calculateLength() method can do this for us. It returns an int array, the first element of which will have the message count for the given text.
For example, using the old onChange(boolean) method, to support API < 16:
private class SmsObserver extends ContentObserver {
private static final Uri SMS_SENT_URI = Uri.parse("content://sms/sent");
private static final String COLUMN_ID = "_id";
private static final String COLUMN_BODY = "body";
private static final String[] PROJECTION = {COLUMN_ID, COLUMN_BODY};
// You might want to persist this value to storage, rather than
// keeping a field, in case the Observer is killed and recreated.
private int lastId;
public SmsObserver(Handler handler) {
super(handler);
}
#Override
public void onChange(boolean selfChange) {
Cursor c = null;
try {
// Get the most recent sent message.
c = getContentResolver().query(SMS_SENT_URI, PROJECTION, null,
null, "date DESC LIMIT 1");
if (c != null && c.moveToFirst()) {
// Check that we've not already counted this one.
final int id = c.getInt(c.getColumnIndex(COLUMN_ID));
if (id == lastId) {
return;
}
lastId = id;
// Get the message body, and have the SmsMessage
// class calculate how many parts it would need.
final String body = c.getString(c.getColumnIndex(COLUMN_BODY));
final int numParts = SmsMessage.calculateLength(body, false)[0];
// Add the number of parts to the count,
// however you might be doing that.
addToCount(numParts);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (c != null) {
c.close();
}
}
}
}
Should you be supporting API 16 and above, we can use the onChange(boolean, Uri) overload, and things get a little simpler, since we don't necessarily need to keep track of the last message ID.
#Override
public void onChange(boolean selfChange, Uri uri) {
Cursor c = null;
try {
// type=2 restricts the query to the sent box, so this just
// won't return any records if the Uri isn't for a sent message.
c = getContentResolver().query(uri, PROJECTION, "type=2", null, null);
if (c != null && c.moveToFirst()) {
final String body = c.getString(c.getColumnIndex(COLUMN_BODY));
final int numParts = SmsMessage.calculateLength(body, false)[0];
addToCount(numParts);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (c != null) {
c.close();
}
}
}
In my application i want to get sms/mms from device and display the messages in listview.By using the following code to get the all sms from device.
public void readSmsFromDevice() {
preferences = PreferenceManager
.getDefaultSharedPreferences(BackgroundService.this);
final_msg_time = preferences.getLong("msgtime", 0);
Uri uriSMSURI = Uri.parse("content://sms/");
String[] projection = { "address", "body", "date", "type" };
String where = "date" + ">" + final_msg_time;
Cursor cur = getContentResolver().query(uriSMSURI, projection, where,null, "date");
while (cur.moveToNext()) {
if(ProfileFragment.stop)
{
break;
}else{
try {
//
Message mess1=new Message();
try{
String _id = cur.getString(cur.getColumnIndex("_id"));
mess1.setId(_id);
}catch(Exception e)
{
mess1.setId("null");
}
try{
String number = cur.getString(cur.getColumnIndex("address"));
number = number.replaceAll("[\\W]", "");
if (number.trim().length() > 10) {
mess1.setNumber(number.substring(number.length() - 10,
number.length()));
mess1.setAddress(number.substring(number.length() - 10,
number.length()));
} else {
mess1.setNumber(number);
mess1.setAddress(number);
}
}
catch(Exception e){}
mess1.setBody(cur.getString(cur.getColumnIndex("body")));
String type = cur.getString(cur.getColumnIndex("type"));
Long millisecond = Long.parseLong(cur.getString(cur
.getColumnIndex("date")));
String dateString = DateFormat.format("yyyy/MM/dd hh:mm:ss a",
new Date(millisecond)).toString();
mess1.setDate_millis(millisecond);
mess1.setDate(dateString);
mess1.setType(type);
mess1.setmessagetype("sms");
messages.add(mess1);
} catch (Exception e) {}
}
}
cur.close();
}
By using this method i am getting all sms from device.But my question is how to differenciate group message.In group message one message sent different contact numbers(senders).So in normal message application group message displayed in separate column and single message displayed in separate column.So my application also i have to display the messages like message application.So in this cursor how to identify group message?Is there any column is available to identify group message?So please suggest me how to do taht.Thanks In Advance.....
the thread THREAD_ID column will give you all the messages in the same conversation. You can then use the address column to differentiate the senders of the messages in the group message.
You should also use the Telephony class that was introduced in API 19 instead of the content resolver. https://developer.android.com/reference/android/provider/Telephony.html
i need to get all the MMS Data detalis like mms_image, address,date and type.
i am using following logic. In this i am using two cursors, one for images and other for remaining fields. but the size of two cursors are different. so, i am unable to match both image and other fields.
//for date,address,type
Cursor curPdu = getContentResolver ().query(Uri.parse("content://mms"), null, null, null, null);
while(curPdu.moveToNext())
{
String id = curPdu.getString (curPdu.getColumnIndex ("_id"));
String date = curPdu.getString (curPdu.getColumnIndex ("date"));
mms_add.add(getAddressNumber(Integer.parseInt(id)));
int type = Integer.parseInt(curPdu.getString(curPdu.getColumnIndex("m_type")));
mms_type.add((type==128)?"2":"1");
mms_date.add(getDate(Long.parseLong(date)));
}
//for image
Cursor curPart = getContentResolver (). query (Uri.parse ("content://mms/part"), null, null, null, null);
while(curPart.moveToNext())
{
coloumns = curPart.getColumnNames();
if(values == null)
values = new String[coloumns.length];
for(int i=0; i< curPart.getColumnCount(); i++)
{
values[i] = curPart.getString(i);
}
if(values[3].equals("image/jpeg"))
{
mms_image.add(GetMmsAttachment(values[0],values[12],values[4]));
}else{
mms_image.add("null");
}
}
so, please guide me how to get all the details using one cusor if possible.
You can try the solution and url provided here.
And may i know why you need 2 cursor ? I assume there is some mms without image attached so that's the reason you get a different count.
I have created a table and trying to fetch data from it using a cursor as follow:
public Cursor getcontent() {
Cursor d = database.query(DatabaseHandler.Table_Name2,allColumns,selection, null, null,null,null);
return d;
}
Cursor r = X.getcontent();
if (r.getCount() > 0) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext()==true);
r.close();
} else {
Log.i("TAG"," No value found");
}
}
I am showing the result in the TextView to see what data it is fetched. My problem is when I run this code sometimes it shows the data in the TextView, whatever it has fetched and sometimes it doesn't. Its a 50:50 ratio, according to me it should show fetched values every time as data is fetched every time I don't know what is wrong here, can someone tell me what's the issue here?
Check Whether Cursor you are getting is Null or not . and if yes then What is the Count of Cursor. you can Do it by Below Way.
Cursor r = X.getcontent();
if ((r != null) && (r.getCount() > 0)) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
r.close();
} else {
Log.i("TAG"," No value found inside Cursor");
}
try like this
Cursor r = X.getcontent();
try {
if (r.moveToFirst()) {
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
}
} finally {
if(r!=null) {
r.close();
}
}