Android programmatically delete Chrome / default browser cookies, history, searches - android

Like the title. I want to delete cookie, cache of browser of Android by coding in my application. (browser not webview)
Thank you!

In your Activity or Service, add
ContentResolver cR = getContentResolver();
if(Browser.canClearHistory(cR)){
Browser.clearHistory(cR);
Browser.clearSearches(cR);
}
where Browser is the android.provider.Browser class.
This will clear the default browser's history.

Yes it is possible to clear chrome history & searches from your application. Please see below.
/**
* Clear the browser history
*/
private void clearChromeHistory(){
ContentResolver cr = getContentResolver();
Uri historyUri = Uri.parse("content://com.android.chrome.browser/history");
Uri searchesUri = Uri.parse("content://com.android.chrome.browser/searches");
deleteChromeHistoryJava(cr, historyUri, null, null);
deleteChromeHistoryJava(cr, searchesUri, null, null);
}
/**
* Delete chrome browser hisory
* #param cr content resolver
* #param whereClause Uri of the browser history query
* #param projection projection array
* #param selection selection item
*/
private void deleteChromeHistoryJava(ContentResolver cr, Uri whereClause, String[] projection, String selection) {
Cursor mCursor = null;
try {
mCursor = cr.query(whereClause, projection, selection,
null, null);
Log.i("deleteChromeHistoryJava", " Query: " + whereClause);
if (mCursor != null) {
mCursor.moveToFirst();
int count = mCursor.getColumnCount();
String COUNT = String.valueOf(count);
Log.i("deleteChromeHistoryJava", " mCursor count" + COUNT);
String url = "";
if (mCursor.moveToFirst() && mCursor.getCount() > 0) {
while (!mCursor.isAfterLast()) {
url = mCursor.getString(mCursor.getColumnIndex(Browser.BookmarkColumns.URL));
Log.i("deleteChromeHistoryJava", " url: " + url);
mCursor.moveToNext();
}
}
cr.delete(whereClause, selection, null);
Log.i("deleteChromeHistoryJava", " GOOD");
}
} catch (IllegalStateException e) {
Log.i("deleteChromeHistoryJava", " IllegalStateException: " + e.getMessage());
} finally {
if (mCursor != null) mCursor.close();
}
}
Add permissions in manifest
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>
<uses-permission android:name="com.android.browser.permission.WRITE_HISTORY_BOOKMARKS"/>
I have no idea if we can delete the cache/cookies using this, but i will post if i can get any further information.

Related

Query to ContactsContract.Contacts.CONTENT_FILTER_URI doesn't consider all contacts

I'm developing a messaging application and need a list of contacts with search-as-you-type capability.
I used Contacts.CONTENT_URI to get list of all contacts and Contacts.CONTENT_FILTER_URI to get list filtered by name.
All seems to work fine, until some testers reported that they can't find some of their contacts using search feature but can see them when viewing whole list. As I'v mentioned above, different URIs are used in these cases.
Here is the code, which performing query to contacts ContentProvider:
private Cursor getContactsCursorByQuery(ContactsQuery query) {
String orderBy = null;
if (query != null) {
switch (query.getSortOrder()) {
case NAME_ASCENDING: {
orderBy = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " COLLATE NOCASE ASC";
break;
}
case NAME_DESCENDING: {
orderBy = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE NOCASE DESC";
break;
}
default: {
LOG.warn("Unsupported sort order " + query.getSortOrder());
}
}
}
ContentResolver contentResolver = CONTENT_RESOLVER;
Cursor cur;
Uri uri;
if (query != null && !TextUtils.isEmpty(query.getName())) {
// In search mode
uri = ContactsContract.Contacts.CONTENT_FILTER_URI.buildUpon()
.appendEncodedPath(Uri.encode(query.getName()))
.build();
} else {
uri = ContactsContract.Contacts.CONTENT_URI;
}
cur = contentResolver.query(uri,
CONTACTS_LIST_PROJECTION,
null,
null,
orderBy);
LOG.debug("Got cursor by query " + (query != null ? query.toString() : "{}"));
return cur;
}
Trying to figure out what I'm doing wrong I studied sources of contacts application from AOSP and found references to ContactsContract.Directory. After some further investigations I'm ended up with such solution:
- query each directory's CONTENT_FILTER_URI;
- merge result cursors and sort them using slightly modified solution for this question;
private Cursor getContactsCursorByQuery(ContactsQuery query) {
String orderBy = null;
if (query != null) {
switch (query.getSortOrder()) {
case NAME_ASCENDING: {
orderBy = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " COLLATE NOCASE ASC";
break;
}
case NAME_DESCENDING: {
orderBy = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE NOCASE DESC";
break;
}
default: {
LOG.warn("Unsupported sort order " + query.getSortOrder());
}
}
}
ContentResolver contentResolver = CONTENT_RESOLVER;
Cursor cur;
Uri uri;
if (query != null && !TextUtils.isEmpty(query.getName())) {
// In search mode
uri = ContactsContract.Contacts.CONTENT_FILTER_URI.buildUpon()
.appendEncodedPath(Uri.encode(query.getName()))
.build();
Directory[] directories = getDirectories();
LOG.debug("Contacts directories: " + Arrays.toString(directories));
List<Cursor> cursors = new ArrayList<Cursor>();
for (int i = 0; i < directories.length; i++) {
if (directories[i].getId() != ContactsContract.Directory.LOCAL_INVISIBLE) {
Uri queryUri = uri.buildUpon()
.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
String.valueOf(directories[i].getId()))
.build();
LOG.debug("Contacts of directory Uri: " + queryUri.toString());
Cursor tempCur;
tempCur = contentResolver.query(queryUri,
CONTACTS_LIST_PROJECTION,
null,
null,
orderBy);
if (tempCur != null) {
cursors.add(tempCur);
}
}
}
Cursor[] cursorArray = new Cursor[cursors.size()];
cursors.toArray(cursorArray);
cur = new ContactsSortCursor(cursorArray, query.getSortOrder());
} else {
uri = ContactsContract.Contacts.CONTENT_URI;
cur = contentResolver.query(uri,
CONTACTS_LIST_PROJECTION,
null,
null,
orderBy);
}
LOG.debug("Got cursor by query " + (query != null ? query.toString() : "{}"));
return cur;
}
But, unfortunately, issue still persists and I left with no ideas how to fix it. Need your help. Thanks in advance.

Android, media scan doesn't generate thumbnails?

I have image files which don't have thumbnails. (imported from my external carmera using NFC)
I want to create thumbnails for my image picker view. (has to be fast)
At this moment, I'm not even sure "MEDIA SCAN" means "generating thumbnail" or what.
I tried to scan file using mMediaScannerConnection.scanFile(mPath, null);
onScanCompleted gets called and I try to get thumbnail using the following two version of functions.
I get null thumbnailPath for both functions, I don't get why..
private String getThumbnailPath(long imageId) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = MediaStore.Images.Thumbnails.queryMiniThumbnail(cr, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
try {
if (c.moveToNext()) {
int dataId = c.getColumnIndex( Images.Thumbnails.DATA);
String strThumPath = c.getString(dataId);
Log.i("ScanTest", "strThumPath = " + strThumPath );
return strThumPath;
}
} finally {
if (c != null) c.close();
}
return null;
}
private String getThumbnailPath2( long imageId ){
// http://wikicloud.blogspot.kr/2010/10/scanfile.html
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Thumbnails.IMAGE_ID + "= ?" , new String[]{String.valueOf(imageId)}, null);
try {
if (c.moveToNext()) {
int dataId = c.getColumnIndex( Images.Thumbnails.DATA);
String strThumPath = c.getString(dataId);
Log.i("ScanTest", "strThumPath = " + strThumPath );
return strThumPath;
}
} finally {
if (c != null) c.close();
}
return null;
}
-- edit --
Here's how I try to get thumbnails.
first create a mapping from image-id to thumbnail-path.
protected Map getThumbnailPathFromDB() {
Map result = new HashMap();
Cursor thumbCursor = null;
thumbCursor = getContentResolver().query(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
null,
null,
null, null);
if (thumbCursor.moveToFirst()) {
do {
String path = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.MediaColumns.DATA));
long imageId = thumbCursor.getLong(thumbCursor
.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID));
result.put(new Long(imageId), path);
} while(thumbCursor.moveToNext());
}
thumbCursor.close();
return result;
next I iterate all images and try to find thumbnails from the mapping I created above
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(
Images.Media.EXTERNAL_CONTENT_URI, null,
null, null, Images.ImageColumns.DATE_MODIFIED + " DESC");
//thumbnailPathList is the mapping I created above, imageId is the id of image obtained from the cursor
String thumbnailPath = thumbnailPathList.get(new Long(imageId));
// thumbnailPath are occasionally null here!,
I tested my code on about 10 devices.
They all have images which I can't find thumbnails for.

Clear history of Chrome browser

How to clear history of chrome browser. For native browser i use following code -
Browser.clearHistory(getContentResolver());
But this does not work for chrome. How can i clear chrome browser history?
Is it possible?
It work fo me
Uri BOOKMARKS_URI = Uri.parse("content://browser/bookmarks");
String TITLE = "title";
String VISITS = "visits";
String BOOKMARK = "bookmark";
ContentResolver resolver = getContentResolver();
try {
Log.i("DEBUG_", "ContentResolver");
Cursor c = resolver.query(
BOOKMARKS_URI,
null,
null, null, null);
c.moveToFirst();
Log.i("DEBUG_", "Cursor : " + c.toString());
resolver.delete(BOOKMARKS_URI, "bookmark == 1", null);
Log.i("DEBUG_", "ContentResolver delete ");
} catch (IllegalStateException e) {
Log.i("DEBUG_", "IllegalStateException " + e.getMessage());
e.printStackTrace();
}
or
Cursor faves = managedQuery(BOOKMARKS_URI,
requestedColumns,
null, null, null);
Yes it is posssible to clear chrome history from your application. Please see below.
/**
* Clear the browser history
*/
private void clearChromeHistory(){
ContentResolver cr = getContentResolver();
Uri historyUri = Uri.parse("content://com.android.chrome.browser/history");
deleteChromeHistoryJava(cr, historyUri, null, null);
}
/**
* Delete chrome browser hisory
* #param cr content resolver
* #param whereClause Uri of the browser history query
* #param projection projection array
* #param selection selection item
*/
private void deleteChromeHistoryJava(ContentResolver cr, Uri whereClause, String[] projection, String selection) {
Cursor mCursor = null;
try {
mCursor = cr.query(whereClause, projection, selection,
null, null);
Log.i("deleteChromeHistoryJava", " Query: " + whereClause);
if (mCursor != null) {
mCursor.moveToFirst();
int count = mCursor.getColumnCount();
String COUNT = String.valueOf(count);
Log.i("deleteChromeHistoryJava", " mCursor count" + COUNT);
String url = "";
if (mCursor.moveToFirst() && mCursor.getCount() > 0) {
while (!mCursor.isAfterLast()) {
url = mCursor.getString(mCursor.getColumnIndex(Browser.BookmarkColumns.URL));
Log.i("deleteChromeHistoryJava", " url: " + url);
mCursor.moveToNext();
}
}
cr.delete(whereClause, selection, null);
Log.i("deleteChromeHistoryJava", " GOOD");
}
} catch (IllegalStateException e) {
Log.i("deleteChromeHistoryJava", " IllegalStateException: " + e.getMessage());
} finally {
if (mCursor != null) mCursor.close();
}
}
Add permission in manifest
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>
<uses-permission android:name="com.android.browser.permission.WRITE_HISTORY_BOOKMARKS"/>

Fetching all Contacts and showing them in listview

I am showing all contacts in listview and it is working great. But I also want to add image to listview. Searched alot but didn't find any good tutorial. Please suggest some tutorials for showing contact images on listview. Following is my code.
Cursor cur = getContacts();
ListView lv = getListView();
String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME };
adapter = new SimpleCursorAdapter(this,
R.layout.contacts_list_row, cur, fields,
new int[] { R.id.title}, 0);
lv.setAdapter(adapter);
getContacts()
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
Thanks in advance :)
Write a custom list view with ImageView and TextView and get the contact icon image from the Content provider using the bellow code
/**
* #return the photo URI
*/
public Uri getPhotoUri() {
try {
Cursor cur = this.ctx.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
.parseLong(getId()));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
And then check the condition image is available then set to imageview
Uri u = objItem.getPhotoUri();
if (u != null) {
mPhotoView.setImageURI(u);
} else {
mPhotoView.setImageResource(R.drawable.defaultimage);
}
I don't know if you will find a tutorial on how to add images with a Simple adapter...you will probably need to create a custom list adapter.
it's really easy and gives you a huge amount of flexibility. try this that should give a decent starting point.
You will need to create a layout that has an ImageView, and the name, then in the adapter you can set the images and names etc.

MemoryFile.finalize() called while ashmem still open - How to deal with it - Android

I have seen questions at SO regarding the same question, but none of them has an accepted answer.
What exactly is the error informing? Why does this occur?
I have few Cursors in my application, and I did close them, after their work is done. But the error still shows up. What could be the reason?
Here is the code :::
private String fetchContactIdFromPhoneNumber(String phoneNumber) {
// TODO Auto-generated method stub
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cFetch = getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
String contactId = "";
if (cFetch.moveToFirst()) {
cFetch.moveToFirst();
contactId = cFetch.getString(cFetch
.getColumnIndex(PhoneLookup._ID));
}
//System.out.println(contactId);
if(cFetch != null)
{
cFetch.close();
}
return contactId;
}
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
Cursor cursor;
try {
cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
if(cursor != null)
{
cursor.close();
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
This is the code where I use cursors. I have also a contentresolver object. Should I close that as well?
And finally, what is the impact on this error on the application, because, it doesn't seem to interrupt the application's execution.

Categories

Resources