Example usage for android.graphics BitmapFactory decodeResource

List of usage examples for android.graphics BitmapFactory decodeResource

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeResource.

Prototype

public static Bitmap decodeResource(Resources res, int id) 

Source Link

Document

Synonym for #decodeResource(Resources,int,android.graphics.BitmapFactory.Options) with null Options.

Usage

From source file:com.appjma.appdeployer.AppFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.app_fragment, container, false);

    mTokenFormat = getString(R.string.app_token_format);
    mGuidFormat = getString(R.string.app_guid_format);

    mListView = (ListView) view.findViewById(android.R.id.list);
    mProgressBar = view.findViewById(android.R.id.progress);
    mEmptyView = view.findViewById(android.R.id.empty);

    mErrorReporter = new ErrorReporter(getActivity(), view, AppContract.AppVersions.CONTENT_URI);

    Bitmap placeHolder = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
    mRemoteImageLoader = RemoteImageLoader.createUsingDp(getActivity(), placeHolder, IMAGE_SIZE_DP,
            IMAGE_SIZE_DP);/*  www  . j a v  a 2 s . c o  m*/

    mDownloadHelper = new DownloadHelper(getActivity(), DownloadService.ACTION_SYNC, this,
            Uri.withAppendedPath(mUri, AppContract.AppVersions.CONTENT_PATH));

    mListView.addHeaderView(createHeaderView(inflater));
    mAdapter = new AppVersionsAdapter(getActivity(), this);
    mListView.setAdapter(mAdapter);
    LoaderManager lm = getLoaderManager();
    lm.initLoader(LOADER_APP, null, this);
    lm.initLoader(LOADER_APP_VERSIONS, null, this);
    lm.initLoader(LOADER_DOWNLOADS, null, mLoaderCallback);

    setHasOptionsMenu(true);

    return view;
}

From source file:com.app.jdy.widget.CustomForwardDialog.java

/**
 * //from w w w  . jav a  2 s.co  m
 * @author Owater
 * @createtime 2015-1-25 ?4:14:15
 * @Decription ??
 *
 * @param id
 */
private void sendUrl(String rid) {
    WXWebpageObject webpage = new WXWebpageObject();
    webpage.webpageUrl = URLs.WX_SHARE_RESULT_URL + "/" + map.get("ID") + "-" + map.get("prodTypeCode") + "-"
            + rid;
    WXMediaMessage msg = new WXMediaMessage(webpage);
    //      msg.title = map.get("shareSubject");
    //      msg.description = map.get("productSubject");
    msg.title = map.get("name");
    msg.description = map.get("shareSubject");
    Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
    msg.thumbData = WxUtil.bmpToByteArray(thumb, true);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("webpage");
    req.message = msg;
    req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
    api.sendReq(req);
}

From source file:fm.smart.r1.ItemActivity.java

static void setSound(ImageView sound_icon, final String sound_url, final Context context, final int type_id,
        final String artifact_id, final String to_record) {
    if (!TextUtils.isEmpty(sound_url)) {
        OnClickListener sound_listener = new OnClickListener() {
            public void onClick(View v) {// TODO removed temporarily
                MediaUtility.playSound(sound_url, ItemListActivity.mMediaPlayer, context);
            }/* w ww.j  av a 2s  .  c o m*/
        };
        sound_icon.setOnClickListener(sound_listener);
        sound_icon
                .setImageBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.active_sound));
    } else {
        if (type_id == R.id.response_sound || type_id == R.id.translation_sound) {
            sound_icon.setVisibility(View.INVISIBLE);
        } else {
            sound_icon.setImageBitmap(
                    BitmapFactory.decodeResource(context.getResources(), R.drawable.inactive_sound_add));

            OnClickListener listener = new OnClickListener() {
                public void onClick(View v) {
                    // TODO removed temporarily
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setClassName(context, CreateSoundActivity.class.getName());
                    AndroidUtils.putExtra(intent, "item_id", (String) item.getId());
                    AndroidUtils.putExtra(intent, "to_record", to_record);
                    AndroidUtils.putExtra(intent, "id", artifact_id);
                    AndroidUtils.putExtra(intent, "sound_type", Integer.toString(type_id));
                    context.startActivity(intent);

                }
            };
            sound_icon.setOnClickListener(listener);
        }
    }
}

From source file:fm.smart.r1.activity.ItemActivity.java

static void setSound(ImageView sound_icon, final String sound_url, final Context context, final int type_id,
        final String artifact_id, final String to_record) {
    if (!TextUtils.isEmpty(sound_url)) {
        OnClickListener sound_listener = new OnClickListener() {
            public void onClick(View v) {
                Main.playSound(sound_url, ItemListActivity.mMediaPlayer, context);
            }/*  w  w w  .j a v  a2s  .  co m*/
        };
        sound_icon.setOnClickListener(sound_listener);
    } else {
        if (type_id == R.id.response_sound || type_id == R.id.translation_sound) {
            sound_icon.setVisibility(View.INVISIBLE);
        } else {
            sound_icon.setImageBitmap(
                    BitmapFactory.decodeResource(context.getResources(), R.drawable.inactive_sound_add));

            OnClickListener listener = new OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setClassName(context, CreateSoundActivity.class.getName());
                    Utils.putExtra(intent, "item_id", (String) item.item_node.atts.get("id"));
                    Utils.putExtra(intent, "to_record", to_record);
                    Utils.putExtra(intent, "id", artifact_id);
                    Utils.putExtra(intent, "sound_type", Integer.toString(type_id));
                    context.startActivity(intent);

                }
            };
            sound_icon.setOnClickListener(listener);
        }
    }
}

From source file:com.gtx.cooliris.imagecache.ImageWorker.java

/**
 * Set placeholder bitmap that shows when the the background thread is running.
 *
 * @param resId//from ww  w. jav  a  2 s.  c om
 */
public void setLoadingImage(int resId) {
    mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId);
}

From source file:com.sina.weibo.sdk.demo.openapi.user_homeActivity.java

/**
 * @see {@link Activity#onCreate}//from  w  w w .  java2s.c  o m
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.weibo_item);
    //mLogoutButton = (Button) findViewById(R.id.logout);

    // ??? Token
    mAccessToken = AccessTokenKeeper.readAccessToken(this);
    // ???
    mUsersAPI = new UsersAPI(this, Constants.APP_KEY, mAccessToken);
    mStatusesAPI = new StatusesAPI(this, Constants.APP_KEY, mAccessToken);
    getUserInfo();

    //
    this.findViewById(R.id.home_page).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, mytestActivity.class));
        }
    });
    this.findViewById(R.id.send_page).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, WBStatus_sendAPIActivity.class));
        }
    });
    //
    //
    this.findViewById(R.id.fllowers).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, user_fllowers.class));
        }
    });
    //?
    this.findViewById(R.id.friends).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(user_homeActivity.this, user_friends.class));
        }
    });
    //
    mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);
    mWeiboShareAPI.registerApp();
    shearMessageReceiver = new ShearMessageReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_SHEAR_RESULT);
    registerReceiver(shearMessageReceiver, filter);
    this.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mWeiboShareAPI.isWeiboAppInstalled()) {
                Toast.makeText(user_homeActivity.this, "", Toast.LENGTH_LONG).show();
            }
            //
            if (true) {
                Bundle bundle = new Bundle();
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo);
                bundle.putString(WBConstants.SDK_WEOYOU_SHARETITLE, "share our app to others");
                bundle.putString(WBConstants.SDK_WEOYOU_SHAREDESC, "say something...");
                bundle.putString(WBConstants.SDK_WEOYOU_SHAREURL, "http://github/laterlater.com");
                bundle.putString("shareBackScheme", "weiboDemo://share");
                bundle.putString(SHARE_APP_NAME, "app name");
                bundle.putString(PARAM_SHARE_FROM, EXTEND_SHARE_570);
                bundle.putByteArray(WBConstants.SDK_WEOYOU_SHAREIMAGE, bitMapToBytes(bitmap));
                mWeiboShareAPI.shareMessageToWeiyou(user_homeActivity.this, bundle);
            } else {
                Toast.makeText(user_homeActivity.this, "?", Toast.LENGTH_LONG).show();
            }
        }
    });
    this.findViewById(R.id.logout).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mAccessToken != null && mAccessToken.isSessionValid()) {
                new LogoutAPI(user_homeActivity.this, Constants.APP_KEY, mAccessToken)
                        .logout(mLogoutRequestListener);
            }
        }
    });
}

From source file:com.alucas.snorlax.module.feature.encounter.EncounterNotification.java

@SuppressWarnings("deprecation")
void show(int pokemonNumber, String pokemonName, Gender gender, double iv, int attack, int defense, int stamina,
        int cp, double level, int hp, double baseWeight, double weight, double baseHeight, double height,
        MoveSettings fastMove, MoveSettings chargeMove, double fleeRate, double pokeRate, double greatRate,
        double ultraRate, PokemonType type1, PokemonType type2, PokemonRarity pokemonClass) {
    final double weightRatio = weight / baseWeight;
    final double heightRatio = height / baseHeight;
    final MODIFIER resourceModifier = (pokemonNumber == PokemonId.PIKACHU_VALUE ? MODIFIER.FAN
            : pokemonNumber == PokemonId.RATTATA_VALUE && heightRatio < 0.80 ? MODIFIER.YOUNGSTER
                    : pokemonNumber == PokemonId.MAGIKARP_VALUE && weightRatio > 1.30 ? MODIFIER.FISHERMAN
                            : MODIFIER.NO);

    final String genderSymbol = PokemonFormat.formatGender(mResources, gender);
    final String fastMoveName = PokemonFormat.formatMove(fastMove.getMovementId());
    final String chargeMoveName = PokemonFormat.formatMove(chargeMove.getMovementId());
    final String fastMoveTypeName = PokemonFormat.formatType(fastMove.getPokemonType());
    final String chargeMoveTypeName = PokemonFormat.formatType(chargeMove.getPokemonType());
    final String fastMoveTypeSymbol = TYPE_SYMBOL.containsKey(fastMove.getPokemonType())
            ? mResources.getString(TYPE_SYMBOL.get(fastMove.getPokemonType()))
            : "?";
    final String chargeMoveTypeSymbol = TYPE_SYMBOL.containsKey(chargeMove.getPokemonType())
            ? mResources.getString(TYPE_SYMBOL.get(chargeMove.getPokemonType()))
            : "?";

    final Map<String, Pair<String, Integer>> symbols = getSymbolReplacementTable();
    new Handler(Looper.getMainLooper()).post(() -> {
        Notification notification = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.drawable.ic_pokeball)
                .setLargeIcon(Bitmap.createScaledBitmap(
                        BitmapFactory.decodeResource(mResources,
                                Resource.getPokemonResourceId(mContext, mResources, pokemonNumber,
                                        resourceModifier)),
                        Resource.getLargeIconWidth(mResources), Resource.getLargeIconHeight(mResources), false))
                .setContentTitle(EncounterFormat.format(
                        mContext.getString(R.string.notification_title, genderSymbol, pokemonName, cp, level),
                        symbols))//w w  w  .  j  av a 2  s.  c o  m
                .setContentText(EncounterFormat.format(mContext.getString(R.string.notification_content, iv,
                        fleeRate, pokeRate, greatRate, ultraRate), symbols))
                .setStyle(new NotificationCompat.InboxStyle()
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_category_stats_content_iv, iv,
                                        attack, defense, stamina), symbols))
                        .addLine(EncounterFormat.format(mContext.getString(
                                R.string.notification_category_stats_content_hp, hp, fleeRate), symbols))
                        .addLine(EncounterFormat
                                .bold(mContext.getString(R.string.notification_category_moves_title)))
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_category_moves_fast,
                                        fastMoveName, fastMoveTypeName, fastMove.getPower()), symbols))
                        .addLine(
                                EncounterFormat.format(
                                        mContext.getString(R.string.notification_category_moves_charge,
                                                chargeMoveName, chargeMoveTypeName, chargeMove.getPower()),
                                        symbols))
                        .addLine(EncounterFormat
                                .bold(mContext.getString(R.string.notification_categoty_catch_title)))
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_categoty_catch_content,
                                        pokeRate, greatRate, ultraRate), symbols))
                        .setSummaryText(getFooter(type1, type2, pokemonClass)))
                .setColor(ContextCompat.getColor(mContext, R.color.red_700)).setAutoCancel(true)
                .setVibrate(new long[] { 0 }).setPriority(Notification.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_ALARM).build();

        hideIcon(notification);

        mNotificationManager.notify(NotificationId.ID_ENCOUNTER, notification);
    });
}

From source file:com.chilliworks.chillisource.core.LocalNotificationReceiver.java

/**
 * Called when a local notification broad cast is received. Funnels the notification
 * into the app if open or into the notification bar if not
 * //  w  w  w  .j  ava 2s.c om
 * @author Steven Hendrie
 * 
 * @param The context.
 * @param The intent.
 */
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context in_context, Intent in_intent) {
    //evaluate whether or not the main engine activity is in the foreground
    boolean isAppInForeground = false;
    if (CSApplication.get() != null && CSApplication.get().isActive() == true) {
        isAppInForeground = true;
    }

    //if the main engine activity is in the foreground, simply pass the
    //notification into it. Otherwise display a notification.
    if (isAppInForeground == true) {
        final Intent intent = new Intent(in_intent.getAction());
        Bundle mapParams = in_intent.getExtras();
        Iterator<String> iter = mapParams.keySet().iterator();

        while (iter.hasNext()) {
            String strKey = iter.next();
            intent.putExtra(strKey, mapParams.get(strKey).toString());
        }

        LocalNotificationNativeInterface localNotificationNI = (LocalNotificationNativeInterface) CSApplication
                .get().getSystem(LocalNotificationNativeInterface.InterfaceID);
        if (localNotificationNI != null) {
            localNotificationNI.onNotificationReceived(intent);
        }
    } else {
        //aquire a wake lock
        if (s_wakeLock != null) {
            s_wakeLock.release();
        }

        PowerManager pm = (PowerManager) in_context.getSystemService(Context.POWER_SERVICE);
        s_wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "NotificationWakeLock");
        s_wakeLock.acquire();

        //pull out the information from the intent
        Bundle params = in_intent.getExtras();
        CharSequence title = params.getString(k_paramNameTitle);
        CharSequence text = params.getString(k_paramNameBody);
        int intentId = params.getInt(LocalNotification.k_paramNameNotificationId);

        int paramSize = params.size();
        String[] keys = new String[paramSize];
        String[] values = new String[paramSize];
        Iterator<String> iter = params.keySet().iterator();
        int paramNumber = 0;
        while (iter.hasNext()) {
            keys[paramNumber] = iter.next();
            values[paramNumber] = params.get(keys[paramNumber]).toString();
            ++paramNumber;
        }

        Intent openAppIntent = new Intent(in_context, CSActivity.class);
        openAppIntent.setAction("android.intent.action.MAIN");
        openAppIntent.addCategory("android.intent.category.LAUNCHER");
        openAppIntent.putExtra(k_appOpenedFromNotification, true);
        openAppIntent.putExtra(k_arrayOfKeysName, keys);
        openAppIntent.putExtra(k_arrayOfValuesName, values);
        openAppIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent sContentIntent = PendingIntent.getActivity(in_context, intentId, openAppIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Bitmap largeIconBitmap = null;
        int LargeIconID = ResourceHelper.GetDynamicResourceIDForField(in_context,
                ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify_large");

        //Use small icon if no large icon
        if (LargeIconID == 0) {
            LargeIconID = ResourceHelper.GetDynamicResourceIDForField(in_context,
                    ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify");
        }

        if (LargeIconID > 0) {
            largeIconBitmap = BitmapFactory.decodeResource(in_context.getResources(), LargeIconID);
        }

        Notification notification = new NotificationCompat.Builder(in_context).setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(ResourceHelper.GetDynamicResourceIDForField(in_context,
                        ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify"))
                .setLargeIcon(largeIconBitmap).setContentIntent(sContentIntent).build();

        NotificationManager notificationManager = (NotificationManager) in_context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(intentId, notification);
        Toast.makeText(in_context, text, Toast.LENGTH_LONG).show();
    }
}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
    String actionName = intent.getStringExtra("actionName");
    if (intent == null || intent.getExtras() == null) {//just removing these checks
    } else if (actionName.equalsIgnoreCase(BLEepService.INTENT_BLEEP_PROCESS)
            && intent.getExtras().containsKey(BLEepService.INTENT_BLEEP_PASSED_LIST)) {
        ArrayList<Bleep> bleeps = (ArrayList<Bleep>) intent.getExtras()
                .getSerializable(BLEepService.INTENT_BLEEP_PASSED_LIST);
        for (final Bleep bleep : bleeps) {
            String msgType = bleep.getType();
            String atts = bleep.getAtts();
            try {
                JSONObject objMsg = new JSONObject(atts);
                //thisBleepService.addExtraLog(bleep, "FEEDBACK", "good");//use this when you want to send a custom log to BMS. for instance, you could display a feedback dialog, and ask users to give a rating, and BMS will help you collate the information. put this where necessary, it's just here for example
                Log.d(TAG, "Message Received of Type: " + msgType);
                if (msgType.equalsIgnoreCase("image")) {
                    final String strImgUrl = objMsg.optString(APIKeyDefineCommand.MSG_IMG);
                    final String adAspect = objMsg.optString(APIKeyDefineCommand.MSG_IMGASP);
                    String strImgMsgTemp = objMsg.optString(APIKeyDefineCommand.MSG_NOTIF);
                    //putting the default message above would only work for missing key, not in case of empty string. empty string will prevent the notification, so fix below
                    if (strImgMsgTemp.equalsIgnoreCase(""))
                        strImgMsgTemp = "No Message";
                    final String strImgMsg = strImgMsgTemp;
                    if (checkIfClosed()) {
                        if (oldcodeon)
                            localNotification("", strImgMsg, 0);
                        continue;
                    }/*from   w  w w  . j a  va  2 s.  c  o m*/
                    if (MainActivity.adlib.get(strImgMsg) == null && !strImgMsg.equalsIgnoreCase("No Message"))
                        Log.d(TAG, "image url start download for key: " + strImgMsg + ", url = " + strImgUrl);
                    else {
                        Log.d(TAG, "Image exists, or no message, not downloading..., key: " + strImgMsg);
                        continue;
                    }

                    if (strImgMsg.equalsIgnoreCase("$28")) {
                        Log.d("Portal", "Image exists, loading from cache");
                        imgShow(BitmapFactory.decodeResource(getResources(), R.drawable.singtel), strImgMsg);
                        continue;
                    } else if (strImgMsg.equalsIgnoreCase("$4.50")) {
                        Log.d("Portal", "Heineken Image exists, loading from cache");
                        imgShow(BitmapFactory.decodeResource(getResources(), R.drawable.heineken), strImgMsg);
                        continue;
                    }

                    ShutterbugManager.getSharedImageManager(BleepActivity.currentBleepActivity)
                            .download(strImgUrl, new ShutterbugManagerListener() {
                                @Override
                                public void onImageSuccess(ShutterbugManager imageManager, Bitmap bitmap,
                                        String url) {
                                    Log.d(TAG, "image url end download " + strImgUrl);
                                    if (strImgUrl.equalsIgnoreCase(AdDialog.getCurrentAdUrl()))
                                        return;
                                    if (AdDialog.howManyAdDialogsShowing == 1) {
                                        AdDialog.closeOnlyAdDialog();
                                    }
                                    final Bitmap bitmap2 = bitmap;

                                    imgShow(bitmap, strImgMsg);

                                    if (oldcodeon) {
                                        BleepActivity.currentBleepActivity.runOnUiThread(new Runnable() {
                                            public void run() {
                                                if (BleepActivity.isBackground)
                                                    localNotification("", strImgMsg, 0);
                                                AdDialog.showAdsDialog(BleepActivity.currentBleepActivity,
                                                        bitmap2, strImgUrl, adAspect);
                                            }
                                        });
                                    }
                                }

                                @Override
                                public void onImageFailure(ShutterbugManager imageManager, String url) {
                                    thisBleepService.eraseTriggerLog(bleep);//to cancel trigger log when trigger is cancelled
                                }
                            });
                } else if (oldcodeon == false) {//don't run anything else
                } else if (msgType.equalsIgnoreCase("alert") && oldcodeon) {

                    // show alert message
                    if (checkIfClosed() || BleepActivity.isBackground) {
                        localNotification(objMsg.optString(APIKeyDefineCommand.MSG_TITLE),
                                objMsg.optString(APIKeyDefineCommand.MSG_CONTENT), 1);
                    } else {
                        showAlert(objMsg.optString(APIKeyDefineCommand.MSG_TITLE),
                                objMsg.optString(APIKeyDefineCommand.MSG_CONTENT));
                    }
                } else if (msgType.equalsIgnoreCase("launch")) {
                    String intentAction = objMsg.optString(APIKeyDefineCommand.MSG_APP_INTENT);
                    String intentUri = objMsg.optString(APIKeyDefineCommand.MSG_APP_URI);
                    String intentType = "";
                    String intentExtras = objMsg.optString(APIKeyDefineCommand.MSG_APP_EXTRAS);
                    String cfmMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_CFM);
                    String failMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_FAIL);
                    processTypeLaunch(intentAction, intentUri, intentType, intentExtras, cfmMsg, failMsg, 2);
                } else if (msgType.equalsIgnoreCase("url")) {
                    String intentAction = Intent.ACTION_VIEW;
                    String intentUri = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    String intentType = "";
                    String intentExtras = "";
                    String cfmMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_CFM);
                    String failMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_FAIL);
                    processTypeLaunch(intentAction, intentUri, intentType, intentExtras, cfmMsg, failMsg, 3);
                } else if (msgType.equalsIgnoreCase("webview")) {
                    String intentAction = Intent.ACTION_VIEW;
                    String intentUri = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    String intentType = "";
                    String intentExtras = "";
                    String cfmMsg = objMsg.optString(APIKeyDefineCommand.MSG_NOTIF);
                    if (cfmMsg.equalsIgnoreCase(""))
                        cfmMsg = "View webpage?";
                    String failMsg = "";
                    processTypeLaunch(intentAction, intentUri, intentType, intentExtras, cfmMsg, failMsg, 4);
                } else if (msgType.equalsIgnoreCase("video")) {
                    String strVidUrl = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    Intent vidIntent = new Intent(this, VideoActivity.class);
                    vidIntent.putExtra("url", strVidUrl);
                    String notifMsg = objMsg.optString(APIKeyDefineCommand.MSG_NOTIF);
                    if (notifMsg.equalsIgnoreCase(""))
                        notifMsg = "Play video?";
                    if (!checkIfClosed() && BleepActivity.isVideoActivityOpen) {
                        thisBleepService.eraseTriggerLog(bleep);//to cancel trigger log when trigger is cancelled
                    } else if (checkIfClosed() || BleepActivity.isBackground) {
                        vidIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        vidIntent.setAction(Intent.ACTION_MAIN);
                        vidIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                        localNotification("", notifMsg, vidIntent, "Video opening failed!", 5);
                    } else {
                        BleepActivity.currentBleepActivity.startActivity(vidIntent);
                    }
                } else if (msgType.equalsIgnoreCase("audio")) {
                    String url = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mediaPlayer.setDataSource(url);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                        }
                    });
                    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            return false;
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //      } else if (actionName.equalsIgnoreCase(BLEepService.INTENT_BLEEP_EXIT) && intent.getExtras().containsKey(BLEepService.INTENT_MSG_NAME)) {
        //         HashMap<String, Object> beaconOutInfo = (HashMap<String, Object>)intent.getSerializableExtra(BLEepService.INTENT_MSG_NAME);   
        //         //Log.d("debug!","debug! this beacon just went out "+beaconOutInfo.get("uuid")+" "+beaconOutInfo.get("major")+" "+beaconOutInfo.get("minor")+" "+beaconOutInfo.get("tag")+" "+beaconOutInfo.get("beaconID"));
    } else if (actionName.equalsIgnoreCase(BLEepService.INTENT_BLEEP_STATE)
            && intent.getExtras().containsKey(BLEepService.INTENT_MSG_NAME)) {
        int beaconState = intent.getIntExtra(BLEepService.INTENT_MSG_NAME, 99);
    }

    return START_NOT_STICKY;
}

From source file:name.gumartinm.weather.information.notification.NotificationIntentService.java

private void showNotification(final Current current, final WeatherLocation weatherLocation) {
    // 1. Update units of measurement.
    final UnitsConversor tempUnitsConversor = new TempUnitsConversor(this.getApplicationContext());

    // 2. Formatters
    final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    tempFormatter.applyPattern("###.##");

    // 3. Prepare data for RemoteViews.
    String tempMax = "";
    if (current.getMain().getTemp_max() != null) {
        double conversion = (Double) current.getMain().getTemp_max();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMax = tempFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }/*from  w  w  w .ja va  2s . c om*/
    String tempMin = "";
    if (current.getMain().getTemp_min() != null) {
        double conversion = (Double) current.getMain().getTemp_min();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMin = tempFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }
    Bitmap picture;
    if ((current.getWeather().size() > 0) && (current.getWeather().get(0).getIcon() != null)
            && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
        final String icon = current.getWeather().get(0).getIcon();
        picture = BitmapFactory.decodeResource(this.getResources(),
                IconsList.getIcon(icon).getResourceDrawable());
    } else {
        picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
    }
    final String city = weatherLocation.getCity();
    final String country = weatherLocation.getCountry();

    // 4. Insert data in RemoteViews.
    final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(),
            R.layout.weather_notification);
    remoteView.setImageViewBitmap(R.id.weather_notification_image, picture);
    remoteView.setTextViewText(R.id.weather_notification_temperature_max, tempMax);
    remoteView.setTextViewText(R.id.weather_notification_temperature_min, tempMin);
    remoteView.setTextViewText(R.id.weather_notification_city, city);
    remoteView.setTextViewText(R.id.weather_notification_country, country);

    // 5. Activity launcher.
    final Intent resultIntent = new Intent(this.getApplicationContext(), MainTabsActivity.class);
    // The PendingIntent to launch our activity if the user selects this notification.
    // The stack builder object will contain an artificial back stack for the started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainTabsActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(this.getApplicationContext());

    // 6. Create notification.
    final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
            this.getApplicationContext()).setContent(remoteView).setSmallIcon(R.drawable.ic_launcher)
                    .setAutoCancel(true).setLocalOnly(true).setWhen(System.currentTimeMillis())
                    .setContentIntent(resultPendingIntent).setPriority(NotificationCompat.PRIORITY_DEFAULT);

    final Notification notification = notificationBuilder.build();
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Send the notification.
    // Sets an ID for the notification, so it can be updated (just in case)
    int notifyID = 1;
    notificationManager.notify(notifyID, notification);
}