Example usage for android.content Intent FLAG_ACTIVITY_NO_HISTORY

List of usage examples for android.content Intent FLAG_ACTIVITY_NO_HISTORY

Introduction

In this page you can find the example usage for android.content Intent FLAG_ACTIVITY_NO_HISTORY.

Prototype

int FLAG_ACTIVITY_NO_HISTORY

To view the source code for android.content Intent FLAG_ACTIVITY_NO_HISTORY.

Click Source Link

Document

If set, the new activity is not kept in the history stack.

Usage

From source file:ru.dublgis.androidhelpers.DesktopUtils.java

public static void showApplicationSettings(final Context ctx) {
    try {/*www. java2  s .c  om*/
        final Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setData(Uri.fromParts("package", ctx.getPackageName(), null));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

        ctx.startActivity(intent);
    } catch (final Throwable throwable) {
        Log.e(TAG, "showApplicationSettings throwable: " + throwable);
    }
}

From source file:com.owncloud.android.ui.dialog.RateMeDialog.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Create a view by inflating desired layout
    View v = inflater.inflate(R.layout.rate_me_dialog, container, false);

    Button rateNowButton = v.findViewById(R.id.button_rate_now);
    Button laterButton = v.findViewById(R.id.button_later);
    Button noThanksButton = v.findViewById(R.id.button_no_thanks);
    TextView titleView = v.findViewById(R.id.rate_me_dialog_title_view);

    titleView.setText(String.format(getString(R.string.rate_dialog_title), getString(R.string.app_name)));

    rateNowButton.setOnClickListener(new View.OnClickListener() {
        @Override/* w  w w  .  j  av a2  s.  c  o m*/
        public void onClick(View v) {
            String packageName = getArguments().getString(APP_PACKAGE_NAME);
            Uri uri = Uri.parse(MARKET_DETAILS_URI + packageName);
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);

            /// To count with Play market back stack, After pressing back button,
            /// to taken back to our application, we need to add following flags to intent.
            int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
            } else {
                flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
            }
            goToMarket.addFlags(flags);

            try {
                startActivity(goToMarket);
            } catch (ActivityNotFoundException e) {
                getActivity()
                        .startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PLAY_STORE_URI + packageName)));
            }
            dialog.dismiss();
        }
    });

    laterButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences preferences = getActivity().getSharedPreferences(AppRater.APP_RATER_PREF_TITLE,
                    0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putLong(AppRater.APP_RATER_PREF_DATE_NEUTRAL, System.currentTimeMillis());
            editor.apply();
            dialog.dismiss();
        }
    });

    noThanksButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences preferences = getActivity().getSharedPreferences(AppRater.APP_RATER_PREF_TITLE,
                    0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean(AppRater.APP_RATER_PREF_DONT_SHOW, true);
            editor.apply();
            dialog.dismiss();
        }
    });

    return v;
}

From source file:org.gateshipone.odyssey.playbackservice.managers.OdysseyNotificationManager.java

public void updateNotification(TrackModel track, PlaybackService.PLAYSTATE state,
        MediaSessionCompat.Token mediaSessionToken) {
    if (track != null) {
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        // Open application intent
        Intent contentIntent = new Intent(mContext, OdysseyMainActivity.class);
        contentIntent.putExtra(OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW,
                OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW_NOWPLAYINGVIEW);
        contentIntent.addFlags(/*from  w  w w. j  av a  2s.  co m*/
                Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_HISTORY);
        PendingIntent contentPendingIntent = PendingIntent.getActivity(mContext, NOTIFICATION_INTENT_OPENGUI,
                contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setContentIntent(contentPendingIntent);

        // Set pendingintents
        // Previous song action
        Intent prevIntent = new Intent(PlaybackService.ACTION_PREVIOUS);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PREVIOUS,
                prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(
                R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();

        // Pause/Play action
        PendingIntent playPauseIntent;
        int playPauseIcon;
        if (state == PlaybackService.PLAYSTATE.PLAYING) {
            Intent pauseIntent = new Intent(PlaybackService.ACTION_PAUSE);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, pauseIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_pause_48dp;
        } else {
            Intent playIntent = new Intent(PlaybackService.ACTION_PLAY);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, playIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_play_arrow_48dp;
        }
        NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon,
                "PlayPause", playPauseIntent).build();

        // Next song action
        Intent nextIntent = new Intent(PlaybackService.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_NEXT,
                nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(
                R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();

        // Quit action
        Intent quitIntent = new Intent(PlaybackService.ACTION_QUIT);
        PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_QUIT,
                quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setDeleteIntent(quitPendingIntent);

        mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mNotificationBuilder.setSmallIcon(R.drawable.odyssey_notification);
        mNotificationBuilder.addAction(prevAction);
        mNotificationBuilder.addAction(playPauseAction);
        mNotificationBuilder.addAction(nextAction);
        NotificationCompat.MediaStyle notificationStyle = new NotificationCompat.MediaStyle();
        notificationStyle.setShowActionsInCompactView(1, 2);
        notificationStyle.setMediaSession(mediaSessionToken);
        mNotificationBuilder.setStyle(notificationStyle);
        mNotificationBuilder.setContentTitle(track.getTrackName());
        mNotificationBuilder.setContentText(track.getTrackArtistName());

        // Remove unnecessary time info
        mNotificationBuilder.setWhen(0);

        // Cover but only if changed
        if (mLastTrack == null || !track.getTrackAlbumKey().equals(mLastTrack.getTrackAlbumKey())) {
            mLastTrack = track;
            mLastBitmap = null;
        }

        // Only set image if an saved one is available
        if (mLastBitmap != null) {
            mNotificationBuilder.setLargeIcon(mLastBitmap);
        } else {
            /**
             * Create a dummy placeholder image for versions greater android 7 because it
             * does not automatically show the application icon anymore in mediastyle notifications.
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Drawable icon = mContext.getDrawable(R.drawable.notification_placeholder_256dp);

                Bitmap iconBitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(),
                        Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(iconBitmap);
                DrawFilter filter = new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, 1);

                canvas.setDrawFilter(filter);
                icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                icon.setFilterBitmap(true);

                icon.draw(canvas);
                mNotificationBuilder.setLargeIcon(iconBitmap);

            } else {
                /**
                 * For older android versions set the null icon which will result in a dummy icon
                 * generated from the application icon.
                 */
                mNotificationBuilder.setLargeIcon(null);

            }
        }

        // Build the notification
        mNotification = mNotificationBuilder.build();

        // Check if run from service and check if playing or pause.
        // Pause notification should be dismissible.
        if (mContext instanceof Service) {
            if (state == PlaybackService.PLAYSTATE.PLAYING) {
                ((Service) mContext).startForeground(NOTIFICATION_ID, mNotification);
            } else {
                ((Service) mContext).stopForeground(false);
            }
        }

        // Send the notification away
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

}

From source file:com.crea_si.eviacam.service.SplashActivity.java

private void checkRequisites() {
    if (!Eula.wasAccepted(this)) {
        Eula.acceptEula(this, this);
        return;/* ww  w.j a v  a2  s  .c  o  m*/
    }

    if (checkPermissions()) {
        // If all permissions granted resume service initialization
        // TODO: remove such ugly static method call
        MainEngine.splashReady(isA11YService());

        /**
         * Restart this activity so that it does not show up in recents
         * nor when pressing back button
         */
        Intent dialogIntent = new Intent(this, SplashActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY);
        dialogIntent.putExtra(IS_A11Y_SERVICE_PARAM, isA11YService());
        dialogIntent.putExtra(IS_SECOND_RUN_PARAM, true);
        startActivity(dialogIntent);
    }
}

From source file:com.untie.daywal.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    thisMonthTv = (TextView) findViewById(R.id.this_month_tv);

    Calendar now = Calendar.getInstance();

    Intent intent = getIntent();/*from w  w  w . j a va  2 s .  co m*/
    year = intent.getIntExtra("year", now.get(Calendar.YEAR));
    month = intent.getIntExtra("month", now.get(Calendar.MONTH));
    order = intent.getIntExtra("order", 0);

    if (order == 0) {
        mf = MonthlyFragment.newInstance(year, month);
        getSupportFragmentManager().beginTransaction().add(R.id.monthly, mf).commit();
    } else if (order == 1) {
        mf = MonthlyFragment.newInstance(year, month - 1);
        getSupportFragmentManager().beginTransaction().replace(R.id.monthly, mf).commit();
    }
    mf.setOnMonthChangeListener(new MonthlyFragment.OnMonthChangeListener() {

        @Override
        public void onChange(int year, int month) {
            HLog.d(TAG, CLASS, "onChange " + year + "." + month);
            thisMonthTv.setText(year + " " + (month + 1) + "");

        }

        @Override
        public void onDayClick(OneDayView dayView) {
            int year = dayView.get(Calendar.YEAR);
            int month = dayView.get(Calendar.MONTH);
            int day = dayView.get(Calendar.DAY_OF_MONTH);
            int week = dayView.get(Calendar.DAY_OF_WEEK);

            Intent intent = new Intent(MainActivity.this, PopupActivity.class);
            intent.putExtra("year", year);
            intent.putExtra("month", month);
            intent.putExtra("day", day);
            intent.putExtra("week", week);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            startActivity(intent);
            //overridePendingTransition(0, 0);
        }

        @Override
        public void onDayLongClick(OneDayView dayView) {

            if (dayView.getImage() != null) {
                final Dialog dayPickerDialog = new Dialog(MainActivity.this);
                dayPickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dayPickerDialog.setContentView(R.layout.dialog_image);
                dayPickerDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                dayPickerDialog.getWindow().setBackgroundDrawable((new ColorDrawable(0x7000000)));
                ImageView imageView = (ImageView) dayPickerDialog.findViewById(R.id.image_popup);
                Uri uri = dayView.getImage();
                Glide.with(MainActivity.this).load(uri).centerCrop().into(imageView);
                dayPickerDialog.show();
                //dayPickerDialog.dismiss();
            }
        }
    });

    thisMonthTv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showDayPicker();
        }
    });

}

From source file:org.androidpn.client.SerivceManager.Notifier.java

public void notify(String notificationId, String apiKey, String title, String message, String uri) {
    Log.d(LOGTAG, "notify()...");

    Log.d(LOGTAG, "notificationId=" + notificationId);
    Log.d(LOGTAG, "notificationApiKey=" + apiKey);
    Log.d(LOGTAG, "notificationTitle=" + title);
    Log.d(LOGTAG, "notificationMessage=" + message);
    Log.d(LOGTAG, "notificationUri=" + uri);

    if (isNotificationEnabled()) {
        // Show the toast
        if (isNotificationToastEnabled()) {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }//w  w w. ja  va2  s  .  co m

        // PNNotification
        int ntfyDefaults = Notification.DEFAULT_LIGHTS;
        if (isNotificationSoundEnabled()) {
            ntfyDefaults |= Notification.DEFAULT_SOUND;
        }
        if (isNotificationVibrateEnabled()) {
            ntfyDefaults |= Notification.DEFAULT_VIBRATE;
        }

        Intent intent;
        //launch mainactivity
        if (uri == null || uri.length() <= 0) {
            intent = new Intent(context, MainActivity.class);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(uri));
        }
        /*
        intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        intent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        intent.putExtra(Constants.NOTIFICATION_TITLE, title);
        intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
        intent.putExtra(Constants.NOTIFICATION_URI, uri);*/
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder notification = new Notification.Builder(context).setContentTitle(title)
                .setContentText(message).setSmallIcon(getNotificationIcon()).setDefaults(ntfyDefaults)
                .setContentIntent(contentIntent)
                //.setLargeIcon(R.drawable.notification)
                .setWhen(System.currentTimeMillis()).setTicker(message);

        notify(notification);

        //notification.flags |= PNNotification.FLAG_AUTO_CANCEL;

        //            Intent intent;
        //            if (uri != null
        //                    && uri.length() > 0
        //                    && (uri.startsWith("http:") || uri.startsWith("https:")
        //                            || uri.startsWith("tel:") || uri.startsWith("geo:"))) {
        //                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        //            } else {
        //                String callbackActivityPackageName = sharedPrefs.getString(
        //                        Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, "");
        //                String callbackActivityClassName = sharedPrefs.getString(
        //                        Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");
        //                intent = new Intent().setClassName(callbackActivityPackageName,
        //                        callbackActivityClassName);
        //                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            }

        //notification.setLatestEventInfo(context, title, message,
        //        contentIntent);
        //notificationManager.notify(random.nextInt(), notification);

        //            Intent clickIntent = new Intent(
        //                    Constants.ACTION_NOTIFICATION_CLICKED);
        //            clickIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        //            clickIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        //            clickIntent.putExtra(Constants.NOTIFICATION_TITLE, title);
        //            clickIntent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
        //            clickIntent.putExtra(Constants.NOTIFICATION_URI, uri);
        //            //        positiveIntent.setData(Uri.parse((new StringBuilder(
        //            //                "notif://notification.adroidpn.org/")).append(apiKey).append(
        //            //                "/").append(System.currentTimeMillis()).toString()));
        //            PendingIntent clickPendingIntent = PendingIntent.getBroadcast(
        //                    context, 0, clickIntent, 0);
        //
        //            notification.setLatestEventInfo(context, title, message,
        //                    clickPendingIntent);
        //
        //            Intent clearIntent = new Intent(
        //                    Constants.ACTION_NOTIFICATION_CLEARED);
        //            clearIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        //            clearIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        //            //        negativeIntent.setData(Uri.parse((new StringBuilder(
        //            //                "notif://notification.adroidpn.org/")).append(apiKey).append(
        //            //                "/").append(System.currentTimeMillis()).toString()));
        //            PendingIntent clearPendingIntent = PendingIntent.getBroadcast(
        //                    context, 0, clearIntent, 0);
        //            notification.deleteIntent = clearPendingIntent;
        //
        //            notificationManager.notify(random.nextInt(), notification);

    } else {
        Log.w(LOGTAG, "Notificaitons disabled.");
    }

    datasource = new PNNotificationDataSource(context);
    datasource.open();
    datasource.createNotification(title, message, uri);
    datasource.close();

    //Update the list view

    if (MainActivity.instance != null) {
        MainActivity.instance.resetList();
    }

}

From source file:com.simplifynowsoftware.flickrdemo.FavoritesFragment.java

protected void showPhotos(List<PhotoCommon> photos) {
    if (null == photos) {
        if (FlickrDemoConstants.DEBUG_ENABLE) {
            Log.w("showPhotos", "Failed to show photos, null input");
        }//w  ww . j  a v  a2s . com
    } else {
        final GridView gridView = (GridView) getActivity().findViewById(R.id.favoritesFragment)
                .findViewById(R.id.photosetGridView);

        gridView.setAdapter(new PhotoAdapter(getActivity(), photos));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                PhotoCommon photo = (PhotoCommon) gridView.getItemAtPosition(position);

                final Intent intent = new Intent(getActivity(), PhotoViewer.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra(PhotoViewer.INTENT_EXTRA_PHOTO_URL,
                        FlickrImageUrl.getUrl(photo, FlickrImageUrl.USE_FULL_SIZE));
                intent.putExtra(PhotoViewer.INTENT_EXTRA_PHOTO_ID, photo.getId());
                intent.putExtra(PhotoViewer.INTENT_EXTRA_PHOTO_SECRET, photo.getSecret());
                startActivity(intent);

                if (FlickrDemoConstants.DEBUG_ENABLE) {
                    Log.i("showPhotos", "Clicked on photo id " + photo.getId());
                }
            }
        });
    }
}

From source file:com.itbooks.app.activities.BaseActivity.java

/**
 * Handler for {@link com.itbooks.bus.DownloadOpenEvent}.
 *
 * @param e//from w  w  w  .  j a  v a  2  s.c  om
 *       Event {@link com.itbooks.bus.DownloadOpenEvent}.
 */
public void onEvent(DownloadOpenEvent e) {
    File pdf = e.getFile();
    try {
        Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
        openFileIntent.setDataAndType(Uri.fromFile(pdf), "application/pdf");
        openFileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(openFileIntent);
    } catch (Exception ex) {
        //Download pdf-reader.
        showDialogFragment(new DialogFragment() {
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                // Use the Builder class for convenient dialog construction
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                        getActivity());
                builder.setTitle(R.string.application_name).setMessage(R.string.msg_no_reader)
                        .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                String pdfReader = "com.adobe.reader";
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW,
                                            Uri.parse("market://details?id=" + pdfReader)));
                                } catch (android.content.ActivityNotFoundException exx) {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                            "https://play.google.com/store/apps/details?id=" + pdfReader)));
                                }
                            }
                        }).setNegativeButton(R.string.btn_not_yet_load, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User cancelled the dialog
                            }
                        });
                // Create the AlertDialog object and return it
                return builder.create();
            }
        }, null);
    }
}

From source file:io.github.pwlin.cordova.plugins.fileopener2.FileOpener2.java

private void _open(String fileArg, String contentType, CallbackContext callbackContext) throws JSONException {
    String fileName = "";
    try {//from w w w  .j a v  a2 s. co m
        CordovaResourceApi resourceApi = webView.getResourceApi();
        Uri fileUri = resourceApi.remapUri(Uri.parse(fileArg));
        fileName = this.stripFileProtocol(fileUri.toString());
    } catch (Exception e) {
        fileName = fileArg;
    }
    File file = new File(fileName);
    if (file.exists()) {
        try {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24) {

                Context context = cordova.getActivity().getApplicationContext();
                path = FileProvider.getUriForFile(context,
                        cordova.getActivity().getPackageName() + ".opener.provider", file);
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                List<ResolveInfo> infoList = context.getPackageManager().queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : infoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, path,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
            /*
             * @see
             * http://stackoverflow.com/questions/14321376/open-an-activity-from-a-cordovaplugin
             */
            cordova.getActivity().startActivity(intent);
            //cordova.getActivity().startActivity(Intent.createChooser(intent,"Open File in..."));
            callbackContext.success();
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put("status", PluginResult.Status.ERROR.ordinal());
            errorObj.put("message", "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put("status", PluginResult.Status.ERROR.ordinal());
        errorObj.put("message", "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:com.atahani.telepathy.ui.fragment.AboutDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View customLayout = inflater.inflate(R.layout.fragment_about_dialog, null);
    //config app version information
    mAppPreferenceTools = new AppPreferenceTools(TApplication.applicationContext);
    AppCompatTextView txAndroidAppVerInfo = (AppCompatTextView) customLayout
            .findViewById(R.id.tx_android_ver_info);
    txAndroidAppVerInfo.setText(String.format(getString(R.string.label_telepathy_for_android),
            mAppPreferenceTools.getTheLastAppVersion()));
    txAndroidAppVerInfo.setOnClickListener(new View.OnClickListener() {
        @Override/*from  ww w .  ja va 2s .  co  m*/
        public void onClick(View v) {
            try {
                //open browser to navigate telepathy website
                Uri telepathyWebSiteUri = Uri.parse("https://github.com/atahani/telepathy-android.git");
                startActivity(new Intent(Intent.ACTION_VIEW, telepathyWebSiteUri));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config google play store link
    AppCompatTextView txRateUsOnGooglePlayStore = (AppCompatTextView) customLayout
            .findViewById(R.id.tx_rate_us_on_play_store);
    txRateUsOnGooglePlayStore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //navigate to market for rate application
            Uri uri = Uri.parse("market://details?id=" + TApplication.applicationContext.getPackageName());
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            // To count with Play market backstack, After pressing back button,
            // to taken back to our application, we need to add following flags to intent.
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            try {
                startActivity(goToMarket);
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (ActivityNotFoundException e) {
                startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
                                + TApplication.applicationContext.getPackageName())));
            }
        }
    });
    //config twitter link
    AppCompatTextView txTwitterLink = (AppCompatTextView) customLayout.findViewById(R.id.tx_twitter_telepathy);
    txTwitterLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                // If Twitter app is not installed, start browser.
                Uri twitterUri = Uri.parse("http://twitter.com/");
                startActivity(new Intent(Intent.ACTION_VIEW, twitterUri));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config privacy link
    AppCompatTextView txPrivacyLink = (AppCompatTextView) customLayout.findViewById(R.id.tx_privacy);
    txPrivacyLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                //open browser to navigate privacy link
                Uri privacyPolicyUri = Uri
                        .parse("https://github.com/atahani/telepathy-android/blob/master/LICENSE.md");
                startActivity(new Intent(Intent.ACTION_VIEW, privacyPolicyUri));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config report bug to open mail application and send bugs report
    AppCompatTextView txReportBug = (AppCompatTextView) customLayout.findViewById(R.id.tx_report_bug);
    txReportBug.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                final Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        getString(R.string.label_report_bug_email_subject));
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailDeviceInformation());
                emailIntent.setData(Uri.parse("mailto:" + getString(R.string.telepathy_report_bug_email)));
                startActivity(Intent.createChooser(emailIntent,
                        getString(R.string.label_report_bug_choose_mail_app)));
                ((TelepathyBaseActivity) getActivity()).setAnimationOnStart();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    //config the about footer image view
    AboutFooterImageView footerImageView = (AboutFooterImageView) customLayout
            .findViewById(R.id.im_delete_user_account);
    footerImageView.setTouchOnImageViewEventListener(new AboutFooterImageView.touchOnImageViewEventListener() {
        @Override
        public void onDoubleTab() {
            try {
                //confirm account delete via alert dialog
                final AlertDialog.Builder confirmAccountDeleteDialog = new AlertDialog.Builder(getActivity());
                confirmAccountDeleteDialog.setTitle(getString(R.string.label_delete_user_account));
                confirmAccountDeleteDialog
                        .setMessage(getString(R.string.label_delete_user_account_description));
                confirmAccountDeleteDialog.setNegativeButton(getString(R.string.action_no), null);
                confirmAccountDeleteDialog.setPositiveButton(getString(R.string.action_yes),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //ok to delete account action
                                final ProgressDialog progressDialog = new ProgressDialog(getActivity());
                                progressDialog.setCancelable(false);
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog
                                        .setMessage(getString(R.string.re_action_on_deleting_user_account));
                                progressDialog.show();
                                TService tService = ((TelepathyBaseActivity) getActivity()).getTService();
                                tService.deleteUserAccount(new Callback<TOperationResultModel>() {
                                    @Override
                                    public void success(TOperationResultModel tOperationResultModel,
                                            Response response) {
                                        if (getActivity() != null && isAdded()) {
                                            //broad cast to close all of the realm  instance
                                            Intent intentToCloseRealm = new Intent(
                                                    Constants.TELEPATHY_BASE_ACTIVITY_INTENT_FILTER);
                                            intentToCloseRealm.putExtra(Constants.ACTION_TO_DO_PARAM,
                                                    Constants.CLOSE_REALM_DB);
                                            LocalBroadcastManager.getInstance(getActivity())
                                                    .sendBroadcastSync(intentToCloseRealm);
                                            mAppPreferenceTools.removeAllOfThePref();
                                            //                                 for sign out google first build GoogleAPIClient
                                            final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(
                                                    TApplication.applicationContext)
                                                            .addApi(Auth.GOOGLE_SIGN_IN_API).build();
                                            googleApiClient.connect();
                                            googleApiClient.registerConnectionCallbacks(
                                                    new GoogleApiClient.ConnectionCallbacks() {
                                                        @Override
                                                        public void onConnected(Bundle bundle) {
                                                            Auth.GoogleSignInApi.signOut(googleApiClient)
                                                                    .setResultCallback(
                                                                            new ResultCallback<Status>() {
                                                                                @Override
                                                                                public void onResult(
                                                                                        Status status) {
                                                                                    //also revoke google access
                                                                                    Auth.GoogleSignInApi
                                                                                            .revokeAccess(
                                                                                                    googleApiClient)
                                                                                            .setResultCallback(
                                                                                                    new ResultCallback<Status>() {
                                                                                                        @Override
                                                                                                        public void onResult(
                                                                                                                Status status) {
                                                                                                            progressDialog
                                                                                                                    .dismiss();
                                                                                                            TelepathyBaseActivity currentActivity = (TelepathyBaseActivity) TApplication.mCurrentActivityInApplication;
                                                                                                            if (currentActivity != null) {
                                                                                                                Intent intent = new Intent(
                                                                                                                        TApplication.applicationContext,
                                                                                                                        SignInActivity.class);
                                                                                                                intent.setFlags(
                                                                                                                        Intent.FLAG_ACTIVITY_CLEAR_TASK
                                                                                                                                | Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                                                                currentActivity
                                                                                                                        .startActivity(
                                                                                                                                intent);
                                                                                                                currentActivity
                                                                                                                        .setAnimationOnStart();
                                                                                                                currentActivity
                                                                                                                        .finish();
                                                                                                            }
                                                                                                        }
                                                                                                    });
                                                                                }
                                                                            });
                                                        }

                                                        @Override
                                                        public void onConnectionSuspended(int i) {
                                                            //do nothing
                                                        }
                                                    });
                                        }
                                    }

                                    @Override
                                    public void failure(RetrofitError error) {
                                        progressDialog.dismiss();
                                        if (getActivity() != null && isAdded()) {
                                            CommonFeedBack commonFeedBack = new CommonFeedBack(
                                                    getActivity().findViewById(android.R.id.content),
                                                    getActivity());
                                            commonFeedBack.checkCommonErrorAndBackUnCommonOne(error);
                                        }
                                    }
                                });
                            }
                        });
                confirmAccountDeleteDialog.show();
            } catch (Exception ex) {
                AndroidUtilities.processApplicationError(ex, true);
                if (isAdded() && getActivity() != null) {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                            getString(R.string.re_action_internal_app_error), Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
    builder.setView(customLayout);
    return builder.create();
}