Example usage for android.content Intent addCategory

List of usage examples for android.content Intent addCategory

Introduction

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

Prototype

public @NonNull Intent addCategory(String category) 

Source Link

Document

Add a new category to the intent.

Usage

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

private void showAudioFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("audio/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {/*w w w.  ja v a2  s. c  o  m*/
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), AUDIO_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

private void showVideoFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("video/*");

    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {//from   ww w. java 2 s.  c o  m
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), VIDEO_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.dsdar.thosearoundme.TeamViewActivity.java

@Override
public void onBackPressed() {

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle("Exit Application?");
    alertDialogBuilder.setMessage("Click yes to exit!").setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Remove Service
                    stopService(new Intent(getBaseContext(), LocationUpdates.class));
                    // stopService(new Intent(getBaseContext(),
                    // LocationService.class));
                    if (itsLocationUpdates != null)
                        itsLocationUpdates.disconnectLocationClient();
                    mHandlerTaskServiceStop = new Runnable() {
                        @Override
                        public void run() {
                            Log.d("tmf", "calling mHandlerTaskServiceStop.......");
                            // Get and set team members location in
                            // map

                            // finish();
                            //                                        moveTaskToBack(true);
                            //
                            //                                        Intent amyProfileIntent = new Intent().setClass(
                            //                                                TeamViewActivity.this, WelcomeActivity.class);
                            //                                        startActivity(amyProfileIntent);
                            //
                            //
                            //                                        android.os.Process
                            //                                                .killProcess(android.os.Process
                            //                                                        .myPid());
                            //                                        System.exit(1);
                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }//  w w w  .j  a  v a2  s  .c om
                    };
                    itsHandlerServiceStop.postDelayed(mHandlerTaskServiceStop, 1500);

                }
            })

            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    dialog.cancel();
                }
            });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

@Override
public void create() {
    try {/*  www . j a  va 2 s.  co  m*/

        setContentView(R.layout.romanblack_html_main);
        root = (FrameLayout) findViewById(R.id.romanblack_root_layout);
        webView = new ObservableWebView(this);
        webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        root.addView(webView);

        webView.setHorizontalScrollBarEnabled(false);
        setTitle("HTML");

        Intent currentIntent = getIntent();
        Bundle store = currentIntent.getExtras();
        widget = (Widget) store.getSerializable("Widget");
        if (widget == null) {
            handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
            return;
        }
        appName = widget.getAppName();

        if (widget.getPluginXmlData().length() == 0) {
            if (currentIntent.getStringExtra("WidgetFile").length() == 0) {
                handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
                return;
            }
        }

        if (widget.getTitle() != null && widget.getTitle().length() > 0) {
            setTopBarTitle(widget.getTitle());
        } else {
            setTopBarTitle(getResources().getString(R.string.romanblack_html_web));
        }

        currentUrl = (String) getSession();
        if (currentUrl == null) {
            currentUrl = "";
        }

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnectedOrConnecting()) {
            isOnline = true;
        }

        // topbar initialization
        setTopBarLeftButtonText(getString(R.string.common_home_upper), true, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        if (isOnline) {
            webView.getSettings().setJavaScriptEnabled(true);
        }

        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setSavePassword(false);
        webView.clearHistory();
        webView.invalidate();

        if (Build.VERSION.SDK_INT >= 19) {
        }
        webView.getSettings().setUserAgentString(
                "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.invalidate();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                }
                    break;
                case MotionEvent.ACTION_UP: {
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                }
                    break;

                case MotionEvent.ACTION_MOVE: {
                }
                    break;

                }
                return false;
            }
        });

        webView.setBackgroundColor(Color.WHITE);
        try {
            if (widget.getBackgroundColor() != Color.TRANSPARENT) {
                webView.setBackgroundColor(widget.getBackgroundColor());
            }
        } catch (IllegalArgumentException e) {
        }

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

        webView.setWebChromeClient(new WebChromeClient() {

            FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                    final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setTitle(R.string.location_dialog_title);
                builder.setMessage(R.string.location_dialog_description);
                builder.setCancelable(true);

                builder.setPositiveButton(R.string.location_dialog_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, true, false);
                            }
                        });

                builder.setNegativeButton(R.string.location_dialog_not_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, false, false);
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
                if (customView != null) {
                    customViewCallback.onCustomViewHidden();
                    return;
                }

                view.setBackgroundColor(Color.BLACK);
                view.setLayoutParams(LayoutParameters);
                root.addView(view);
                customView = view;
                customViewCallback = callback;
                webView.setVisibility(View.GONE);
            }

            @Override
            public void onHideCustomView() {
                if (customView == null) {
                    return;
                } else {
                    closeFullScreenVideo();
                }
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);//Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                isMedia = true;
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                isMedia = true;
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                isV21 = true;
                mUploadMessageV21 = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                return true;
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                if (state == states.EMPTY) {
                    currentUrl = url;
                    setSession(currentUrl);
                    state = states.LOAD_START;
                    handler.sendEmptyMessage(SHOW_PROGRESS);
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {

                if (!alreadyLoaded
                        && (url.startsWith("http://www.youtube.com/get_video_info?")
                                || url.startsWith("https://www.youtube.com/get_video_info?"))
                        && Build.VERSION.SDK_INT < 11) {
                    try {
                        String path = url.contains("https://www.youtube.com/get_video_info?")
                                ? url.replace("https://www.youtube.com/get_video_info?", "")
                                : url.replace("http://www.youtube.com/get_video_info?", "");

                        String[] parqamValuePairs = path.split("&");

                        String videoId = null;

                        for (String pair : parqamValuePairs) {
                            if (pair.startsWith("video_id")) {
                                videoId = pair.split("=")[1];
                                break;
                            }
                        }

                        if (videoId != null) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                    .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));
                            needRefresh = true;
                            alreadyLoaded = !alreadyLoaded;

                            return;
                        }
                    } catch (Exception ex) {
                    }
                } else {
                    super.onLoadResource(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (hideProgress) {
                    if (TextUtils.isEmpty(WebPlugin.this.url)) {
                        state = states.LOAD_COMPLETE;
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        super.onPageFinished(view, url);
                    } else {
                        view.loadUrl("javascript:(function(){" + "l=document.getElementById('link');"
                                + "e=document.createEvent('HTMLEvents');" + "e.initEvent('click',true,true);"
                                + "l.dispatchEvent(e);" + "})()");
                        hideProgress = false;
                    }
                } else {
                    state = states.LOAD_COMPLETE;
                    handler.sendEmptyMessage(HIDE_PROGRESS);
                    super.onPageFinished(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (errorCode == WebViewClient.ERROR_BAD_URL) {
                    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                            DOWNLOAD_REQUEST_CODE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setMessage(R.string.notification_error_ssl_cert_invalid);
                builder.setPositiveButton(WebPlugin.this.getResources().getString(R.string.wp_continue),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.proceed();
                            }
                        });
                builder.setNegativeButton(WebPlugin.this.getResources().getString(R.string.wp_cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.cancel();
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {

                    if (url.contains("youtube.com/watch")) {
                        if (Build.VERSION.SDK_INT < 11) {
                            try {
                                startActivity(
                                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                                .setData(Uri.parse(url)));
                                return true;
                            } catch (Exception ex) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else if (url.contains("paypal.com")) {
                        if (url.contains("&bn=ibuildapp_SP")) {
                            return false;
                        } else {
                            url = url + "&bn=ibuildapp_SP";

                            webView.loadUrl(url);

                            return true;
                        }
                    } else if (url.contains("sms:")) {
                        try {
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(url));
                            startActivity(smsIntent);
                            return true;
                        } catch (Exception ex) {
                            Log.e("", ex.getMessage());
                            return false;
                        }
                    } else if (url.contains("tel:")) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse(url));
                        startActivity(callIntent);
                        return true;
                    } else if (url.contains("mailto:")) {
                        MailTo mailTo = MailTo.parse(url);

                        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                        emailIntent.setType("plain/text");
                        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                new String[] { mailTo.getTo() });

                        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mailTo.getSubject());
                        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailTo.getBody());
                        WebPlugin.this.startActivity(Intent.createChooser(emailIntent,
                                getString(R.string.romanblack_html_send_email)));
                        return true;
                    } else if (url.contains("rtsp:")) {
                        Uri address = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, address);

                        final PackageManager pm = getPackageManager();
                        final List<ResolveInfo> matches = pm.queryIntentActivities(intent, 0);
                        if (matches.size() > 0) {
                            startActivity(intent);
                        } else {
                            Toast.makeText(WebPlugin.this, getString(R.string.romanblack_html_no_video_player),
                                    Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    } else if (url.startsWith("intent:") || url.startsWith("market:")
                            || url.startsWith("col-g2m-2:")) {
                        Intent it = new Intent();
                        it.setData(Uri.parse(url));
                        startActivity(it);

                        return true;
                    } else if (url.contains("//play.google.com/")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } else {
                        if (url.contains("ibuildapp.com-1915109")) {
                            String param = Uri.parse(url).getQueryParameter("widget");
                            finish();
                            if (param != null && param.equals("1001"))
                                com.appbuilder.sdk.android.Statics.launchMain();
                            else if (param != null && !"".equals(param)) {
                                View.OnClickListener widget = Statics.linkWidgets.get(Integer.valueOf(param));
                                if (widget != null)
                                    widget.onClick(view);
                            }
                            return false;
                        }

                        currentUrl = url;
                        setSession(currentUrl);
                        if (!isOnline) {
                            handler.sendEmptyMessage(HIDE_PROGRESS);
                            handler.sendEmptyMessage(STOP_LOADING);
                        } else {
                            String pageType = "application/html";
                            if (!url.contains("vk.com")) {
                                getPageType(url);
                            }
                            if (pageType.contains("application") && !pageType.contains("html")
                                    && !pageType.contains("xml")) {
                                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                                        DOWNLOAD_REQUEST_CODE);
                                return super.shouldOverrideUrlLoading(view, url);
                            } else {
                                view.getSettings().setLoadWithOverviewMode(true);
                                view.getSettings().setUseWideViewPort(true);
                                view.setBackgroundColor(Color.WHITE);
                            }
                        }
                        return false;
                    }

                } catch (Exception ex) { // Error Logging
                    return false;
                }
            }
        });

        handler.sendEmptyMessage(SHOW_PROGRESS);

        new Thread() {
            @Override
            public void run() {

                EntityParser parser;
                if (widget.getPluginXmlData() != null) {
                    if (widget.getPluginXmlData().length() > 0) {
                        parser = new EntityParser(widget.getPluginXmlData());
                    } else {
                        String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                        parser = new EntityParser(xmlData);
                    }
                } else {
                    String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                    parser = new EntityParser(xmlData);
                }

                parser.parse();

                url = parser.getUrl();
                html = parser.getHtml();

                if (url.length() > 0 && !isOnline) {
                    handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
                } else {
                    if (isOnline) {
                    } else {
                        if (html.length() == 0) {
                        }
                    }
                    if (html.length() > 0 || url.length() > 0) {
                        handler.sendEmptyMessageDelayed(SHOW_HTML, 700);
                    } else {
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        handler.sendEmptyMessage(INITIALIZATION_FAILED);
                    }
                }
            }
        }.start();

    } catch (Exception ex) {
    }
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

public void imageOpen(Fragment f, final int REQUEST_CAMERA, final int SELECT_FILE) {

    GeneralHelper.getInstance(MainActivity.this).setTempFragment(f);
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override//  w w  w.ja v  a2  s.co m
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {

                java.io.File imageFile = new File(
                        (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/."
                                + Constants.APPNAME + "/" + System.currentTimeMillis() + ".jpeg"));

                PreferencesManager.setPreferenceByKey(MainActivity.this, "IMAGEWWC",
                        imageFile.getAbsolutePath());
                //
                imageFilePath = imageFile;
                imageFileUri = Uri.fromFile(imageFile);
                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(i, REQUEST_CAMERA);

            } else if (items[item].equals("Choose from Library")) {
                if (Build.VERSION.SDK_INT < 19) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                }

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

From source file:activities.PaintActivity.java

@Override
public void onBackPressed() {
    if (backButtonCount >= 1) {
        if (toast != null)
            toast.cancel();/*from w  w  w . j  a va2  s  . c  om*/
        toast = null;
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        backButtonCount = 0;
    } else {
        toast = Toast.makeText(this, "Press the back button once again to close the application.",
                Toast.LENGTH_LONG);
        toast.show();
        backButtonCount++;
    }
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

private Intent getIntentOpenExport() {
    Intent intent;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
        intent = new Intent(Intent.ACTION_GET_CONTENT);
    else//  w  w w. jav  a  2  s. co  m
        intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*"); // text/xml
    return intent;
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

private Intent getIntentOpenHosts() {
    Intent intent;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
        intent = new Intent(Intent.ACTION_GET_CONTENT);
    else/*from  w w w.  java  2  s  .c  o m*/
        intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*"); // text/plain
    return intent;
}

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

@SuppressWarnings("Convert2streamapi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void updateRecentApps(final boolean firstRefresh) {
    SharedPreferences pref = U.getSharedPreferences(this);
    final PackageManager pm = getPackageManager();
    final List<AppEntry> entries = new ArrayList<>();
    List<LauncherActivityInfo> launcherAppCache = new ArrayList<>();
    int maxNumOfEntries = U.getMaxNumOfEntries(this);
    int realNumOfPinnedApps = 0;
    boolean fullLength = pref.getBoolean("full_length", false);

    PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
    List<AppEntry> pinnedApps = pba.getPinnedApps();
    List<AppEntry> blockedApps = pba.getBlockedApps();
    List<String> applicationIdsToRemove = new ArrayList<>();

    // Filter out anything on the pinned/blocked apps lists
    if (pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);

        for (AppEntry entry : pinnedApps) {
            boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(),
                    userManager.getUserForSerialNumber(entry.getUserId(this)));

            if (packageEnabled)
                entries.add(entry);/*from  w  w w .  j av a  2s.co  m*/
            else
                realNumOfPinnedApps--;

            applicationIdsToRemove.add(entry.getPackageName());
        }

        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }

    if (blockedApps.size() > 0) {
        for (AppEntry entry : blockedApps) {
            applicationIdsToRemove.add(entry.getPackageName());
        }
    }

    // Get list of all recently used apps
    List<AppEntry> usageStatsList = realNumOfPinnedApps < maxNumOfEntries ? getAppEntries() : new ArrayList<>();
    if (usageStatsList.size() > 0 || realNumOfPinnedApps > 0 || fullLength) {
        if (realNumOfPinnedApps < maxNumOfEntries) {
            List<AppEntry> usageStatsList2 = new ArrayList<>();
            List<AppEntry> usageStatsList3 = new ArrayList<>();
            List<AppEntry> usageStatsList4 = new ArrayList<>();
            List<AppEntry> usageStatsList5 = new ArrayList<>();
            List<AppEntry> usageStatsList6;

            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);

            // Filter out apps without a launcher intent
            // Also filter out the current launcher, and Taskbar itself
            for (AppEntry packageInfo : usageStatsList) {
                if (hasLauncherIntent(packageInfo.getPackageName())
                        && !packageInfo.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                        && !packageInfo.getPackageName().equals(defaultLauncher.activityInfo.packageName))
                    usageStatsList2.add(packageInfo);
            }

            // Filter out apps that don't fall within our current search interval
            for (AppEntry stats : usageStatsList2) {
                if (stats.getLastTimeUsed() > searchInterval || runningAppsOnly)
                    usageStatsList3.add(stats);
            }

            // Sort apps by either most recently used, or most time used
            if (!runningAppsOnly) {
                if (sortOrder.contains("most_used")) {
                    Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getTotalTimeInForeground(),
                            us1.getTotalTimeInForeground()));
                } else {
                    Collections.sort(usageStatsList3,
                            (us1, us2) -> Long.compare(us2.getLastTimeUsed(), us1.getLastTimeUsed()));
                }
            }

            // Filter out any duplicate entries
            List<String> applicationIds = new ArrayList<>();
            for (AppEntry stats : usageStatsList3) {
                if (!applicationIds.contains(stats.getPackageName())) {
                    usageStatsList4.add(stats);
                    applicationIds.add(stats.getPackageName());
                }
            }

            // Filter out the currently running foreground app, if requested by the user
            if (pref.getBoolean("hide_foreground", false)) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(
                        USAGE_STATS_SERVICE);
                UsageEvents events = mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis());
                UsageEvents.Event eventCache = new UsageEvents.Event();
                String currentForegroundApp = null;

                while (events.hasNextEvent()) {
                    events.getNextEvent(eventCache);

                    if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                        if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                                && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName())
                                && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName())
                                && !eventCache.getClassName()
                                        .equals(InvisibleActivityFreeform.class.getCanonicalName())))
                            currentForegroundApp = eventCache.getPackageName();
                    }
                }

                if (!applicationIdsToRemove.contains(currentForegroundApp))
                    applicationIdsToRemove.add(currentForegroundApp);
            }

            for (AppEntry stats : usageStatsList4) {
                if (!applicationIdsToRemove.contains(stats.getPackageName())) {
                    usageStatsList5.add(stats);
                }
            }

            // Truncate list to a maximum length
            if (usageStatsList5.size() > maxNumOfEntries)
                usageStatsList6 = usageStatsList5.subList(0, maxNumOfEntries);
            else
                usageStatsList6 = usageStatsList5;

            // Determine if we need to reverse the order
            boolean needToReverseOrder;
            switch (U.getTaskbarPosition(this)) {
            case "bottom_right":
            case "top_right":
                needToReverseOrder = sortOrder.contains("false");
                break;
            default:
                needToReverseOrder = sortOrder.contains("true");
                break;
            }

            if (needToReverseOrder) {
                Collections.reverse(usageStatsList6);
            }

            // Generate the AppEntries for TaskbarAdapter
            int number = usageStatsList6.size() == maxNumOfEntries
                    ? usageStatsList6.size() - realNumOfPinnedApps
                    : usageStatsList6.size();

            UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);

            final List<UserHandle> userHandles = userManager.getUserProfiles();

            for (int i = 0; i < number; i++) {
                for (UserHandle handle : userHandles) {
                    String packageName = usageStatsList6.get(i).getPackageName();
                    List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle);
                    if (!list.isEmpty()) {
                        // Google App workaround
                        if (!packageName.equals("com.google.android.googlequicksearchbox"))
                            launcherAppCache.add(list.get(0));
                        else {
                            boolean added = false;
                            for (LauncherActivityInfo info : list) {
                                if (info.getName()
                                        .equals("com.google.android.googlequicksearchbox.SearchActivity")) {
                                    launcherAppCache.add(info);
                                    added = true;
                                }
                            }

                            if (!added)
                                launcherAppCache.add(list.get(0));
                        }

                        AppEntry newEntry = new AppEntry(packageName, null, null, null, false);

                        newEntry.setUserId(userManager.getSerialNumberForUser(handle));
                        entries.add(newEntry);

                        break;
                    }
                }
            }
        }

        while (entries.size() > maxNumOfEntries) {
            try {
                entries.remove(entries.size() - 1);
                launcherAppCache.remove(launcherAppCache.size() - 1);
            } catch (ArrayIndexOutOfBoundsException e) {
                /* Gracefully fail */ }
        }

        // Determine if we need to reverse the order again
        if (U.getTaskbarPosition(this).contains("vertical")) {
            Collections.reverse(entries);
            Collections.reverse(launcherAppCache);
        }

        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the Taskbar or not
        boolean shouldRedrawTaskbar = firstRefresh;

        List<String> finalApplicationIds = new ArrayList<>();
        for (AppEntry entry : entries) {
            finalApplicationIds.add(entry.getPackageName());
        }

        if (finalApplicationIds.size() != currentTaskbarIds.size() || numOfPinnedApps != realNumOfPinnedApps)
            shouldRedrawTaskbar = true;
        else {
            for (int i = 0; i < finalApplicationIds.size(); i++) {
                if (!finalApplicationIds.get(i).equals(currentTaskbarIds.get(i))) {
                    shouldRedrawTaskbar = true;
                    break;
                }
            }
        }

        if (shouldRedrawTaskbar) {
            currentTaskbarIds = finalApplicationIds;
            numOfPinnedApps = realNumOfPinnedApps;

            UserManager userManager = (UserManager) getSystemService(USER_SERVICE);

            int launcherAppCachePos = -1;
            for (int i = 0; i < entries.size(); i++) {
                if (entries.get(i).getComponentName() == null) {
                    launcherAppCachePos++;
                    LauncherActivityInfo appInfo = launcherAppCache.get(launcherAppCachePos);
                    String packageName = entries.get(i).getPackageName();

                    entries.remove(i);

                    AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(),
                            appInfo.getLabel().toString(), IconCache.getInstance(TaskbarService.this)
                                    .getIcon(TaskbarService.this, pm, appInfo),
                            false);

                    newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                    entries.add(i, newEntry);
                }
            }

            final int numOfEntries = Math.min(entries.size(), maxNumOfEntries);

            handler.post(() -> {
                if (numOfEntries > 0 || fullLength) {
                    ViewGroup.LayoutParams params = scrollView.getLayoutParams();
                    DisplayMetrics metrics = getResources().getDisplayMetrics();
                    int recentsSize = getResources().getDimensionPixelSize(R.dimen.icon_size) * numOfEntries;
                    float maxRecentsSize = fullLength ? Float.MAX_VALUE : recentsSize;

                    if (U.getTaskbarPosition(TaskbarService.this).contains("vertical")) {
                        int maxScreenSize = metrics.heightPixels - U.getStatusBarHeight(TaskbarService.this)
                                - U.getBaseTaskbarSize(TaskbarService.this);

                        params.height = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("bottom")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.height = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    } else {
                        int maxScreenSize = metrics.widthPixels - U.getBaseTaskbarSize(TaskbarService.this);

                        params.width = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("right")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.width = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    }

                    scrollView.setLayoutParams(params);

                    taskbar.removeAllViews();
                    for (int i = 0; i < entries.size(); i++) {
                        taskbar.addView(getView(entries, i));
                    }

                    isShowingRecents = true;
                    if (shouldRefreshRecents && scrollView.getVisibility() != View.VISIBLE) {
                        if (firstRefresh)
                            scrollView.setVisibility(View.INVISIBLE);
                        else
                            scrollView.setVisibility(View.VISIBLE);
                    }

                    if (firstRefresh && scrollView.getVisibility() != View.VISIBLE)
                        new Handler().post(() -> {
                            switch (U.getTaskbarPosition(TaskbarService.this)) {
                            case "bottom_left":
                            case "bottom_right":
                            case "top_left":
                            case "top_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(0, 0);
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                break;
                            case "bottom_vertical_left":
                            case "bottom_vertical_right":
                            case "top_vertical_left":
                            case "top_vertical_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(0, 0);
                                break;
                            }

                            if (shouldRefreshRecents) {
                                scrollView.setVisibility(View.VISIBLE);
                            }
                        });
                } else {
                    isShowingRecents = false;
                    scrollView.setVisibility(View.GONE);
                }
            });
        }
    } else if (firstRefresh || currentTaskbarIds.size() > 0) {
        currentTaskbarIds.clear();
        handler.post(() -> {
            isShowingRecents = false;
            scrollView.setVisibility(View.GONE);
        });
    }
}

From source file:com.findcab.activity.LocationOverlay.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        //         exitDialog(context);
        //??home?
        Intent intents = new Intent(Intent.ACTION_MAIN);
        intents.addCategory(Intent.CATEGORY_HOME);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);//from www. j a va 2  s  .c  om
    }
    return super.onKeyDown(keyCode, event);
}