Example usage for android.content Intent setData

List of usage examples for android.content Intent setData

Introduction

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

Prototype

public @NonNull Intent setData(@Nullable Uri data) 

Source Link

Document

Set the data this intent is operating on.

Usage

From source file:com.irccloud.android.Notifications.java

public NotificationCompat.Builder alert(int bid, String title, String body) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext()).setContentTitle(title)
                    .setContentText(body).setTicker(body).setAutoCancel(true).setColor(IRCCloudApplication
                            .getInstance().getApplicationContext().getResources().getColor(R.color.dark_blue))
                    .setSmallIcon(R.drawable.ic_stat_notify);

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    builder.setContentIntent(// w ww  .j  ava2s  .  com
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(bid,
            builder.build());

    return builder;
}

From source file:com.etalio.android.EtalioBase.java

/**
 * Requests an access token and a refresh token from Etalio
 *///from w w  w  .j a v  a 2s.c  o m
protected void authorizeAndAcquireTokensFromCallback(final Intent intent, final AuthenticationCallback callback)
        throws EtalioAuthorizationCodeException {
    if (!isEtalioSignInCallback(intent)) {
        throw new IllegalArgumentException("The intent does not contain a valid authentication callback.");
    }
    //set the code for later
    final String code = getAuthorizationCodeFromUri(intent.getData());
    //Reset intent data to not trigger this call again.
    if (intent != null) {
        intent.setData(null);
    }

    new AsyncTask<String, Void, Boolean>() {

        public EtalioTokenException error;

        @Override
        protected Boolean doInBackground(String... params) {
            //get and set the access/refresh tokens
            try {
                requestNewToken(params[0]);
            } catch (EtalioTokenException e) {
                this.error = e;
                return false;
            } catch (IOException e) {
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (callback != null) {
                if (result) {
                    callback.onAuthenticationSuccess();
                } else {
                    callback.onAuthenticationFailure(this.error);
                }
            }
        }
    }.execute(code);
}

From source file:com.dtworkshop.inappcrossbrowser.WebViewBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @return              "" if ok, or error message.
 *///  w  w w  .  j a v  a  2  s  . co m
public String openExternal(String url) {
    try {
        Intent intent = null;
        intent = new Intent(Intent.ACTION_VIEW);
        // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
        // Adding the MIME type to http: URLs causes them to not be handled by the downloader.
        Uri uri = Uri.parse(url);
        if ("file".equals(uri.getScheme())) {
            intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
        } else {
            intent.setData(uri);
        }
        this.cordova.getActivity().startActivity(intent);
        return "";
    } catch (android.content.ActivityNotFoundException e) {
        Log.d(LOG_TAG, "InAppBrowser: Error loading url " + url + ":" + e.toString());
        return e.toString();
    }
}

From source file:com.usertaxi.TaxiOntheWay_Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiontheway);

    taxiOntheWay_activity_instance = this;
    AppPreferences.setApprequestTaxiScreen(TaxiOntheWay_Activity.this, true);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);//from   w ww. j av  a2  s . c o  m
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);
    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    FloatingActionButton fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    FloatingActionButton fab_call = (FloatingActionButton) findViewById(R.id.fab_call);
    FloatingActionButton fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    textheader = (TextView) findViewById(R.id.textheader);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");
    textheader.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);
    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);

    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    Log.d("data value", data + "");

    //caceldialog();
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(data);
        AppPreferences.setAcceptdriverId(TaxiOntheWay_Activity.this, jsonObject.getString("driverId"));
        Log.d("driverid---", AppPreferences.getAcceptdriverId(TaxiOntheWay_Activity.this));
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        //driverlatitude = jsonObject.getDouble("latitude");
        //driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        //            Log.d("longitudeeeee:------", String.valueOf(jsonObject.getDouble("longitude")));

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        final MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        //  marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }
        //taxiname.setText(drivertaxiname);

        Intent intent1 = new Intent(TaxiOntheWay_Activity.this, DriverService.class);
        intent1.putExtra("driverId", jsonObject.getString("driverId"));
        startService(intent1);

        if (driverimage.equalsIgnoreCase("")) {
            mdriverimage.setImageResource(R.drawable.ic_action_user);
        } else {
            Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                    .resize(200, 200).into(mdriverimage);
        }

        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                        /* try{
                             String url = Function.getDirectionsUrl(new LatLng(Double.parseDouble(AppPreferences.getPreviouslat(getApplicationContext())),
                                     Double.parseDouble(AppPreferences.getPreviouslong(getApplicationContext()))),
                                     new LatLng(Double.parseDouble(AppPreferences.getCurrentlat(getApplicationContext())),
                                             Double.parseDouble(AppPreferences.getCurrentlong(getApplicationContext()))));
                             RoutesDownloadTask downloadTask = new RoutesDownloadTask(TaxiOntheWay_Activity.this);
                             downloadTask.execute(url);
                         }catch(Exception e)
                         {
                             e.printStackTrace();
                         }*/
                    }
                });
            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    /////////////notification dataend///////////////

    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();

        }
    });
    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });
    fab_call.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + drivermobile));
            startActivity(callIntent);
        }
    });

    moveMarkerList = new ArrayList<LatLng>();
    //        moveRoadMarker();
}

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  .  ja  v a2 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:cn.edu.wyu.documentviewer.DocumentsActivity.java

private void onFinished(Uri... uris) {
    Log.d(TAG, "onFinished() " + Arrays.toString(uris));

    final Intent intent = new Intent();
    if (uris.length == 1) {
        intent.setData(uris[0]);
    } else if (uris.length > 1) {
        final ClipData clipData = new ClipData(null, mState.acceptMimes, new ClipData.Item(uris[0]));
        for (int i = 1; i < uris.length; i++) {
            clipData.addItem(new ClipData.Item(uris[i]));
        }/*from  w w  w .  j  a  v a  2 s .c  om*/
        intent.setClipData(clipData);
    }

    if (mState.action == ACTION_GET_CONTENT) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    }

    setResult(Activity.RESULT_OK, intent);
    finish();
}

From source file:cn.edu.wyu.documentviewer.DocumentsActivity.java

public void onDocumentPicked(DocumentInfo doc) {
    final FragmentManager fm = getFragmentManager();
    if (doc.isDirectory()) {
        if (DEBUG) {
            Log.i(TAG, "onDocumentPicked()+directory");
        }//from  w  ww  .  j  av a  2  s .c  om
        mState.stack.push(doc);
        mState.stackTouched = true;
        onCurrentDirectoryChanged(ANIM_DOWN);
    } else if (mState.action == ACTION_OPEN || mState.action == ACTION_GET_CONTENT) {
        // Explicit file picked, return
        if (DEBUG) {
            Log.i(TAG, "onDocumentPicked() " + mState.action);
        }
        new ExistingFinishTask(doc.derivedUri).executeOnExecutor(getCurrentExecutor());

        //           final Intent view = new Intent(Intent.ACTION_VIEW);
        //            view.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //            view.setData(doc.derivedUri);

        //            try {
        //                startActivity(view);
        //            } catch (ActivityNotFoundException ex2) {
        //                Toast.makeText(this, R.string.toast_no_application, Toast.LENGTH_SHORT).show();
        //            }            
    } else if (mState.action == ACTION_CREATE) {
        // Replace selected file
        if (DEBUG) {
            Log.i(TAG, "onDocumentPicked() " + mState.action);
        }
        SaveFragment.get(fm).setReplaceTarget(doc);
    } else if (mState.action == ACTION_MANAGE) {
        // First try managing the document; we expect manager to filter
        // based on authority, so we don't grant.
        if (DEBUG) {
            Log.i(TAG, "onDocumentPicked() " + mState.action);
        }
        final Intent manage = new Intent(DocumentsContract.ACTION_MANAGE_DOCUMENT);
        manage.setData(doc.derivedUri);

        try {
            startActivity(manage);
        } catch (ActivityNotFoundException ex) {
            // Fall back to viewing
            final Intent view = new Intent(Intent.ACTION_VIEW);
            view.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            view.setData(doc.derivedUri);

            try {
                startActivity(view);
            } catch (ActivityNotFoundException ex2) {
                Toast.makeText(this, R.string.toast_no_application, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

From source file:com.jamiealtizer.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param usePhoneGap   Load url in PhoneGap webview
 * @return              "" if ok, or error message.
 *///from   ww  w .j a v  a2 s .c  o  m
public String openExternal(String url) {
    try {
        Intent intent = null;
        intent = new Intent(Intent.ACTION_VIEW);
        // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
        // Adding the MIME type to http: URLs causes them to not be handled by the downloader.
        Uri uri = Uri.parse(url);
        if ("file".equals(uri.getScheme())) {
            intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
        } else {
            intent.setData(uri);
        }
        intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
        this.cordova.getActivity().startActivity(intent);
        return "";
    } catch (android.content.ActivityNotFoundException e) {
        Log.d(LOG_TAG, "InAppBrowser: Error loading url " + url + ":" + e.toString());
        return e.toString();
    }
}

From source file:com.irccloud.android.Notifications.java

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title,
        String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network,
        String auto_messages[]) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());

    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext())
                    .setContentTitle(title + ((network != null) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.dark_blue))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE);
        String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound");
        if (ringtone != null && ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }/*from ww w. j a va  2  s. c o  m*/

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(
                    android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE);
        else
            builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS);
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    if (replyIntent != null) {
        WearableExtender extender = new WearableExtender();
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
        extender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_reply, "Reply", replyPendingIntent)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                        .build());

        if (count > 1 && wear_text != null)
            extender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true))
                            .build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (auto_messages != null) {
            for (String m : auto_messages) {
                if (m != null && m.length() > 0) {
                    unreadConvBuilder.addMessage(m);
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(extender)
                .extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    android.app.Notification notification = builder.build();

    RemoteViews contentView = new RemoteViews(
            IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification);
    contentView.setTextViewText(R.id.title, title + " (" + network + ")");
    contentView.setTextViewText(R.id.text,
            (count == 1) ? Html.fromHtml(text) : (count + " unread highlights."));
    contentView.setLong(R.id.time, "setTime", eids[0] / 1000);
    notification.contentView = contentView;

    if (Build.VERSION.SDK_INT >= 16 && big_text != null) {
        RemoteViews bigContentView = new RemoteViews(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                R.layout.notification_expanded);
        bigContentView.setTextViewText(R.id.title,
                title + (!title.equals(network) ? (" (" + network + ")") : ""));
        bigContentView.setTextViewText(R.id.text, big_text);
        bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
        if (count > 3) {
            bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
            bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
        } else {
            bigContentView.setViewVisibility(R.id.more, View.GONE);
        }
        if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
            bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
            bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
            i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
            i.setData(Uri.parse("irccloud-bid://" + bid));
            i.putExtras(replyIntent);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent quickReplyIntent = PendingIntent.getActivity(
                    IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
        }
        notification.bigContentView = bigContentView;
    }

    return notification;
}

From source file:in.shick.diode.user.ProfileActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.compose_message_menu_id:
        if (mSettings.isLoggedIn()) {
            showDialog(Constants.DIALOG_COMPOSE);
        } else {//  w w  w .j  av a2 s. c  om
            showDialog(Constants.DIALOG_LOGIN);
        }
        break;
    case R.id.saved_menu_id:
        if (mSettings.isLoggedIn()) {
            Intent intent = new Intent(getApplicationContext(), ThreadsListActivity.class);
            intent.setData(Util.createSavedUri(mSettings.getUsername()));
            startActivity(intent);
            Util.overridePendingTransition(null, this, android.R.anim.slide_in_left,
                    android.R.anim.slide_out_right);
        }
        break;

    case R.id.refresh_menu_id:
        new DownloadProfileTask(mUsername).execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        break;
    case android.R.id.home:
        Common.goHome(this);
        break;
    }

    return true;
}