Example usage for android.content Intent resolveActivity

List of usage examples for android.content Intent resolveActivity

Introduction

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

Prototype

public ComponentName resolveActivity(@NonNull PackageManager pm) 

Source Link

Document

Return the Activity component that should be used to handle this intent.

Usage

From source file:me.trashout.fragment.TrashDetailFragment.java

@OnClick({ R.id.trash_detail_cleaned_btn, R.id.trash_detail_still_here_btn, R.id.trash_detail_more_btn,
        R.id.trash_detail_less_btn, R.id.trash_detail_direction_btn, R.id.trash_detail_create_event_btn,
        R.id.trash_detail_send_notification_btn, R.id.trash_detail_report_as_spam_btn,
        R.id.trash_detail_edit_fab, R.id.trash_detail_image })
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.trash_detail_cleaned_btn:
        TrashReportOrEditFragment trashReportOrEditFragmentCleaned = TrashReportOrEditFragment
                .newInstance(mTrash, true, false, false, false);
        getBaseActivity().replaceFragment(trashReportOrEditFragmentCleaned);
        break;/*from   w w  w .  ja v  a2  s. c  o  m*/
    case R.id.trash_detail_still_here_btn:
        TrashReportOrEditFragment trashReportOrEditFragmentStillHere = TrashReportOrEditFragment
                .newInstance(mTrash, false, true, false, false);
        getBaseActivity().replaceFragment(trashReportOrEditFragmentStillHere);
        break;
    case R.id.trash_detail_more_btn:
        TrashReportOrEditFragment trashReportOrEditFragmentMore = TrashReportOrEditFragment.newInstance(mTrash,
                false, false, true, false);
        getBaseActivity().replaceFragment(trashReportOrEditFragmentMore);
        break;
    case R.id.trash_detail_less_btn:
        TrashReportOrEditFragment trashReportOrEditFragmentLess = TrashReportOrEditFragment.newInstance(mTrash,
                false, false, false, true);
        getBaseActivity().replaceFragment(trashReportOrEditFragmentLess);
        break;
    case R.id.trash_detail_direction_btn:
        if (mTrash != null) {
            Uri gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + mTrash.getGps().getLat() + ","
                    + mTrash.getGps().getLng());
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");
            if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                startActivity(mapIntent);
            }
        }
        break;
    case R.id.trash_detail_create_event_btn:
        EventCreateFragment eventCreateFragment = EventCreateFragment.newInstance(getTrashId(),
                mTrash != null ? mTrash.getPosition() : null);
        eventCreateFragment.setTargetFragment(this, 0);
        getBaseActivity().replaceFragment(eventCreateFragment);
        break;
    case R.id.trash_detail_send_notification_btn:
        sendNotificationEmail();
        break;
    case R.id.trash_detail_report_as_spam_btn:
        if (mTrash != null) {
            MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                    .title(R.string.global_validation_warning).content(R.string.trash_spam_comfirmation)
                    .positiveText(android.R.string.yes).negativeText(android.R.string.cancel).autoDismiss(true)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            showProgressDialog();
                            CreateTrashNewSpamService.startForRequest(getContext(),
                                    TRASH_CREATE_SPAM_REQUEST_ID, mTrash.getActivityId(), user.getId());
                        }
                    }).build();

            dialog.show();
        }
        break;
    case R.id.trash_detail_edit_fab:
        TrashReportOrEditFragment trashReportOrEditFragment = TrashReportOrEditFragment.newInstance(mTrash,
                false, false, false, false);
        getBaseActivity().replaceFragment(trashReportOrEditFragment);
        break;
    case R.id.trash_detail_image:
        if (mTrash != null && mTrash.getImages() != null && !mTrash.getImages().isEmpty()) {
            PhotoFullscreenFragment photoFullscreenFragment = PhotoFullscreenFragment.newInstance(mImages, 0);
            getBaseActivity().replaceFragment(photoFullscreenFragment);
        }
        break;
    }
}

From source file:com.example.android.navigationdrawerexample.Controller.PilihanController.java

/**
 @Override/* w ww .  j a v a2s  .c o m*/
 public boolean onPrepareOptionsMenu(Menu menu) {
 // If the nav drawer is open, hide action items related to the content view
 boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
 menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
 return super.onPrepareOptionsMenu(menu);
 }
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action buttons
    switch (item.getItemId()) {
    case R.id.action_websearch:
        // create intent to perform web search for this planet
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
        // catch event that there's no activity to handle intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@Override
protected WebView createViewInstance(final ThemedReactContext reactContext) {
    final ReactWebView webView = new ReactWebView(reactContext);

    /**/*from   w ww  .  j a  v  a 2 s . co m*/
     * cookie?
     * 5.0???cookie,5.0?false
     * 
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
    }

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            reactContext.getCurrentActivity().startActivity(intent);

            //                DownloadManager.Request request = new DownloadManager.Request(
            //                        Uri.parse(url));
            //
            //                request.setMimeType(mimetype);
            //                String cookies = CookieManager.getInstance().getCookie(url);
            //                request.addRequestHeader("cookie", cookies);
            //                request.addRequestHeader("User-Agent", userAgent);
            //                request.allowScanningByMediaScanner();
            ////                request.setTitle()
            //                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            //                request.setDestinationInExternalPublicDir(
            //                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
            //                                url, contentDisposition, mimetype));
            //                DownloadManager dm = (DownloadManager) reactContext.getCurrentActivity().getSystemService(DOWNLOAD_SERVICE);
            //                dm.enqueue(request);
            //                Toast.makeText(reactContext, "...", //To notify the Client that the file is being downloaded
            //                        Toast.LENGTH_LONG).show();

        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage message) {
            if (ReactBuildConfig.DEBUG) {
                return super.onConsoleMessage(message);
            }
            // Ignore console logs in non debug builds.
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile = new File(storageDir, /* directory */
                    imageFileName + ".jpg" /* filename */
            );
            return imageFile;
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent
                    .resolveActivity(reactContext.getCurrentActivity().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    FLog.e(ReactConstants.TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("*/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "?");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            // final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
            // galleryIntent.setType("image/*");
            // final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choose File");
            // reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            if (mVideoView != null) {
                callback.onCustomViewHidden();
                return;
            }

            // Store the view and it's callback for later, so we can dispose of them correctly
            mVideoView = view;
            mCustomViewCallback = callback;

            view.setBackgroundColor(Color.BLACK);
            getRootView().addView(view, FULLSCREEN_LAYOUT_PARAMS);
            webView.setVisibility(View.GONE);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity()
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }

        @Override
        public void onHideCustomView() {
            if (mVideoView == null) {
                return;
            }

            mVideoView.setVisibility(View.GONE);
            getRootView().removeView(mVideoView);
            mVideoView = null;
            mCustomViewCallback.onCustomViewHidden();
            webView.setVisibility(View.VISIBLE);
            //                View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
            //                // Show Status Bar.
            //                int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
            //                decorView.setSystemUiVisibility(uiOptions);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    //                                decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                    //                                    @Override
                    //                                    public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    //                                        WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    //                                        return defaultInsets.replaceSystemWindowInsets(
                    //                                                defaultInsets.getSystemWindowInsetLeft(),
                    //                                                0,
                    //                                                defaultInsets.getSystemWindowInsetRight(),
                    //                                                defaultInsets.getSystemWindowInsetBottom());
                    //                                    }
                    //                                });
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }

        private ViewGroup getRootView() {
            return ((ViewGroup) reactContext.getCurrentActivity().findViewById(android.R.id.content));
        }

    });

    reactContext.addLifecycleEventListener(webView);
    reactContext.addActivityEventListener(new ActivityEventListener() {
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
                return;
            }
            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[] { Uri.parse(mCameraPhotoPath) };
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[] { Uri.parse(dataString) };
                    }
                }
            }

            if (results == null) {
                mFilePathCallback.onReceiveValue(new Uri[] {});
            } else {
                mFilePathCallback.onReceiveValue(results);
            }
            mFilePathCallback = null;
            return;
        }

        @Override
        public void onNewIntent(Intent intent) {
        }
    });
    mWebViewConfig.configWebView(webView);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setDefaultFontSize(16);
    webView.getSettings().setTextZoom(100);
    // Fixes broken full-screen modals/galleries due to body height being 0.
    webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    return webView;
}

From source file:com.farmerbb.notepad.fragment.NoteEditFragment.java

public void dispatchKeyShortcutEvent(int keyCode) {
    switch (keyCode) {

    // CTRL+S: Save
    case KeyEvent.KEYCODE_S:
        // Set current note contents to a String
        contents = noteContents.getText().toString();

        // If EditText is empty, show toast informing user to enter some text
        if (contents.equals(""))
            showToast(R.string.empty_note);
        else {/*from   w w w. ja  va2  s .  c om*/
            try {
                // Keyboard shortcut just saves the note; no dialog shown
                saveNote();
                isSavedNote = true;

                // Change window title
                String title;
                try {
                    title = listener.loadNoteTitle(filename);
                } catch (IOException e) {
                    title = getResources().getString(R.string.edit_note);
                }

                getActivity().setTitle(title);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(),
                            R.drawable.ic_recents_logo)).getBitmap();

                    ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title,
                            bitmap, ContextCompat.getColor(getActivity(), R.color.primary));
                    getActivity().setTaskDescription(taskDescription);
                }
            } catch (IOException e) {
                // Show error message as toast if file fails to save
                showToast(R.string.failed_to_save);
            }
        }
        break;

    // CTRL+D: Delete
    case KeyEvent.KEYCODE_D:
        listener.showDeleteDialog();
        break;

    // CTRL+H: Share
    case KeyEvent.KEYCODE_H:
        // Set current note contents to a String
        contents = noteContents.getText().toString();

        // If EditText is empty, show toast informing user to enter some text
        if (contents.equals(""))
            showToast(R.string.empty_note);
        else {
            // Send a share intent
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_TEXT, contents);
            shareIntent.setType("text/plain");

            // Verify that the intent will resolve to an activity, and send
            if (shareIntent.resolveActivity(getActivity().getPackageManager()) != null)
                startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
        }
        break;
    }
}

From source file:us.theparamountgroup.android.inventory.EditorActivity.java

public void orderProduct(View view) {

    String nameProduct = mNameEditText.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, "supplier@example.com");
    intent.putExtra(Intent.EXTRA_SUBJECT, "Order " + nameProduct);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);/*from  w ww .j ava 2  s . co m*/
    } else {
        Toast.makeText(this, "Sorry no access to email", Toast.LENGTH_SHORT).show();
        return;
    }

}

From source file:foam.starwisp.StarwispBuilder.java

public static void photo(StarwispActivity ctx, String path, int code) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(ctx.getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;//from w  w w . j a  v a2s  . c o  m
        photoFile = new File(path);

        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            ctx.startActivityForResult(takePictureIntent, code);
        } else {
            Log.i("starwisp", "Could not open photo file");
        }
    }
}

From source file:dynamite.zafroshops.app.MainActivity.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
    case R.id.action_settings:
        return true;

    case R.id.new_zop_add:
        addZopFragment.setVisibility();/*  w ww. ja  v a  2  s .c  o  m*/
        FullMobileZop newZop = addZopFragment.getFullMobileZop();
        ArrayList<MobileOpeningHour> moh;
        ArrayList<MobileZopService> ms;

        if (NewZopOpenings != null) {
            moh = new ArrayList();
            for (int i = 0; i < NewZopOpenings.size(); i++) {
                moh.addAll(NewZopOpenings.get(i).Hours);
            }
            newZop.OpeningHours = moh;
        }

        if (NewZopServices != null) {
            ms = new ArrayList();
            for (int i = 0; i < NewZopServices.size(); i++) {
                MobileZopService mzs = new MobileZopService();

                mzs.Service = NewZopServices.get(i);
                ms.add(mzs);
            }
            newZop.Services = ms;
        }

        if (addZopFragment.ValidateNewZop(newZop)) {
            addZopFragment.setMessage();
            addZopFragment.setVisibility();
            if (PushHandler.ids == null) {
                PushHandler.ids = new ArrayList<>();
            }
            PushHandler.ids.add(newZop.Name);
            ListenableFuture<FullMobileZop> result = MainActivity.MobileClient.invokeApi("mobileZop", newZop,
                    FullMobileZop.class);
            Futures.addCallback(result, new FutureCallback<FullMobileZop>() {
                @Override
                public void onSuccess(FullMobileZop result) {
                    SimpleDialogFragment dialog = new SimpleDialogFragment();
                    Bundle args = new Bundle();
                    if (result == null) {
                        args.putString(SimpleDialogFragment.DIALOG_MESSAGE, getString(R.string.new_zop_failed)
                                + "\n" + getString(R.string.new_zop_check_location));
                    } else if (result.id.compareTo("-1") == 0) {
                        args.putString(SimpleDialogFragment.DIALOG_MESSAGE,
                                getString(R.string.new_zop_failed) + "\n" + result.Name);
                    } else {
                        PushHandler.ids.add(result.id);
                        args.putString(SimpleDialogFragment.DIALOG_MESSAGE,
                                getString(R.string.new_zop_success));
                        NewZopOpenings.clear();
                        NewZopServices.clear();
                        addZopFragment.clearForm(null);
                    }
                    addZopFragment.resetVisibility();
                    dialog.setArguments(args);
                    dialog.show(getSupportFragmentManager(), "new_zop_success");
                }

                @Override
                public void onFailure(@NonNull Throwable t) {
                    SimpleDialogFragment dialog = new SimpleDialogFragment();
                    Bundle args = new Bundle();

                    addZopFragment.resetVisibility();
                    args.putString(SimpleDialogFragment.DIALOG_MESSAGE, getString(R.string.new_zop_failed));
                    dialog.setArguments(args);
                    dialog.show(getSupportFragmentManager(), "new_zop_failed");
                }
            });
        } else {
            addZopFragment.resetVisibility();
            addZopFragment.setMessage();
        }
        break;

    case R.id.menu_zop_review:
        if (currentZop != null) {
            ReviewDialogFragment dialog = new ReviewDialogFragment();
            Bundle args = new Bundle();
            args.putString(ReviewDialogFragment.DIALOG_ZOP_ID, zopID);
            dialog.setArguments(args);
            dialog.show(getSupportFragmentManager(), "review");
        }
        break;

    case R.id.menu_zop_drive_to:
        if (currentZop != null && currentZop.Location != null && currentZop.Location.Latitude != null) {
            Uri uri = Uri.parse(String.format(Locale.US, "google.navigation:q=%f,%f",
                    currentZop.Location.Latitude, currentZop.Location.Longitude));
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
            mapIntent.setPackage("com.google.android.apps.maps");

            if (mapIntent.resolveActivity(getPackageManager()) != null) {
                startActivity(mapIntent);
            }
        }
        break;

    case R.id.menu_zop_call:
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        if (currentZop != null && currentZop.CountryPhoneCode != null && currentZop.PhoneNumber != null
                && !currentZop.PhoneNumber.trim().equals("")) {
            callIntent.setData(Uri.parse("tel:" + currentZop.CountryPhoneCode + currentZop.PhoneNumber));
            startActivity(callIntent);
        }
        break;

    case R.id.menu_location_refresh:
        getLocation(true);
        getAddress(true);
        break;

    case R.id.menu_zop_refresh:
        refresh();
        break;

    case R.id.menu_zops_refresh:
        getLocation(true);
        getAddress(true);
        nextMenu(AllZopsFragment.newInstance(position, true), false, 1);
        break;
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.desno365.mods.Activities.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    switch (item.getItemId()) {

    case android.R.id.home:
        if (mNavigationDrawerFragment.isDrawerOpen())
            MainNavigationDrawerFragment.mDrawerLayout.closeDrawer(findViewById(R.id.navigation_drawer));
        else// w w  w .  j a v  a 2s .c om
            MainNavigationDrawerFragment.mDrawerLayout.openDrawer(findViewById(R.id.navigation_drawer));
        return true;

    case R.id.action_info:
        startActivity(new Intent(this, AboutActivity.class));
        return true;

    case R.id.action_help:
        startActivity(new Intent(this, HelpActivity.class));
        return true;

    case R.id.action_news:
        startActivity(new Intent(this, NewsActivity.class));
        return true;

    case R.id.action_share:
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.share_body));
        startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));
        DesnoUtils.sendAction(mTracker, "Share");
        return true;

    case R.id.action_feedback:
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:")); // only email apps should handle this
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "desno365@gmail.com" });
        intent.putExtra(Intent.EXTRA_SUBJECT, "Desno365's Mods feedback");
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
        DesnoUtils.sendAction(mTracker, "Feedback");
        return true;

    case R.id.action_rate:
        final String appPackageName = getPackageName();
        try {
            //play store installed
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            //play store not installed
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
        }
        DesnoUtils.sendAction(mTracker, "Rate-app");
        return true;

    case R.id.action_settings:
        Intent intentSettings = new Intent(this, SettingsActivity.class);
        startActivity(intentSettings);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.mocap.MocapFragment.java

public void SaveOBJ(Context context, MyGLSurfaceView glview) {
    Log.i(TAG, "DIR: ");
    float sVertices[] = glview.getsVertices();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    File mFile;/*ww w.  j  av a 2s  .  com*/

    if (Environment.DIRECTORY_PICTURES != null) {
        try {
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "mocap.obj");

            Log.i(TAG, "Long Vertices: " + sVertices.length);
            fOut = new FileOutputStream(mFile);
            osw = new OutputStreamWriter(fOut);
            osw.write("# *.obj file (Generate by Mocap 3D)\n");
            osw.flush();

            for (int i = 0; i < sVertices.length - 4; i = i + 3) {

                try {
                    String data = "v " + Float.toString(sVertices[i]) + " " + Float.toString(sVertices[i + 1])
                            + " " + Float.toString(sVertices[i + 2]) + "\n";
                    Log.i(TAG, i + ": " + data);
                    osw.write(data);
                    osw.flush();

                } catch (Exception e) {
                    Toast.makeText(context, "erreur d'criture: " + e, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Erreur: " + e);
                }

            }

            osw.write("# lignes:\n");
            osw.write("l ");
            osw.flush();
            ;
            for (int i = 1; i < (-1 + sVertices.length / 3); i++) {
                osw.write(i + " ");
                osw.flush();
            }
            //popup surgissant pour le rsultat
            Toast.makeText(getActivity(), "Save : " + Environment.DIRECTORY_PICTURES + "/mocap.obj ",
                    Toast.LENGTH_SHORT).show();

            //lancement d'un explorateur de fichiers vers le fichier crer
            //systeme des intend
            try {
                File root = new File(Environment.DIRECTORY_PICTURES);
                Uri uri = Uri.fromFile(mFile);

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(uri);

                // Verify that the intent will resolve to an activity
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    Log.i(TAG, "intent pk: ");
                    getActivity().startActivityForResult(intent, 1);
                }
            } catch (Exception e) {
                Log.i(TAG, "Erreur intent: " + e);
            }
        } catch (Exception e) {
            Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
            }

        }

    } else {
        Toast.makeText(context, "Pas de carte ext", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.farmerbb.taskbar.service.StartMenuService.java

@SuppressLint("RtlHardcoded")
private void drawStartMenu() {
    IconCache.getInstance(this).clearCache();

    final SharedPreferences pref = U.getSharedPreferences(this);
    final boolean hasHardwareKeyboard = getResources()
            .getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;

    switch (pref.getString("show_search_bar", "keyboard")) {
    case "always":
        shouldShowSearchBox = true;/*from   ww w.  j a  v a  2s . c  o  m*/
        break;
    case "keyboard":
        shouldShowSearchBox = hasHardwareKeyboard;
        break;
    case "never":
        shouldShowSearchBox = false;
        break;
    }

    // Initialize layout params
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    U.setCachedRotation(windowManager.getDefaultDisplay().getRotation());

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            shouldShowSearchBox ? 0
                    : WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            PixelFormat.TRANSLUCENT);

    // Determine where to show the start menu on screen
    switch (U.getTaskbarPosition(this)) {
    case "bottom_left":
        layoutId = R.layout.start_menu_left;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        break;
    case "bottom_vertical_left":
        layoutId = R.layout.start_menu_vertical_left;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        break;
    case "bottom_right":
        layoutId = R.layout.start_menu_right;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        break;
    case "bottom_vertical_right":
        layoutId = R.layout.start_menu_vertical_right;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        break;
    case "top_left":
        layoutId = R.layout.start_menu_top_left;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        break;
    case "top_vertical_left":
        layoutId = R.layout.start_menu_vertical_left;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        break;
    case "top_right":
        layoutId = R.layout.start_menu_top_right;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        break;
    case "top_vertical_right":
        layoutId = R.layout.start_menu_vertical_right;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        break;
    }

    // Initialize views
    int theme = 0;

    switch (pref.getString("theme", "light")) {
    case "light":
        theme = R.style.AppTheme;
        break;
    case "dark":
        theme = R.style.AppTheme_Dark;
        break;
    }

    ContextThemeWrapper wrapper = new ContextThemeWrapper(this, theme);
    layout = (StartMenuLayout) LayoutInflater.from(wrapper).inflate(layoutId, null);
    startMenu = (GridView) layout.findViewById(R.id.start_menu);

    if ((shouldShowSearchBox && !hasHardwareKeyboard)
            || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
        layout.viewHandlesBackButton();

    boolean scrollbar = pref.getBoolean("scrollbar", false);
    startMenu.setFastScrollEnabled(scrollbar);
    startMenu.setFastScrollAlwaysVisible(scrollbar);
    startMenu.setScrollBarStyle(scrollbar ? View.SCROLLBARS_OUTSIDE_INSET : View.SCROLLBARS_INSIDE_OVERLAY);

    if (pref.getBoolean("transparent_start_menu", false))
        startMenu.setBackgroundColor(0);

    searchView = (SearchView) layout.findViewById(R.id.search);

    int backgroundTint = U.getBackgroundTint(this);

    FrameLayout startMenuFrame = (FrameLayout) layout.findViewById(R.id.start_menu_frame);
    FrameLayout searchViewLayout = (FrameLayout) layout.findViewById(R.id.search_view_layout);
    startMenuFrame.setBackgroundColor(backgroundTint);
    searchViewLayout.setBackgroundColor(backgroundTint);

    if (shouldShowSearchBox) {
        if (!hasHardwareKeyboard)
            searchView.setIconifiedByDefault(true);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!hasSubmittedQuery) {
                    ListAdapter adapter = startMenu.getAdapter();
                    if (adapter != null) {
                        hasSubmittedQuery = true;

                        if (adapter.getCount() > 0) {
                            View view = adapter.getView(0, null, startMenu);
                            LinearLayout layout = (LinearLayout) view.findViewById(R.id.entry);
                            layout.performClick();
                        } else {
                            if (pref.getBoolean("hide_taskbar", true)
                                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                                LocalBroadcastManager.getInstance(StartMenuService.this)
                                        .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_TASKBAR"));
                            else
                                LocalBroadcastManager.getInstance(StartMenuService.this)
                                        .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));

                            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                            intent.putExtra(SearchManager.QUERY, query);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            if (intent.resolveActivity(getPackageManager()) != null)
                                startActivity(intent);
                            else {
                                Uri uri = new Uri.Builder().scheme("https").authority("www.google.com")
                                        .path("search").appendQueryParameter("q", query).build();

                                intent = new Intent(Intent.ACTION_VIEW);
                                intent.setData(uri);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                try {
                                    startActivity(intent);
                                } catch (ActivityNotFoundException e) {
                                    /* Gracefully fail */ }
                            }
                        }
                    }
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                searchView.setIconified(false);

                View closeButton = searchView.findViewById(R.id.search_close_btn);
                if (closeButton != null)
                    closeButton.setVisibility(View.GONE);

                refreshApps(newText, false);

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
                    new Handler().postDelayed(() -> {
                        EditText editText = (EditText) searchView.findViewById(R.id.search_src_text);
                        if (editText != null) {
                            editText.requestFocus();
                            editText.setSelection(editText.getText().length());
                        }
                    }, 50);
                }

                return true;
            }
        });

        searchView.setOnQueryTextFocusChangeListener((view, b) -> {
            if (!hasHardwareKeyboard) {
                ViewGroup.LayoutParams params1 = startMenu.getLayoutParams();
                params1.height = getResources().getDimensionPixelSize(b
                        && !U.isServiceRunning(this, "com.farmerbb.secondscreen.service.DisableKeyboardService")
                                ? R.dimen.start_menu_height_half
                                : R.dimen.start_menu_height);
                startMenu.setLayoutParams(params1);
            }

            if (!b) {
                if (hasHardwareKeyboard && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
                    LocalBroadcastManager.getInstance(StartMenuService.this)
                            .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
                else {
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
        });

        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);

        LinearLayout powerButton = (LinearLayout) layout.findViewById(R.id.power_button);
        powerButton.setOnClickListener(view -> {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            openContextMenu(location);
        });

        powerButton.setOnGenericMotionListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                    && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                int[] location = new int[2];
                view.getLocationOnScreen(location);
                openContextMenu(location);
            }
            return false;
        });

        searchViewLayout.setOnClickListener(view -> searchView.setIconified(false));

        startMenu.setOnItemClickListener((parent, view, position, id) -> {
            hideStartMenu();

            AppEntry entry = (AppEntry) parent.getAdapter().getItem(position);
            U.launchApp(StartMenuService.this, entry.getPackageName(), entry.getComponentName(),
                    entry.getUserId(StartMenuService.this), null, false, false);
        });

        if (pref.getBoolean("transparent_start_menu", false))
            layout.findViewById(R.id.search_view_child_layout).setBackgroundColor(0);
    } else
        searchViewLayout.setVisibility(View.GONE);

    textView = (TextView) layout.findViewById(R.id.no_apps_found);

    LocalBroadcastManager.getInstance(this).unregisterReceiver(toggleReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(toggleReceiverAlt);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(hideReceiver);

    LocalBroadcastManager.getInstance(this).registerReceiver(toggleReceiver,
            new IntentFilter("com.farmerbb.taskbar.TOGGLE_START_MENU"));
    LocalBroadcastManager.getInstance(this).registerReceiver(toggleReceiverAlt,
            new IntentFilter("com.farmerbb.taskbar.TOGGLE_START_MENU_ALT"));
    LocalBroadcastManager.getInstance(this).registerReceiver(hideReceiver,
            new IntentFilter("com.farmerbb.taskbar.HIDE_START_MENU"));

    handler = new Handler();
    refreshApps(true);

    windowManager.addView(layout, params);
}