Android: Get updated and deleted contact only - android

I am developing an application in which i am working on Android Contacts and not able to move ahead. In app the need of application is that the contact which is updated should send to server or the contact which is deleted should send to server for sync.
I am using the contact service as:
public class ContactService extends Service {
private int mContactCount;
Cursor cursor = null;
static ContentResolver mContentResolver = null;
// Content provider authority
public static final String AUTHORITY = "com.android.contacts";
// Account typek
public static final String ACCOUNT_TYPE = "com.example.myapp.account";
// Account
public static final String ACCOUNT = "myApp";
// Instance fields
Account mAccount;
Bundle settingsBundle;
#Override
public void onCreate() {
super.onCreate();
// Get contact count at start of service
mContactCount = getContactCount();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Get contact count at start of service
this.getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
private int getContactCount() {
try {
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null) {
return cursor.getCount();
} else {
cursor.close();
return 0;
}
} catch (Exception ignore) {
} finally {
cursor.close();
}
return 0;
}
private ContentObserver mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
this.onChange(selfChange, null);
}
#Override
public void onChange(boolean selfChange, Uri uri) {
new changeInContact().execute();
}
};
public class changeInContact extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<Integer> arrayListContactID = new ArrayList<Integer>();
int currentCount = getContactCount();
if (currentCount > mContactCount) {
// Contact Added
} else if (currentCount < mContactCount) {
// Delete Contact
} else if (currentCount == mContactCount) {
// Update Contact
}
mContactCount = currentCount;
return "";
}
#Override
protected void onPostExecute(String result) {
contactService = false;
} // End of post
}
}
The issues i am facing are as follows :
A: In the above code for getting the recently updated contact i need to check the Version of each contact from device with my database stored version of contacts. Which took much time for large amount of contacts.
B. For getting deleted contact i need to check that the data for the Raw id stored in my database is present in device or not. If not then the contact is deleted. It also take too much time to check whole contacts.
But the same thing contact refresh is done in whats app in very few seconds like 2 to three seconds...
EDIT :
In the above code in following module :
if (currentCount > mContactCount) {
// Contact Added
Log.d("In","Add");
} else if (currentCount < mContactCount) {
// Delete Contact
Log.d("In","Delete");
} else if (currentCount == mContactCount) {
// Update Contact
Log.d("In","Update");
}
I put the log. So the update module is called many times, and also when i do add or delete that time too...
Please guide me and suggest me what to do to reduce the timing for the above tasks...

use the below query to get all the deleted and updated contacts.
public static final String ACCOUNT_TYPE = "com.android.account.youraccounttype"
public static final String WHERE_MODIFIED = "( "+RawContacts.DELETED + "=1 OR "+
RawContacts.DIRTY + "=1 ) AND "+RawContacts.ACCOUNT_TYPE+" = '"+ ACCOUNT_TYPE+"'";
c = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
null,
WHERE_MODIFIED,
null,
null);

Related

Android - Cancel notifications from other apps

I am trying to make a launcher which automatically cancels the notifications of some specific apps (whose package name is stored in variable label) registered in the SQLite database.
I have retrieved data from database in the NotificationListenerService onCreate() Method and cancelled the notification as soon as the are posted.
I have granted permissions to my NotificationListenerService to access notification content. But still when a new notification comes it doesn't gets logged.
My NotificationListenerService class looks like this:
public class AppsNotificationListenerService extends NotificationListenerService {
AppsDbHelper appsDbHelper;
SQLiteDatabase db;
ArrayList<AppItem> apps;
#Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
#Override
public void onCreate() {
super.onCreate();
appsDbHelper = new AppsDbHelper(this);
db = appsDbHelper.getReadableDatabase();
apps = new ArrayList<AppItem>();
Cursor cursor = db.query(Constants.AppsEntry.TABLE_NAME,null, null,
null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
AppItem app = new AppItem();
app.label = cursor.getString(2);
app.name = cursor.getString(1);
int use = cursor.getInt(3);
if(use == 1){
app.isUseful=true;
}else{
app.isUseful=false;
}
if(!app.isUseful){
apps.add(app);
}
} while (cursor.moveToNext());
}
cursor.close();
}
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
Log.i("NotifListenerService", "Notification Posted");
Log.i("NotifListenerService", sbn.getId()+" "+sbn.getKey()+" "+sbn.getPackageName());
String packageName = sbn.getPackageName();
for(AppItem app : apps){
if(packageName.equals(app.label)){
cancelNotification(sbn.getKey());
}
}
}
}
What am I doing wrong?

How to know that contact is deleted/updated/added and which contact has been newly added

I am using a content observer to know that there is a change made to contact phonebook of the device but I am not getting the exact task done like whether the contact has been added, deleted or updated and what is the value of the modified contact.
// Service running in background which always run and check to know that content has been changed
public class ContactChange extends Service {
ContactObserver observer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
observer = new ContactObserver(new Handler(),getApplicationContext());
// TODO Auto-generated method stub
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, false, observer);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(observer);
}
}
//Content observer where we get to know that changes has made to the contact phonebook
public class ContactObserver extends ContentObserver {
private Context mContext;
DataBaseCurdOperation dataBaseCurdOperation;
ApiInterface apiInterface;
MyPrefs myPrefs;
ArrayList<InviteList> inviteArrayList;
public ContactObserver(Handler handler, Context context) {
super(handler);
this.mContext = context;
dataBaseCurdOperation = new DataBaseCurdOperation(mContext);
myPrefs = new MyPrefs(mContext);
apiInterface = ServiceGenerator.createService(ApiInterface.class, Config.BASE_URL_1);
inviteArrayList = new ArrayList<InviteList>();
}
#Override
public void onChange(boolean selfChange) {
this.onChange(selfChange, null);
}
#Override
public void onChange(boolean selfChange, Uri uri) {
Logger.LogError("URI", uri.toString());
boolean hasContactPermission = (ContextCompat.checkSelfPermission(mContext,
android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED);
if (hasContactPermission) {
SavingContactsActivity savingContactsActivity = new SavingContactsActivity(mContext);
savingContactsActivity.execute();
new InviteApiCall().execute();
}
}
Taking this approach and it is giving the contact whether it is added or updated not got the solution for deleted but surely will post the answer of deleted soon....
And I worked on the database after that
public class ContactSyncObserver extends ContentObserver {
Context mContext;
DataBaseCurdOperation dataBaseCurdOperation;
MyPrefs myPrefs;
public ContactSyncObserver(Handler handler, Context mContext) {
super(handler);
this.mContext = mContext;
dataBaseCurdOperation = new DataBaseCurdOperation(mContext);
myPrefs = new MyPrefs(mContext);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
boolean hasContactPermission = (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED);
if (hasContactPermission) {
try {
Cursor cursor = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP + " Desc");
if (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Logger.LogError("contactId", myPrefs.getContactId());
String name = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String rawContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
String phoneNumber = null;
String hasPhoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhoneNumber) > 0) {
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
while (phones.moveToNext()) {
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("Number", phoneNumber);
}
phones.close();
}
if (phoneNumber != null) {
phoneNumber = phoneNumber.replaceAll(" ", "");
}
if (dataBaseCurdOperation.checkIsContactIdExist(id)) {
if (!myPrefs.getContactId().equals(id)) {
dataBaseCurdOperation.updateNewNumber(id, phoneNumber, name, "updated");
UtilHandler.TriggerRefresh();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
myPrefs.setContactId("0");
}
}, 3000);
}
} else {
dataBaseCurdOperation.insertServerContact(id, name, phoneNumber, "inserted", "newNumber", "newName");
UtilHandler.TriggerRefresh(); // triggering my sync adapter here...
}
myPrefs.setContactId(id);
}
} catch (Exception e) {
Logger.LogError("Contact Exception", "occured");
}
}
}
}

BroadcastReceiver to listen when a contact added or deleted from favorite/stared

Is there a way to listen/handle at the time when a contact is added/deleted from favorite/starred contact list.
I have checked for onChange(). But its not handling the Favorite/Starred settings.
There is a default contact observer .. I hope its helpful for you
public class MyCOntentObserver extends ContentObserver {
public MyCOntentObserver() {
super(null);
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
final int currentCount = getContactCount();
// Get count from your sqlite database
int mContactCount = getContactOWNCount();
if (currentCount < mContactCount) {
// DELETE HAPPEN.
Log.e("Status", "Deletion");
//contactDBOperaion.SyncContacts(1);
} else if (currentCount == mContactCount) {
// UPDATE HAPPEN.
// contactDBOperaion.SyncContacts(0);
} else {
// INSERT HAPPEN.
Log.e("Status", "Insertion");
// contactDBOperaion.SyncContacts(2);
}
Log.e("", "~~~~~~" + selfChange);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
}

Android ContentObserver: How to reach only new updated data?

I register SMS ContentObserver in my app. I want to update my ArrayList onChange with MessageID. This is my ObServer code..
public class SmsObserver extends ContentObserver {
private Context mContext;
private String contactId = "", contactName = "";
private String smsBodyStr = "", phoneNoStr = "";
private long smsDatTime = System.currentTimeMillis();
static final Uri SMS_STATUS_URI = Uri.parse("content://sms");
public SmsObserver(Handler handler, Context ctx) {
super(handler);
mContext = ctx;
}
public boolean deliverSelfNotifications() {
return true;
}
public void onChange(boolean selfChange) {
try{
Cursor sms_sent_cursor = mContext.getContentResolver().query(SMS_STATUS_URI, null, null, null, null);
if (sms_sent_cursor != null) {
if (sms_sent_cursor.moveToFirst()) {
String protocol = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("protocol"));
if(protocol == null){
int type = sms_sent_cursor.getInt(sms_sent_cursor.getColumnIndex ("type"));
if(type == 2){
smsBodyStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")).trim();
phoneNoStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")).trim();
smsDatTime = sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date"));
}
}
}
} else {
Log.e("Info","Send Cursor is Empty");
}
} catch(Exception sggh) {
Log.e("Error", "Error on onChange : "+sggh.toString());
}
super.onChange(selfChange);
}
}
But, I am sending two messages. The first one is the phone closed. The second is the phone open. The first update is the latter. The second update is the first I sent the phone opens. With this ObServer I can access only the most recent post. Showing only the most recent data. How can I get the new updated data?

I have problems when using sqlite inside AsyncTask in android?

I face two main problems when using a sqlite command inside an AsncTask in android.
When I execute a select command on the first try I get no results but on the second try (loading a activity that has this Asynctask) I do get results.
Sometimes I get an error that the database is not closed despite that it is already closed/
What is the problem with this?
UPDATE:
This is the code that retrive data from database (db.getAllMessage)
private ArrayList<FriendMessagesResulted> getMessagesFromCach(Context c){
FriendMessagesResulted messagesResulted1 = new FriendMessagesResulted();
DBAdapter db = new DBAdapter(c);
Cursor c1;
db.open();
c1 = db.getAllMessage(Settings.getCurrentUserId(c),Integer.parseInt(fId));
Log.d("***Database count",c1.getCount()+" from: "+Settings.getCurrentUserId(c)+" to:"+Integer.parseInt(fId));
c1.moveToFirst();
if(c1.getCount()>0)
status=true;
if (messagesResultedList == null) {
messagesResultedList = new ArrayList<FriendMessagesResulted>();
}
else
messagesResultedList.clear();
while (c1.isAfterLast() == false) {
if(Integer.parseInt(c1.getString(0))>maxId)
maxId=Integer.parseInt(c1.getString(0));
messagesResulted1.set_mId(Integer.parseInt(c1.getString(0)));
messagesResulted1.set_msgTxt("MD:"+c1.getString(3));
messagesResulted1.set_MessageTime(c1.getString(4));
messagesResulted1.set_dir(c1.getString(5));
messagesResultedList.add(messagesResulted1);
c1.moveToNext();
}
db.close();
c1.close();
return messagesResultedList;
}
and this the code for AsyncTask, where I call get getMessagesFromCach method
private void getMessages(final Context c)
{
handler = new Handler();
r=new Runnable() {
public void run() {
class RecentMessageLoader extends AsyncTask<Void, Void, ArrayList<FriendMessagesResulted>>{
ArrayList<FriendMessagesResulted> messagesResultedList=null;
#Override
protected ArrayList<FriendMessagesResulted> doInBackground(Void... params) {
if(!finishLoadingPastMessages)
{
messagesResultedList=getMessagesFromCach(c);
if(!status){
Log.d("Where are you","I'm in JSON");
messagesResultedList=getMessagesFromJSON(c);
}
}
else{
Log.d("Where are you","I'm in Recent messages");
messagesResultedList=getRecentMessages(c,Settings.getCurrentUserId(c),Integer.parseInt(fId));
}
return messagesResultedList;
}
protected void onPostExecute( ArrayList<FriendMessagesResulted> FMRList ) {
// to disappear loading message
d.dismiss();
finishLoadingPastMessages=true;
if(FMRList!=null){
for(int i=FMRList.size()-1;i>=0;i--)
addMessage(FMRList.get(i),c);
}
handler.postDelayed(r, 2000);
}
}
new RecentMessageLoader().execute();
}
};
handler.post(r);
}
UPDATE 2 : Cach class ..
public class Cach {
static DBAdapter db;
public Cach(Context c)
{
}
public static void AddMessages(Context c,
int id,
int fromId,
int toId,
String message,
String dir,
String MessageTime)
{
db = new DBAdapter(c);
db.open();
long id2;
id2 = db.insertMessage(id, fromId, toId, message, dir,MessageTime);
db.close();
}
}
It seems the problem is with the type of variables you are using.. there must be Static variables of instance variables which are getting set from many sources... try not to use static variables and use local variables I mean in the methods implicitly.

Categories

Resources