Example usage for android.app Notification FLAG_AUTO_CANCEL

List of usage examples for android.app Notification FLAG_AUTO_CANCEL

Introduction

In this page you can find the example usage for android.app Notification FLAG_AUTO_CANCEL.

Prototype

int FLAG_AUTO_CANCEL

To view the source code for android.app Notification FLAG_AUTO_CANCEL.

Click Source Link

Document

Bit to be bitwise-ored into the #flags field that should be set if the notification should be canceled when it is clicked by the user.

Usage

From source file:de.taxilof.UulmLoginAgent.java

/**
 * notify the User in Statusbar/*from   www.  j a v  a  2 s.co  m*/
 */
private void notify(String subject, String message, boolean errorIcon) {
    // build notification with notifyString
    Notification notifyDetails;
    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (errorIcon) {
        notifyDetails = new Notification(R.drawable.icon_red, subject, System.currentTimeMillis());
    } else {
        notifyDetails = new Notification(R.drawable.icon, subject, System.currentTimeMillis());
    }
    PendingIntent myIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    notifyDetails.setLatestEventInfo(context, subject, message, myIntent);
    notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}

From source file:com.airbop.client.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//* ww w .java  2  s. c  o m*/
private static void generateNotification(Context context, String title, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if ((title == null) || (title.equals(""))) {
        title = context.getString(R.string.app_name);
    }
    Intent notificationIntent = new Intent(context, DemoActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(intent).setSmallIcon(icon).setWhen(when)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message)).build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}

From source file:com.nanostuffs.yurdriver.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from  w w w  .j a  v a 2  s .co  m
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MapActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(AndyConstants.NOTIFICATION_ID, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();

}

From source file:com.mutu.gpstracker.streaming.CustomUpload.java

private void notifyError(Context context, Exception e) {
    Log.e(TAG, "Custom upload failed", e);
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);

    int icon = R.drawable.ic_maps_indicator_current_position;
    CharSequence tickerText = context.getText(R.string.customupload_failed);
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, tickerText, when);

    Context appContext = context.getApplicationContext();
    CharSequence contentTitle = tickerText;
    CharSequence contentText = e.getMessage();
    Intent notificationIntent = new Intent(context, CustomUpload.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(appContext, contentTitle, contentText, contentIntent);
    notification.flags = Notification.FLAG_AUTO_CANCEL;

    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

From source file:com.sip.pwc.sipphone.service.Downloader.java

@Override
protected void onHandleIntent(Intent intent) {
    HttpGet getMethod = new HttpGet(intent.getData().toString());
    int result = Activity.RESULT_CANCELED;
    String outPath = intent.getStringExtra(EXTRA_OUTPATH);
    boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
    int icon = intent.getIntExtra(EXTRA_ICON, 0);
    String title = intent.getStringExtra(EXTRA_TITLE);
    boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));

    // Build notification
    Builder nb = new Builder(this);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentTitle(title);/* ww w.ja v a 2 s .  c o m*/
    nb.setSmallIcon(android.R.drawable.stat_sys_download);
    nb.setOngoing(true);
    Intent i = new Intent(this, SipHome.class);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));

    RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.download_notif);
    contentView.setImageViewResource(R.id.status_icon, icon);
    contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
    contentView.setProgressBar(R.id.status_progress, 50, 0, false);
    contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
    nb.setContent(contentView);

    final Notification notification = showNotif ? nb.build() : null;
    notification.contentView = contentView;
    if (!TextUtils.isEmpty(outPath)) {
        try {
            File output = new File(outPath);
            if (output.exists()) {
                output.delete();
            }

            if (notification != null) {
                notificationManager.notify(NOTIF_DOWNLOAD, notification);
            }
            ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
                private int oldState = 0;

                @Override
                public void run(long progress, long total) {
                    //Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
                    int newState = (int) Math.round(progress * 50.0f / total);
                    if (oldState != newState) {

                        notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
                        notificationManager.notify(NOTIF_DOWNLOAD, notification);
                        oldState = newState;
                    }

                }
            });
            boolean hasReply = client.execute(getMethod, responseHandler);

            if (hasReply) {

                if (checkMd5) {
                    URL url = new URL(intent.getData().toString().concat(".md5sum"));
                    InputStream content = (InputStream) url.getContent();
                    if (content != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(content));
                        String downloadedMD5 = "";
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            throw new IOException("md5_verification : no sum on server");
                        }
                        if (!MD5.checkMD5(downloadedMD5, output)) {
                            throw new IOException("md5_verification : incorrect");
                        }
                    }
                }
                PendingIntent pendingIntent = (PendingIntent) intent
                        .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + outPath);
                } catch (IOException e) {
                    Log.e(THIS_FILE, "Unable to make the apk file readable", e);
                }

                Log.d(THIS_FILE, "Download finished of : " + outPath);
                if (pendingIntent != null) {

                    notification.contentIntent = pendingIntent;
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.icon = android.R.drawable.stat_sys_download_done;
                    notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
                    notification.contentView.setTextViewText(R.id.status_text,
                            getResources().getString(R.string.done)
                                    // TODO should be a parameter of this class
                                    + " - Click to install");
                    notificationManager.notify(NOTIF_DOWNLOAD, notification);

                    /*
                    try {
                       pendingIntent.send();
                         notificationManager.cancel(NOTIF_DOWNLOAD);
                    } catch (CanceledException e) {
                       Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
                    }
                    */
                } else {
                    Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
                }

                result = Activity.RESULT_OK;
            }
        } catch (IOException e) {
            Log.e(THIS_FILE, "Exception in download", e);
        }
    }

    if (result == Activity.RESULT_CANCELED) {
        notificationManager.cancel(NOTIF_DOWNLOAD);
    }
}

From source file:com.sonetel.service.Downloader.java

@Override
protected void onHandleIntent(Intent intent) {
    HttpGet getMethod = new HttpGet(intent.getData().toString());
    int result = Activity.RESULT_CANCELED;
    String outPath = intent.getStringExtra(EXTRA_OUTPATH);
    boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
    int icon = intent.getIntExtra(EXTRA_ICON, 0);
    String title = intent.getStringExtra(EXTRA_TITLE);
    boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));

    // Build notification
    Builder nb = new NotificationCompat.Builder(this);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentTitle(title);/*from   w w w.j a  va2 s. c om*/
    nb.setSmallIcon(android.R.drawable.stat_sys_download);
    nb.setOngoing(true);
    Intent i = new Intent(this, SipHome.class);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));

    RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.download_notif);
    contentView.setImageViewResource(R.id.status_icon, icon);
    contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
    contentView.setProgressBar(R.id.status_progress, 50, 0, false);
    contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
    nb.setContent(contentView);

    final Notification notification = showNotif ? nb.getNotification() : null;
    notification.contentView = contentView;
    if (!TextUtils.isEmpty(outPath)) {
        try {
            File output = new File(outPath);
            if (output.exists()) {
                output.delete();
            }

            if (notification != null) {
                notificationManager.notify(NOTIF_DOWNLOAD, notification);
            }
            ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
                private int oldState = 0;

                @Override
                public void run(long progress, long total) {
                    //Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
                    int newState = (int) Math.round(progress * 50.0f / total);
                    if (oldState != newState) {

                        notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
                        notificationManager.notify(NOTIF_DOWNLOAD, notification);
                        oldState = newState;
                    }

                }
            });
            boolean hasReply = client.execute(getMethod, responseHandler);

            if (hasReply) {

                if (checkMd5) {
                    URL url = new URL(intent.getData().toString().concat(".md5sum"));
                    InputStream content = (InputStream) url.getContent();
                    if (content != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(content));
                        String downloadedMD5 = "";
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            throw new IOException("md5_verification : no sum on server");
                        }
                        if (!MD5.checkMD5(downloadedMD5, output)) {
                            throw new IOException("md5_verification : incorrect");
                        }
                    }
                }
                PendingIntent pendingIntent = (PendingIntent) intent
                        .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + outPath);
                } catch (IOException e) {
                    Log.e(THIS_FILE, "Unable to make the apk file readable", e);
                }

                Log.d(THIS_FILE, "Download finished of : " + outPath);
                if (pendingIntent != null) {

                    notification.contentIntent = pendingIntent;
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.icon = android.R.drawable.stat_sys_download_done;
                    notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
                    notification.contentView.setTextViewText(R.id.status_text,
                            getResources().getString(R.string.done)
                                    // TODO should be a parameter of this class
                                    + " - Click to install");
                    notificationManager.notify(NOTIF_DOWNLOAD, notification);

                    /*
                    try {
                       pendingIntent.send();
                         notificationManager.cancel(NOTIF_DOWNLOAD);
                    } catch (CanceledException e) {
                       Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
                    }
                    */
                } else {
                    Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
                }

                result = Activity.RESULT_OK;
            }
        } catch (IOException e) {
            Log.e(THIS_FILE, "Exception in download", e);
        }
    }

    if (result == Activity.RESULT_CANCELED) {
        notificationManager.cancel(NOTIF_DOWNLOAD);
    }
}

From source file:com.csipsimple.service.Downloader.java

@Override
protected void onHandleIntent(Intent intent) {
    HttpGet getMethod = new HttpGet(intent.getData().toString());
    int result = Activity.RESULT_CANCELED;
    String outPath = intent.getStringExtra(EXTRA_OUTPATH);
    boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
    int icon = intent.getIntExtra(EXTRA_ICON, 0);
    String title = intent.getStringExtra(EXTRA_TITLE);
    boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));

    // Build notification
    Builder nb = new NotificationCompat.Builder(this);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentTitle(title);//from w  w w  .  j  a  v  a2 s.com
    nb.setSmallIcon(android.R.drawable.stat_sys_download);
    nb.setOngoing(true);
    Intent i = new Intent(this, SipHome.class);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));

    RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.download_notif);
    contentView.setImageViewResource(R.id.status_icon, icon);
    contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
    contentView.setProgressBar(R.id.status_progress, 50, 0, false);
    contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
    nb.setContent(contentView);

    final Notification notification = showNotif ? nb.build() : null;
    notification.contentView = contentView;
    if (!TextUtils.isEmpty(outPath)) {
        try {
            File output = new File(outPath);
            if (output.exists()) {
                output.delete();
            }

            if (notification != null) {
                notificationManager.notify(NOTIF_DOWNLOAD, notification);
            }
            ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
                private int oldState = 0;

                @Override
                public void run(long progress, long total) {
                    //Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
                    int newState = (int) Math.round(progress * 50.0f / total);
                    if (oldState != newState) {

                        notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
                        notificationManager.notify(NOTIF_DOWNLOAD, notification);
                        oldState = newState;
                    }

                }
            });
            boolean hasReply = client.execute(getMethod, responseHandler);

            if (hasReply) {

                if (checkMd5) {
                    URL url = new URL(intent.getData().toString().concat(".md5sum"));
                    InputStream content = (InputStream) url.getContent();
                    if (content != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(content));
                        String downloadedMD5 = "";
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            throw new IOException("md5_verification : no sum on server");
                        }
                        if (!MD5.checkMD5(downloadedMD5, output)) {
                            throw new IOException("md5_verification : incorrect");
                        }
                    }
                }
                PendingIntent pendingIntent = (PendingIntent) intent
                        .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + outPath);
                } catch (IOException e) {
                    Log.e(THIS_FILE, "Unable to make the apk file readable", e);
                }

                Log.d(THIS_FILE, "Download finished of : " + outPath);
                if (pendingIntent != null) {

                    notification.contentIntent = pendingIntent;
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.icon = android.R.drawable.stat_sys_download_done;
                    notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
                    notification.contentView.setTextViewText(R.id.status_text,
                            getResources().getString(R.string.done)
                                    // TODO should be a parameter of this class
                                    + " - Click to install");
                    notificationManager.notify(NOTIF_DOWNLOAD, notification);

                    /*
                    try {
                       pendingIntent.send();
                         notificationManager.cancel(NOTIF_DOWNLOAD);
                    } catch (CanceledException e) {
                       Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
                    }
                    */
                } else {
                    Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
                }

                result = Activity.RESULT_OK;
            }
        } catch (IOException e) {
            Log.e(THIS_FILE, "Exception in download", e);
        }
    }

    if (result == Activity.RESULT_CANCELED) {
        notificationManager.cancel(NOTIF_DOWNLOAD);
    }
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

@SuppressWarnings("deprecation")
public Notification createNotification(Bundle settings, JSONObject obj) {

    // notifications[i] = api.normalizeAPI({
    // 'string': {
    // mandatory: ['title', 'body'],
    // defaults: {'icon':'icon'}
    // },//www  . j a  va  2s. co m
    //
    // 'number': {
    // mandatory: ['id', 'timeMillisSince1970'],
    // // the number of ms after which we start prioritising more recent
    // things above you.
    // defaults: {'epsilon': 1000 * 60 * 24 * 365}
    // },
    //
    // 'boolean': {
    // defaults: {
    // 'vibrate': false,
    // 'sound': false
    // }
    // }

    int icon = settings.getInt("notification_icon", -1);
    if (icon == -1) {
        Log.e(C.TAG, "Need a notification_icon resource in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    Notification n = new Notification();
    n.icon = icon;
    n.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    long alarmTime = obj.optLong("timeMillisSince1970");
    long displayTime = obj.optLong("displayTimestamp", alarmTime);
    n.when = displayTime;
    n.tickerText = obj.optString("body");
    n.setLatestEventInfo(mContext, obj.optString("title"), obj.optString("body"), null);

    if (obj.optBoolean("vibrate")) {
        n.defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (obj.optBoolean("sound")) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }

    String uriString = settings.getString("content_uri_prefix");
    if (uriString == null) {
        Log.e(C.TAG, "Need a content_uri_prefix in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    if (uriString.contains("%d")) {
        uriString = String.format(uriString, obj.optInt("id"));
    }
    Uri uri = Uri.parse(uriString);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setData(uri);
    n.contentIntent = PendingIntent.getActivity(mContext, 23, intent, PendingIntent.FLAG_ONE_SHOT);
    return n;
}

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/* w ww . j  a v a2s  .c  om*/
    categoryToId = new HashMap<>();
    payeeToId = new HashMap<>();
    methodToId = new HashMap<>();
    accountUuidToId = new HashMap<>();
    String uuidFromExtras = extras.getString(KEY_UUID);
    Timber.i("onPerformSync " + extras.toString());

    AccountManager accountManager = AccountManager.get(getContext());

    Exceptional<SyncBackendProvider> backendProviderExceptional = SyncBackendProviderFactory.get(getContext(),
            account);
    SyncBackendProvider backend;
    try {
        backend = backendProviderExceptional.getOrThrow();
    } catch (Throwable throwable) {
        syncResult.databaseError = true;
        AcraHelper.report(throwable instanceof Exception ? ((Exception) throwable) : new Exception(throwable));
        GenericAccountService.deactivateSync(account);
        accountManager.setUserData(account, GenericAccountService.KEY_BROKEN, "1");
        String content = String.format(Locale.ROOT,
                "The backend could not be instantiated.Reason: %s. Please try to delete and recreate it.",
                throwable.getMessage());
        Intent manageIntent = new Intent(getContext(), ManageSyncBackends.class);
        NotificationBuilderWrapper builder = NotificationBuilderWrapper
                .defaultBigTextStyleBuilder(getContext(), "Synchronization backend deactivated", content)
                .setContentIntent(PendingIntent.getActivity(getContext(), 0, manageIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT));
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
                notification);
        return;
    }
    if (!backend.setUp()) {
        syncResult.stats.numIoExceptions++;
        syncResult.delayUntil = 300;
        return;
    }

    String autoBackupFileUri = extras.getString(KEY_UPLOAD_AUTO_BACKUP);
    if (autoBackupFileUri != null) {
        try {
            backend.storeBackup(Uri.parse(autoBackupFileUri));
        } catch (IOException e) {
            String content = getContext().getString(R.string.auto_backup_cloud_failure, autoBackupFileUri,
                    account.name) + " " + e.getMessage();
            Notification notification = NotificationBuilderWrapper.defaultBigTextStyleBuilder(getContext(),
                    getContext().getString(R.string.pref_auto_backup_title), content).build();
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
                    notification);
        }
        return;
    }

    Cursor c;

    String[] selectionArgs;
    String selection = KEY_SYNC_ACCOUNT_NAME + " = ?";
    if (uuidFromExtras != null) {
        selection += " AND " + KEY_UUID + " = ?";
        selectionArgs = new String[] { account.name, uuidFromExtras };
    } else {
        selectionArgs = new String[] { account.name };
    }
    String[] projection = { KEY_ROWID };
    try {
        c = provider.query(TransactionProvider.ACCOUNTS_URI, projection,
                selection + " AND " + KEY_SYNC_SEQUENCE_LOCAL + " = 0", selectionArgs, null);
    } catch (RemoteException e) {
        syncResult.databaseError = true;
        AcraHelper.report(e);
        return;
    }
    if (c == null) {
        syncResult.databaseError = true;
        AcraHelper.report("Cursor is null");
        return;
    }
    if (c.moveToFirst()) {
        do {
            long accountId = c.getLong(0);
            try {
                provider.update(buildInitializationUri(accountId), new ContentValues(0), null, null);
            } catch (RemoteException e) {
                syncResult.databaseError = true;
                AcraHelper.report(e);
                return;
            }
        } while (c.moveToNext());
    }

    try {
        c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection, selectionArgs, null);
    } catch (RemoteException e) {
        syncResult.databaseError = true;
        AcraHelper.report(e);
        return;
    }
    if (c != null) {
        if (c.moveToFirst()) {
            do {
                long accountId = c.getLong(0);

                String lastLocalSyncKey = KEY_LAST_SYNCED_LOCAL(accountId);
                String lastRemoteSyncKey = KEY_LAST_SYNCED_REMOTE(accountId);

                long lastSyncedLocal = Long
                        .parseLong(getUserDataWithDefault(accountManager, account, lastLocalSyncKey, "0"));
                long lastSyncedRemote = Long
                        .parseLong(getUserDataWithDefault(accountManager, account, lastRemoteSyncKey, "0"));
                dbAccount.set(org.totschnig.myexpenses.model.Account.getInstanceFromDb(accountId));
                Timber.i("now syncing " + dbAccount.get().label);
                if (uuidFromExtras != null && extras.getBoolean(KEY_RESET_REMOTE_ACCOUNT)) {
                    if (!backend.resetAccountData(uuidFromExtras)) {
                        syncResult.stats.numIoExceptions++;
                        Timber.e("error resetting account data");
                    }
                    continue;
                }
                if (!backend.withAccount(dbAccount.get())) {
                    syncResult.stats.numIoExceptions++;
                    Timber.e("error withAccount");
                    continue;
                }

                if (backend.lock()) {
                    try {
                        ChangeSet changeSetSince = backend.getChangeSetSince(lastSyncedRemote, getContext());

                        if (changeSetSince.isFailed()) {
                            syncResult.stats.numIoExceptions++;
                            Timber.e("error getting changeset");
                            continue;
                        }

                        List<TransactionChange> remoteChanges;
                        lastSyncedRemote = changeSetSince.sequenceNumber;
                        remoteChanges = changeSetSince.changes;

                        List<TransactionChange> localChanges = new ArrayList<>();
                        long sequenceToTest = lastSyncedLocal + 1;
                        while (true) {
                            List<TransactionChange> nextChanges = getLocalChanges(provider, accountId,
                                    sequenceToTest);
                            if (nextChanges.size() > 0) {
                                localChanges.addAll(
                                        Stream.of(nextChanges).filter(change -> !change.isEmpty()).toList());
                                lastSyncedLocal = sequenceToTest;
                                sequenceToTest++;
                            } else {
                                break;
                            }
                        }

                        if (localChanges.size() == 0 && remoteChanges.size() == 0) {
                            continue;
                        }

                        if (localChanges.size() > 0) {
                            localChanges = collectSplits(localChanges);
                        }

                        Pair<List<TransactionChange>, List<TransactionChange>> mergeResult = mergeChangeSets(
                                localChanges, remoteChanges);
                        localChanges = mergeResult.first;
                        remoteChanges = mergeResult.second;

                        if (remoteChanges.size() > 0) {
                            writeRemoteChangesToDb(provider,
                                    Stream.of(remoteChanges)
                                            .filter(change -> !(change.isCreate() && uuidExists(change.uuid())))
                                            .toList(),
                                    accountId);
                            accountManager.setUserData(account, lastRemoteSyncKey,
                                    String.valueOf(lastSyncedRemote));
                        }

                        if (localChanges.size() > 0) {
                            lastSyncedRemote = backend.writeChangeSet(localChanges, getContext());
                            if (lastSyncedRemote != ChangeSet.FAILED) {
                                if (!BuildConfig.DEBUG) {
                                    // on debug build for auditing purposes, we keep changes in the table
                                    provider.delete(TransactionProvider.CHANGES_URI,
                                            KEY_ACCOUNTID + " = ? AND " + KEY_SYNC_SEQUENCE_LOCAL + " <= ?",
                                            new String[] { String.valueOf(accountId),
                                                    String.valueOf(lastSyncedLocal) });
                                }
                                accountManager.setUserData(account, lastLocalSyncKey,
                                        String.valueOf(lastSyncedLocal));
                                accountManager.setUserData(account, lastRemoteSyncKey,
                                        String.valueOf(lastSyncedRemote));
                            }
                        }
                    } catch (IOException e) {
                        Timber.e(e, "Error while syncing ");
                        syncResult.stats.numIoExceptions++;
                    } catch (RemoteException | OperationApplicationException | SQLiteException e) {
                        Timber.e(e, "Error while syncing ");
                        syncResult.databaseError = true;
                        AcraHelper.report(e);
                    } finally {
                        if (!backend.unlock()) {
                            Timber.e("Unlocking backend failed");
                            syncResult.stats.numIoExceptions++;
                        }
                    }
                } else {
                    //TODO syncResult.delayUntil = ???
                    syncResult.stats.numIoExceptions++;
                }
            } while (c.moveToNext());
        }
        c.close();
    }
    backend.tearDown();
}

From source file:com.hybris.mobile.lib.location.geofencing.service.GeofencingIntentService.java

/**
 * Send a notification when a geofence is triggered
 *
 * @param geofence           the geofence triggered
 * @param notification       the notification object
 * @param geofenceTransition the geofence transition type
 *///from  w w  w.j  ava  2s  . c  om
protected void sendNotification(Geofence geofence, GeofenceObject.Notification notification,
        int geofenceTransition) {

    if (notification != null) {

        // Notification
        String notificationContentTitle = notification.getNotificationTitle();
        String notificationContentText = notification.getNotificationText();
        int notificationIconResId = notification.getNotificationIconResId();

        Notification.Builder builder = new Notification.Builder(this);

        builder.setContentTitle(notificationContentTitle).setContentText(notificationContentText);

        if (notificationIconResId > 0) {
            builder.setSmallIcon(notificationIconResId);
        }

        try {
            // Intent on click on the notification
            if (StringUtils.isNotBlank(notification.getIntentClassDestination())) {
                Class<?> intentClassDestination = Class.forName(notification.getIntentClassDestination());

                // Create an explicit content Intent that starts the Activity defined in intentClassDestination
                Intent notificationIntent = new Intent(this, intentClassDestination);

                // Geofence Id to pass to the activity in order to retrieve the object
                if (notification.getIntentBundle() != null) {
                    GeofenceObject.IntentBundle intentBundle = notification.getIntentBundle();
                    notificationIntent.putExtra(intentBundle.getKeyName(), intentBundle.getBundle());

                    // Easter egg :)
                    if (intentBundle.getBundle().getBoolean(GeofencingConstants.EXTRA_PLAY_SOUND)) {
                        MediaPlayer mediaPlayer;
                        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
                            Log.d(TAG, "Playing entering geofence sound");
                            mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.entering_geofence);
                        } else {
                            Log.d(TAG, "Playing exiting geofence sound");
                            mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.leaving_geofence);
                        }

                        mediaPlayer.start();
                    }
                }

                PendingIntent notificationPendingIntent = PendingIntent.getActivity(this,
                        geofence.getRequestId().hashCode(), notificationIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                builder.setContentIntent(notificationPendingIntent);
            }

        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Unable to find class " + notification.getIntentClassDestination() + "."
                    + e.getLocalizedMessage());
        }

        // Constructing the Notification and setting the flag to auto remove the notification when the user click on it
        Notification notificationView;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notificationView = builder.build();
        } else {
            notificationView = builder.getNotification();
        }

        notificationView.flags = Notification.FLAG_AUTO_CANCEL;
        notificationView.defaults = Notification.DEFAULT_ALL;

        // Get an instance of the Notification manager
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        // Issue the notification
        mNotificationManager.notify(UUID.randomUUID().toString().hashCode(), notificationView);
    } else {
        Log.e(TAG, "Notification empty for Geofence " + geofence);
    }

}