您好我正在尝试查找我的Gmail帐户中未读邮件的数量,这是我在谷歌搜索过的,但我没有得到 任何工作的解决方案,最后我发现一个文件来自下面链接我遵循相同的过程,但它返回始终未读邮件计数为0但在Gmail帐户中有2个未读邮件
http://android-developers.blogspot.in/2012/04/gmail-public-labels-api.html
有人可以帮助我,因为我等待3天后的正确解决方案
public static int getGmailCount(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;
}
答案 0 :(得分:1)
我从未尝试过这个,但你可以尝试一下。
public class MainActivity extends AppCompatActivity {
AccountManager accountManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(this);
Account account= getAccount(accountManager);
Log.d("MainActivity","UnreadCount-----> "+getUnreadCount(account.name));
}
public Account getAccount(AccountManager accountManager) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
account = null;
}
return account;
}
public int getUnreadCount(String accountName) {
Cursor cursor = getContentResolver().query(
GmailContract.Labels.getLabelsUri(accountName),
UnreadQuery.PROJECTION, null, null, null
);
try {
if (cursor == null || cursor.isAfterLast()) {
return 0;
}
int unread = 0;
while (cursor.moveToNext()) {
String canonicalName = cursor.getString(UnreadQuery.CANONICAL_NAME);
int unreadInLabel = cursor.getInt(UnreadQuery.NUM_UNREAD_CONVERSATIONS);
if (GmailContract.Labels.LabelCanonicalNames.CANONICAL_NAME_INBOX_CATEGORY_PRIMARY.equals(canonicalName)) {
unread = Math.max(unread, unreadInLabel);
}
}
return unread;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private interface UnreadQuery {
String[] PROJECTION = {
GmailContract.Labels.NUM_UNREAD_CONVERSATIONS,
GmailContract.Labels.CANONICAL_NAME,
};
int NUM_UNREAD_CONVERSATIONS = 0;
int CANONICAL_NAME = 1;
}
}