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:android_network.hetnet.vpn_service.ActivityLog.java

private Intent getIntentPCAPDocument() {
    Intent intent;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        if (Util.isPackageInstalled("org.openintents.filemanager", this)) {
            intent = new Intent("org.openintents.action.PICK_DIRECTORY");
        } else {//  www.  j  a va2s  .com
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(
                    Uri.parse("https://play.google.com/store/apps/details?id=org.openintents.filemanager"));
        }
    } else {
        intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/octet-stream");
        intent.putExtra(Intent.EXTRA_TITLE,
                "netguard_" + new SimpleDateFormat("yyyyMMdd").format(new Date().getTime()) + ".pcap");
    }
    return intent;
}

From source file:com.egloos.hyunyi.musicinfo.LinkPopUp.java

@Override
public void onCreate(Bundle saveInstanceState) {
    super.onCreate(saveInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    Bundle b = getIntent().getExtras();/*from w  w  w . ja  va 2s . com*/

    SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);

    imageOptions = new DisplayImageOptions.Builder().cacheInMemory(false).cacheOnDisk(true)
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY)
            .showImageOnLoading(R.drawable.connecting_anim).build();
    config = new ImageLoaderConfiguration.Builder(getApplicationContext()).diskCacheExtraOptions(480, 320, null)
            .defaultDisplayImageOptions(imageOptions).build();

    if (imageLoader == null)
        imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited())
        imageLoader.init(config);

    setContentView(R.layout.link_dialog);

    imageFrame = (FrameLayout) findViewById(R.id.image_frame);
    iBottomPanel = (ImageView) findViewById(R.id.bottom_panel);

    lArtistLink = (RelativeLayout) findViewById(R.id.l_artist_link);

    bPopUpClose = (ImageView) findViewById(R.id.b_popup_close);
    bPopUpClose.setOnClickListener(this);

    tEchoNest = (TextView) findViewById(R.id.t_echo_nest);
    tAttribution = (TextView) findViewById(R.id.t_attribution);

    tArtistName = (TextView) findViewById(R.id.t_artist_name);
    tArtistName.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //isMove = false;
                mTouchX = event.getRawX();
                mTouchY = event.getRawY();
                break;

            case MotionEvent.ACTION_UP:
                //Log.i("musicInfo", "ACTION_UP! TouchY:" + mTouchY + " UpY: " + event.getRawY() + " Move: " + (mTouchY - event.getRawY()));
                int RawY = (int) event.getRawY();
                int dY = (int) (mTouchY - event.getRawY());
                if (dY > 200) {
                    imageLoader.resume();
                    //Log.i("musicInfo", "mGridView TOP = " + mGridView.getTop() + " mGridView TransitionY =" + mGridView.getTranslationY());
                    while (mGridView.getTranslationY() > tArtistName.getHeight()) {
                        //Log.i("musicInfo", "Moving UP! mGridView: " + mGridView.getTranslationY() + " tArtistName: " + tArtistName.getTranslationY());
                        mGridView.setTranslationY(mGridView.getTranslationY() - 1);
                        tArtistName.setTranslationY(tArtistName.getTranslationY() - 1);

                    }
                } else if (dY > 5 && dY <= 200 || (dY <= 5 && tArtistName.getTranslationY() < 0)) {
                    while (tArtistName.getTranslationY() < 0) {
                        //Log.i("musicInfo", "Moving DOWN! mGridView: " + mGridView.getTranslationY() + " tArtistName: " + tArtistName.getTranslationY());
                        mGridView.setTranslationY(mGridView.getTranslationY() + 1);
                        tArtistName.setTranslationY(tArtistName.getTranslationY() + 1);
                    }
                    imageLoader.pause();
                }
                break;

            case MotionEvent.ACTION_MOVE:
                //isMove = true;

                //int top = tArtistName.getTop();
                //int bottom = tArtistName.getBottom();
                //int left = tArtistName.getLeft();
                //int right = tArtistName.getRight();

                int x = (int) (event.getRawX() - mTouchX);
                int y = (int) (event.getRawY() - mTouchY);

                final int num = 5;
                if (y > -num && y < num) {
                    //isMove = false;
                    break;
                } else if (y > 0) {

                } else {
                    imageFrame.bringChildToFront(mGridView);
                    tArtistName.setTranslationY((float) y);
                    mGridView.setTranslationY((float) (SGVtransition + y));

                    //Log.i("musicInfo", String.format("T: %d, B: %d", mGridView.getTop(), mGridView.getBottom()));

                }

                break;
            }
            return true;
        }
    });

    ArtistImage = (ImageView) findViewById(R.id.artist_image);

    lLinkList = (LinearLayout) findViewById(R.id.l_link_list);

    mGridView = (StaggeredGridView) findViewById(R.id.SG_view);

    SGVtransition = 900;

    mGridView.setTranslationY(SGVtransition);

    JSONObject artist_info = null;
    try {
        artist_info = new JSONObject(b.getString("artist_info"));
        Log.i("musicInfo", "LinkPopUp. OnCreate" + artist_info.toString());
        displayArtistInfo(artist_info);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (artist_info != null)
        jArtists.put(artist_info);
    if (prefs.getBoolean("SimilarOn", false)) {
        getSimilarArtistsInfo((String) tArtistName.getText());
        ArtistImage.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    //isMove = false;
                    mTouchX = event.getRawX();
                    mTouchY = event.getRawY();
                    break;

                case MotionEvent.ACTION_UP:
                    //Log.i("musicInfo", "ACTION_UP! TouchY:" + mTouchY + " UpY: " + event.getRawY() + " Move: " + (mTouchY - event.getRawY()));
                    int dX = (int) (mTouchX - event.getRawX());
                    if (dX > 5) {
                        if (jArtists.length() > 1) {
                            imageLoader.stop();
                            try {
                                if (artistNum == 0) {
                                    artistNum = jArtists.length() - 1;
                                } else {
                                    artistNum--;
                                }

                                displayArtistInfo(jArtists.getJSONObject(artistNum));
                                imageLoader.resume();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                    } else if (dX < -5) {
                        if (jArtists.length() > 1) {
                            imageLoader.stop();
                            try {
                                if (artistNum == jArtists.length() - 1) {
                                    artistNum = 0;
                                } else {
                                    artistNum++;
                                }
                                displayArtistInfo(jArtists.getJSONObject(artistNum));
                                imageLoader.resume();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    break;

                case MotionEvent.ACTION_MOVE:

                    break;
                }

                return true;
            }
        });
    }

    mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            //Log.d("musicInfo", "SGV onScrollStateChanged:" + scrollState);
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            //Log.d("musicInfo", "SGV onScroll firstVisibleItem:" + firstVisibleItem + " visibleItemCount:" + visibleItemCount + " totalItemCount:" + totalItemCount);
            // our handling
            if (!mHasRequestedMore) {
                int lastInScreen = firstVisibleItem + visibleItemCount;
                if (lastInScreen >= totalItemCount) {
                    //Log.d("musicInfo", "SGV onScroll lastInScreen - so load more");
                    mHasRequestedMore = true;
                    onLoadMoreItems();
                }
            }
        }

        private void onLoadMoreItems() {
            if (jVideoArray == null)
                return;
            final ArrayList<JSONObject> sampleData = generateImageData(jVideoArray);
            for (JSONObject data : sampleData) {
                mAdapter.add(data);
            }
            // stash all the data in our backing store
            mData.addAll(sampleData);
            // notify the adapter that we can update now
            mAdapter.notifyDataSetChanged();
            mHasRequestedMore = false;
        }
    });

    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), "Open the Video...", Toast.LENGTH_SHORT).show();
            StaggeredViewAdapter.ViewHolder vh = (StaggeredViewAdapter.ViewHolder) view.getTag();

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse((String) vh.url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            //finish();

        }

    });

    //int[] lArtistLinkPosition = new int[2];
    //int[] tArtistNamePosition = new int[2];

    //lArtistLink.getLocationOnScreen(lArtistLinkPosition);
    //tArtistName.getLocationOnScreen(tArtistNamePosition);

    //Log.d("musicInfo", "SGV transition = " + SGVtransition);
}

From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java

/**
 * Export data./*from ww  w . j a  v  a2  s .c  o m*/
 * 
 * @param descr
 *            description of the exported rule set
 * @param fn
 *            one of the predefined file names from {@link DataProvider}.
 */
private void exportData(final String descr, final String fn) {
    if (descr == null) {
        final EditText et = new EditText(this);
        Builder builder = new Builder(this);
        builder.setView(et);
        builder.setCancelable(true);
        builder.setTitle(R.string.export_rules_descr);
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                Preferences.this.exportData(et.getText().toString(), fn);
            }
        });
        builder.show();
    } else {
        final ProgressDialog d = new ProgressDialog(this);
        d.setIndeterminate(true);
        d.setMessage(this.getString(R.string.export_progr));
        d.setCancelable(false);
        d.show();

        // run task in background
        final AsyncTask<Void, Void, String> task = // .
                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(final Void... params) {
                        if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                            return DataProvider.backupRuleSet(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                            return DataProvider.backupLogs(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                            return DataProvider.backupNumGroups(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                            return DataProvider.backupHourGroups(Preferences.this, descr);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final String result) {
                        Log.d(TAG, "export:\n" + result);
                        System.out.println("\n" + result);
                        d.dismiss();
                        if (result != null && result.length() > 0) {
                            Uri uri = null;
                            int resChooser = -1;
                            if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                                uri = DataProvider.EXPORT_RULESET_URI;
                                resChooser = R.string.export_rules_;
                            } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                                uri = DataProvider.EXPORT_LOGS_URI;
                                resChooser = R.string.export_logs_;
                            } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_NUMGROUPS_URI;
                                resChooser = R.string.export_numgroups_;
                            } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_HOURGROUPS_URI;
                                resChooser = R.string.export_hourgroups_;
                            }
                            final Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType(DataProvider.EXPORT_MIMETYPE);
                            intent.putExtra(Intent.EXTRA_STREAM, uri);
                            intent.putExtra(Intent.EXTRA_SUBJECT, // .
                                    "Call Meter 3G export");
                            intent.addCategory(Intent.CATEGORY_DEFAULT);

                            try {
                                final File d = Environment.getExternalStorageDirectory();
                                final File f = new File(d, DataProvider.PACKAGE + File.separator + fn);
                                f.mkdirs();
                                if (f.exists()) {
                                    f.delete();
                                }
                                f.createNewFile();
                                FileWriter fw = new FileWriter(f);
                                fw.append(result);
                                fw.close();
                                // call an exporting app with the uri to the
                                // preferences
                                Preferences.this.startActivity(
                                        Intent.createChooser(intent, Preferences.this.getString(resChooser)));
                            } catch (IOException e) {
                                Log.e(TAG, "error writing export file", e);
                                Toast.makeText(Preferences.this, R.string.err_export_write, Toast.LENGTH_LONG)
                                        .show();
                            }
                        }
                    }
                };
        task.execute((Void) null);
    }
}

From source file:it.chefacile.app.MainActivity.java

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this).setIcon(R.drawable.logo).setTitle("Exit").setMessage("Are you sure?")
            .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                @Override/*from   www .  java 2 s . c  o m*/
                public void onClick(DialogInterface dialog, int which) {

                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
                    startActivity(intent);
                    finish();
                    System.exit(0);
                }
            }).setNegativeButton("no", null).show();
}

From source file:com.egloos.hyunyi.musicinfo.LinkPopUp.java

private void displayArtistInfo(JSONObject j) throws JSONException {
    if (imageLoader == null)
        imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited())
        imageLoader.init(config);/*from   w ww  .  j av  a 2 s. c o  m*/

    Log.i("musicInfo", "LinkPopUp. displayArtistInfo " + j.toString());

    //JSONObject j_artist_info = j.getJSONObject("artist");

    final String artist_name = j.getString("name");

    tArtistName.setText(artist_name);
    final JSONObject urls = j.optJSONObject("urls");
    final JSONArray videos = j.optJSONArray("video");
    final JSONArray images = j.optJSONArray("images");

    final String msg = artist_name.replaceAll("\\p{Punct}", " ").replaceAll("\\p{Space}", "+");

    AsyncHttpClient client = new AsyncHttpClient();

    String fmURL = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + msg
            + "&autocorrect[1]&format=json&api_key=ca4c10f9ae187ebb889b33ba12da7ee9";
    Log.i("musicInfo", fmURL);

    client.get(fmURL, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String r = new String(responseBody);
            ArrayList<String> image_urls = new ArrayList<String>();

            try {
                Log.i("musicInfo", "Communicating with LastFM...");

                JSONObject json = new JSONObject(r);
                Log.i("musicInfo", json.toString());

                json = json.getJSONObject("artist");
                Log.i("musicInfo", json.toString());

                JSONArray artist_images = json.optJSONArray("image");
                Log.i("musicInfo", artist_images.toString());

                for (int i = 0; i < artist_images.length(); i++) {
                    JSONObject j = artist_images.getJSONObject(i);
                    Log.i("musicInfo", j.optString("size"));
                    if (j.optString("size").contains("extralarge")) {
                        image_urls.add(j.optString("#text"));
                        //b.putString("fm_image", j.getString("#text"));
                        //Log.i("musicInfo", j.getString("#text"));
                        break;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (images != null) {
                for (int i = 0; i < images.length(); i++) {
                    JSONObject image = null;
                    try {
                        image = images.getJSONObject(i);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    int width = image.optInt("width", 0);
                    int height = image.optInt("height", 0);
                    String url = image.optString("url", "");
                    Log.i("musicInfo", i + ": " + url);
                    if ((width * height > 10000) && (width * height < 100000)
                            && (!url.contains("userserve-ak"))) {
                        //if ((width>300&&width<100)&&(height>300&&height<1000)&&(!url.contains("userserve-ak"))) {
                        image_urls.add(url);
                        Log.i("musicInfo", "Selected: " + url);
                        //available_images.put(image);
                    }
                }
            }

            int random = (int) (Math.random() * image_urls.size());
            final String f_url = image_urls.get(random);

            Log.i("musicInfo",
                    "Total image#=" + image_urls.size() + " Selected image#=" + random + " " + f_url);

            if (image_urls.size() > 0) {
                imageLoader.displayImage(f_url, ArtistImage, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        lLinkList.removeAllViews();
                        //String attr = fImage.optJSONObject("license").optString("attribution");
                        //tAttribution.setText("Credit. " + ((attr == null) || (attr.contains("n/a")) ? "Unknown" : attr));
                        if (urls != null) {
                            String[] jsonName = { "wikipedia_url", "mb_url", "lastfm_url", "official_url",
                                    "twitter_url" };
                            for (int i = 0; i < jsonName.length; i++) {
                                if ((urls.optString(jsonName[i]) != null)
                                        && (urls.optString(jsonName[i]) != "")) {
                                    Log.d("musicinfo", "Link URL: " + urls.optString(jsonName[i]));
                                    TextView tv = new TextView(getApplicationContext());
                                    tv.setTextSize(11);
                                    tv.setPadding(16, 16, 16, 16);
                                    tv.setTextColor(Color.LTGRAY);
                                    tv.setTypeface(Typeface.SANS_SERIF);
                                    tv.setGravity(Gravity.CENTER_VERTICAL);

                                    switch (jsonName[i]) {
                                    case "official_url":
                                        tv.setText("HOME.");
                                        break;
                                    case "wikipedia_url":
                                        tv.setText("WIKI.");
                                        break;
                                    case "mb_url":
                                        tv.setText("Music Brainz.");
                                        break;
                                    case "lastfm_url":
                                        tv.setText("Last FM.");
                                        break;
                                    case "twitter_url":
                                        tv.setText("Twitter.");
                                        break;
                                    }

                                    try {
                                        tv.setTag(urls.getString(jsonName[i]));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    tv.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent = new Intent();
                                            intent.setAction(Intent.ACTION_VIEW);
                                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                                            intent.setData(Uri.parse((String) v.getTag()));
                                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            startActivity(intent);
                                            Toast.makeText(getApplicationContext(), "Open the Link...",
                                                    Toast.LENGTH_SHORT).show();
                                            //finish();
                                        }
                                    });
                                    lLinkList.addView(tv);
                                }
                            }
                        } else {
                            TextView tv = new TextView(getApplicationContext());
                            tv.setTextSize(11);
                            tv.setPadding(16, 16, 16, 16);
                            tv.setTextColor(Color.LTGRAY);
                            tv.setTypeface(Typeface.SANS_SERIF);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            tv.setText("Sorry, No Link Here...");
                            lLinkList.addView(tv);
                        }

                        if (videos != null) {
                            jVideoArray = videos;
                            mAdapter = new StaggeredViewAdapter(getApplicationContext(),
                                    android.R.layout.simple_list_item_1, generateImageData(videos));
                            //if (mData == null) {
                            mData = generateImageData(videos);
                            //}

                            //mAdapter.clear();

                            for (JSONObject data : mData) {
                                mAdapter.add(data);
                            }
                            mGridView.setAdapter(mAdapter);
                        } else {

                        }

                        adjBottomColor(((ImageView) view).getDrawable());
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {

                    }
                });
            } else {
                ArtistImage.setImageResource(R.drawable.lamb_no_image_available);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}

From source file:com.example.google.play.apkx.SampleDownloaderActivity.java

private void launchDownloader() {
    try {/* w w  w.  j a v  a2 s  .  com*/
        Intent launchIntent = SampleDownloaderActivity.this.getIntent();
        Intent intentToLaunchThisActivityFromNotification = new Intent(SampleDownloaderActivity.this,
                SampleDownloaderActivity.this.getClass());
        intentToLaunchThisActivityFromNotification
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());

        if (launchIntent.getCategories() != null) {
            for (String category : launchIntent.getCategories()) {
                intentToLaunchThisActivityFromNotification.addCategory(category);
            }
        }

        if (DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
                PendingIntent.getActivity(SampleDownloaderActivity.this, 0,
                        intentToLaunchThisActivityFromNotification, PendingIntent.FLAG_UPDATE_CURRENT),
                SampleDownloaderService.class) != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
            initializeDownloadUI();
            return;
        } // otherwise we fall through to starting the movie
    } catch (NameNotFoundException e) {
        Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
        e.printStackTrace();
    }
}

From source file:com.android.launcher3.Utilities.java

private static void changeDefaultLauncher(Context context) {
    PackageManager packageManager = context.getPackageManager();
    ComponentName componentName = new ComponentName(context, FakeActivity.class);
    packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    Intent selector = new Intent(Intent.ACTION_MAIN);
    selector.addCategory(Intent.CATEGORY_HOME);
    selector.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(selector);/*from  w w w  .ja v  a2  s  .c  o m*/

    packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
            PackageManager.DONT_KILL_APP);
}

From source file:com.dwdesign.tweetings.activity.ImageViewerActivity.java

@Override
public void onClick(final View view) {
    final Uri uri = getIntent().getData();
    switch (view.getId()) {
    case R.id.close: {
        onBackPressed();/*from  ww  w . ja  va  2s. c om*/
        break;
    }
    case R.id.refresh_stop_save: {
        if (!mImageLoaded && !mImageLoading) {
            loadImage();
        } else if (!mImageLoaded && mImageLoading) {
            stopLoading();
        } else if (mImageLoaded) {
            saveImage();
        }
        break;
    }
    case R.id.share: {
        if (uri == null) {
            break;
        }
        final Intent intent = new Intent(Intent.ACTION_SEND);
        final String scheme = uri.getScheme();
        if ("file".equals(scheme)) {
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        } else {
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, uri.toString());
        }
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
        break;
    }
    case R.id.open_in_browser: {
        if (uri == null) {
            break;
        }
        final String scheme = uri.getScheme();
        if ("http".equals(scheme) || "https".equals(scheme)) {
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            try {
                startActivity(intent);
            } catch (final ActivityNotFoundException e) {
                // Ignore.
            }
        }
        break;
    }
    }
}

From source file:net.bluecarrot.lite.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // if the app is being launched for the first time
    if (savedPreferences.getBoolean("first_run", true)) {
        //todo presentation
        // save the fact that the app has been started at least once
        savedPreferences.edit().putBoolean("first_run", false).apply();
    }/*from  w w w . j  av  a 2s  .  c  o  m*/

    setContentView(R.layout.activity_main);//load the layout

    //**MOBFOX***//

    banner = (Banner) findViewById(R.id.banner);
    final Activity self = this;

    banner.setListener(new BannerListener() {
        @Override
        public void onBannerError(View view, Exception e) {
            //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerLoaded(View view) {
            //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClosed(View view) {
            //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerFinished(View view) {
            // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClicked(View view) {
            //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onCustomEvent(JSONArray jsonArray) {
            return false;
        }
    });

    banner.setInventoryHash(appHash);
    banner.load();

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialBlueFacebook, R.color.darkBlueSlimFacebookTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    /** get a subject and text and check if this is a link trying to be shared */
    String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT);
    String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT);

    // if we have a valid URL that was shared by us, open the sharer
    if (sharedUrl != null) {
        if (!sharedUrl.equals("")) {
            // check if the URL being shared is a proper web URL
            if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
                // if it's not, let's see if it includes an URL in it (prefixed with a message)
                int startUrlIndex = sharedUrl.indexOf("http:");
                if (startUrlIndex > 0) {
                    // seems like it's prefixed with a message, let's trim the start and get the URL only
                    sharedUrl = sharedUrl.substring(startUrlIndex);
                }
            }
            // final step, set the proper Sharer...
            urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject);
            // ... and parse it just in case
            urlSharer = Uri.parse(urlSharer).toString();
            isSharer = true;
        }
    }

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);
    //fits images to screen

    if (isSharer) {//if is a share request
        webViewFacebook.loadUrl(urlSharer);//load the sharer url
        isSharer = false;
    } else
        goHome();//load homepage

    //        webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
    //            public void onSwipeLeft() {
    //                webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" +
    //                        getString(R.string.urlFacebookMobile) + "messages/';}");
    //            }
    //
    //        });

    //WebViewClient that is the client callback.
    webViewFacebook.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>"
                    + getString(R.string.titleNoConnection) + "</h1> <h3 "
                    + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='font-size:30px; text-align:center; padding-top:80%; "
                    + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>";
            webViewFacebook.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || Uri.parse(url).getHost().endsWith("facebook.com")
                    || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) {
                //url is ok
                return false;
            } else {
                if (Uri.parse(url).getHost().endsWith("fbcdn.net")) {
                    //TODO add the possibility to download and share directly

                    Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser),
                            Toast.LENGTH_LONG).show();
                    //TODO get bitmap from url

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //if the link doesn't contain 'facebook.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } //https://www.facebook.com/dialog/return/close?#_=_
        }

        //START management of loading
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //TODO when I push on messages, open messanger
            //                if(url!=null){
            //                    if (url.contains("soft=messages") || url.contains("facebook.com/messages")) {
            //                        Toast.makeText(getApplicationContext(),"Open Messanger",
            //                                Toast.LENGTH_SHORT).show();
            //                        startActivity(new Intent(getPackageManager().getLaunchIntentForPackage("com.facebook.orca")));//messanger
            //                    }
            //                }

            // show you progress image
            if (!swipeRefresh) {
                if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                    final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                    refreshItem.setActionView(R.layout.circular_progress_bar);
                }
            }
            swipeRefresh = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(null);
            }

            //load the css customizations
            String css = "";
            if (savedPreferences.getBoolean("pref_blackTheme", false)) {
                css += getString(R.string.blackCss);
            }
            if (savedPreferences.getBoolean("pref_fixedBar", true)) {

                css += getString(R.string.fixedBar);//get the first part

                int navbar = 0;//default value
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id
                if (resourceId > 0) {//if there is
                    navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension
                }
                float density = getResources().getDisplayMetrics().density;
                int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44)
                        / density);

                css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll;  }";//without this doen-t scroll

            }
            if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) {
                css += getString(R.string.hideSponsoredPost);
            }

            //apply the customizations
            webViewFacebook.loadUrl(
                    "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = "
                            + "str; document.body.appendChild(node); } addStyleString('" + css + "');");

            //finish the load
            super.onPageFinished(view, url);

            //when the page is loaded, stop the refreshing
            swipeRefreshLayout.setRefreshing(false);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to the Geolocation
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            //todo notify when the gps is used
        }

        //to upload files
        //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
        // for >= Lollipop, all in one
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            /** Request permission for external storage access.
             *  If granted it's awesome and go on,
             *  otherwise just stop here and leave the method.
             */
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(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
                    Toast.makeText(getApplicationContext(), "Error occurred while creating the File",
                            Toast.LENGTH_LONG).show();
                }

                // 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("image/*");

            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, getString(R.string.chooseAnImage));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

            return true;
        }

        // creating image files (Lollipop only)
        private File createImageFile() throws IOException {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }

            // create an image file name
            imageStorageDir = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            return imageStorageDir;
        }

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            mUploadMessage = uploadMsg;

            try {
                File imageStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        appDirectoryName);

                if (!imageStorageDir.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    imageStorageDir.mkdirs();
                }

                File file = new File(imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis()) + ".jpg");

                mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

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

                Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage));
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });

                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show();
            }
        }

        // openFileChooser for other Android versions

        /**
         * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
         * https://code.google.com/p/android/issues/detail?id=62220
         * however newer versions of KitKat fixed it on some devices
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

    });

    // OnLongClickListener for detecting long clicks on links and images
    // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
    webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // activate long clicks on links and image links according to settings
            if (true) {
                WebView.HitTestResult result = webViewFacebook.getHitTestResult();
                if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
                        || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    Message msg = linkHandler.obtainMessage();
                    webViewFacebook.requestFocusNodeHref(msg);
                    return true;
                }
            }
            return false;
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.dwdesign.gallery3d.app.ImageViewerGLActivity.java

@Override
public void onClick(final View view) {
    final Uri uri = getIntent().getData();
    switch (view.getId()) {
    case R.id.close: {
        onBackPressed();//from  ww w  .jav  a 2s  .c om
        break;
    }
    case R.id.refresh_stop_save: {
        final LoaderManager lm = getSupportLoaderManager();
        if (!mImageLoaded && !lm.hasRunningLoaders()) {
            loadImage();
        } else if (!mImageLoaded && lm.hasRunningLoaders()) {
            stopLoading();
        } else if (mImageLoaded) {
            new SaveImageTask(this, mImageFile).execute();
        }
        break;
    }
    case R.id.share: {
        if (uri == null) {
            break;
        }
        final Intent intent = new Intent(Intent.ACTION_SEND);
        if (mImageFile != null && mImageFile.exists()) {
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mImageFile));
        } else {
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, uri.toString());
        }
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
        break;
    }
    case R.id.open_in_browser: {
        if (uri == null) {
            break;
        }
        final String scheme = uri.getScheme();
        if ("http".equals(scheme) || "https".equals(scheme)) {
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            try {
                startActivity(intent);
            } catch (final ActivityNotFoundException e) {
                // Ignore.
            }
        }
        break;
    }
    }
}