Android - Cancel notifications from other apps - android

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?

Related

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");
}
}
}
}

Android: Get updated and deleted contact only

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);

java.lang.IllegalArgumentException: URI: content://com.android.contacts, calling user:

I have created contact change observer, when a user any time change their contact need to know what change they did.
Step 1 :
public class ContactChangeObserver extends ContentObserver {
Context mContext;
public ContactChangeObserver(Handler handler, Context ctx) {
super(handler);
mContext = ctx;
}
#Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.e("Content Change", "Added New onChange selfChange");
}
#Override
public void onChange(boolean selfChange, Uri uri) {
Log.e("NoOf Content Change", "Contant Change Happen");
super.onChange(selfChange, uri);
if(mContext != null) {
Log.e("Content Change Name :", "start checking");
AppPreferences appPreferences = new AppPreferences(mContext);
String[] projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if (cursor.moveToFirst()) {
String sender = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String mobileno = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String status = "phone";
MaraContactsManager.getInstance().updateContactDB(mContext, mobileno, sender, status, appPreferences.getCountryCode());
}
}
}
Step 2: have register this by calling at HomeActivity
contactChangeObserver = new ContactChangeObserver(new Handler(),getApplicationContext());
getApplicationContext().getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactChangeObserver);
Step 3: when i change any contact it goes to onChange Methode but I am not getting which contact changes done it says
java.lang.IllegalArgumentException: URI: content://com.android.contacts, calling user:
Please Help

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?

Getting 2 SQLite records for every email received

I'm very new to android, and programming in general. I've got an email receiver using the K9 email client. I'm checking the email for proper formatting and taking the contents of the email and entering it into an SQLite database on the phone. The receiver is working properly. The problem is that when I send a properly formatted message, it makes 2 records from the first email. If I send another message without deleting the first one, it makes 4 records of the second. The third makes 6 records, etc. I know there is probably something obvious that I'm missing but I can't find the problem.
Here is the code:
public class EmailReceiver extends BroadcastReceiver{
private JobsData jobs;
public static final Uri k9uri = Uri.parse("content://com.fsck.k9.messageprovider/inbox_messages/");
static String[] messages_projection = new String[] {"subject", "preview", "unread"};
#Override
public void onReceive(Context context, Intent intent) {
try {
Context mContext = context;
Cursor curSt = mContext.getContentResolver().query(k9uri, messages_projection, "unread='true'", null, null);
curSt.moveToFirst();
String preview = null;
String subject = null;
jobs = new JobsData(context);
int i = 0;
while (!curSt.isAfterLast()) {
subject = curSt.getString(0);
boolean test = subject.startsWith("JOB# ");
if (test) {
boolean check = true;
try {
for (int k = 5; k < subject.length(); k++) {
if (!Character.isDigit(subject.charAt(k))) {
check = false;
break;
}
}
} catch (Exception e) {
} finally {
}
if (check) {
preview = curSt.getString(1);
compareDb(subject.substring(7), preview, context);
}
}
curSt.moveToNext();
}
curSt.close();
} catch (Exception e) {
Toast toast = Toast.makeText(context, e.toString(), Toast.LENGTH_LONG);
toast.show();
}
if (emails != null) {
}
}
private void compareDb (String jobNo, String preview, Context context) {
try {
String[] dbJobs = new String[] {"JobNo"};
SQLiteDatabase db = jobs.getReadableDatabase();
Cursor dbCur = db.query(tableName, dbJobs, null, null, null, null, null);
dbCur.moveToFirst();
while (!dbCur.isAfterLast()) {
if (!jobNo.equals(dbCur.getString(0))) {
jobExtractor(preview, jobNo, context);
}
dbCur.moveToNext();
}
dbCur.close();
} catch (Exception e){
Toast toast = Toast.makeText(context, e.toString(), Toast.LENGTH_LONG);
toast.show();
}
}
private void addJobs(Job job){
SQLiteDatabase db = jobs.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(custName, job.getCustName());
values.put(jobNumber, job.getJobNumber());
values.put(jobType, job.getJobType());
values.put(address, job.getAddress());
values.put(zip, job.getZip());
values.put(contact, job.getContact());
values.put(contactNumber, job.getContactNumber());
values.put(problem, job.getProblem());
db.insertOrThrow(tableName, null, values);
db.close();
}
The "jobextractor" method works fine so I didn't include it. If someone can please help me I would appreciate it.
Thanks
Just a side note. I also want it to only look at unread email but that's not working either. Not a major problem at this point but if you have an answer to that I would be very grateful.
I foundthe problem.
while (!dbCur.isAfterLast()) {
if (!jobNo.equals(dbCur.getString(0))) {
jobExtractor(preview, jobNo, context);
}
dbCur.moveToNext();
}
The problem was here. I was checking to see if the job number matched existing records in the database. It went through each record in the table and added a new job for every record that didn't match. I replaced the jobExctractor line with a boolean check and if the check returned true after the loop I didn't add the job.

Categories

Resources