Example usage for android.content Intent FLAG_ACTIVITY_RESET_TASK_IF_NEEDED

List of usage examples for android.content Intent FLAG_ACTIVITY_RESET_TASK_IF_NEEDED

Introduction

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

Prototype

int FLAG_ACTIVITY_RESET_TASK_IF_NEEDED

To view the source code for android.content Intent FLAG_ACTIVITY_RESET_TASK_IF_NEEDED.

Click Source Link

Document

If set, and this activity is either being started in a new task or bringing to the top an existing task, then it will be launched as the front door of the task.

Usage

From source file:de.lespace.apprtc.ConnectActivity.java

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

    setContentView(R.layout.activity_connect);
    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefFrom = getString(R.string.pref_from_key);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoom = getString(R.string.pref_room_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);
    from = sharedPref.getString(keyprefFrom, getString(R.string.pref_from_default));
    //    String roomUrl = sharedPref.getString(
    //            keyprefRoomServerUrl, getString(R.string.pref_room_server_url_default));

    // Video call enabled flag.
    boolean videoCallEnabled = sharedPref.getBoolean(keyprefVideoCallEnabled,
            Boolean.valueOf(getString(R.string.pref_videocall_default)));

    // Get default codecs.
    String videoCodec = sharedPref.getString(keyprefVideoCodec, getString(R.string.pref_videocodec_default));
    String audioCodec = sharedPref.getString(keyprefAudioCodec, getString(R.string.pref_audiocodec_default));

    // Check HW codec flag.
    boolean hwCodec = sharedPref.getBoolean(keyprefHwCodecAcceleration,
            Boolean.valueOf(getString(R.string.pref_hwcodec_default)));

    // Check Capture to texture.
    boolean captureToTexture = sharedPref.getBoolean(keyprefCaptureToTexture,
            Boolean.valueOf(getString(R.string.pref_capturetotexture_default)));

    // Check Disable Audio Processing flag.
    boolean noAudioProcessing = sharedPref.getBoolean(keyprefNoAudioProcessingPipeline,
            Boolean.valueOf(getString(R.string.pref_noaudioprocessing_default)));

    // Check Disable Audio Processing flag.
    boolean aecDump = sharedPref.getBoolean(keyprefAecDump,
            Boolean.valueOf(getString(R.string.pref_aecdump_default)));

    // Check OpenSL ES enabled flag.
    boolean useOpenSLES = sharedPref.getBoolean(keyprefOpenSLES,
            Boolean.valueOf(getString(R.string.pref_opensles_default)));

    // Check for mandatory permissions.
    int counter = 0;
    missingPermissions = new ArrayList();

    for (String permission : MANDATORY_PERMISSIONS) {
        if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            counter++;/*  w w  w  .j  a v  a 2s .c o m*/
            missingPermissions.add(permission);
        }
    }
    requestPermission();
    // mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    gcmRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                logAndToast(getString(R.string.gcm_send_message));
                // mInformationTextView.setText(getString(R.string.gcm_send_message));
            } else {
                logAndToast(getString(R.string.gcm_send_message));
                // mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };

    //Bring Call2Front when
    bringToFrontBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            Intent intentStart = new Intent(getApplicationContext(), ConnectActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            startActivity(intentStart);
            //  newFragment.show(transaction,"loading");

            //  showDialog();
        }
    };

    // Registering BroadcastReceiver
    registerGCMReceiver();
    registerBringToFrontReceiver();

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // Get video resolution from settings.
    int videoWidth = 0;
    int videoHeight = 0;
    String resolution = sharedPref.getString(keyprefResolution, getString(R.string.pref_resolution_default));
    String[] dimensions = resolution.split("[ x]+");
    if (dimensions.length == 2) {
        try {
            videoWidth = Integer.parseInt(dimensions[0]);
            videoHeight = Integer.parseInt(dimensions[1]);
        } catch (NumberFormatException e) {
            videoWidth = 0;
            videoHeight = 0;
            Log.e(TAG, "Wrong video resolution setting: " + resolution);
        }
    }

    // Get camera fps from settings.
    int cameraFps = 0;
    String fps = sharedPref.getString(keyprefFps, getString(R.string.pref_fps_default));
    String[] fpsValues = fps.split("[ x]+");
    if (fpsValues.length == 2) {
        try {
            cameraFps = Integer.parseInt(fpsValues[0]);
        } catch (NumberFormatException e) {
            Log.e(TAG, "Wrong camera fps setting: " + fps);
        }
    }

    // Check capture quality slider flag.
    boolean captureQualitySlider = sharedPref.getBoolean(keyprefCaptureQualitySlider,
            Boolean.valueOf(getString(R.string.pref_capturequalityslider_default)));

    // Get video and audio start bitrate.
    int videoStartBitrate = 0;
    String bitrateTypeDefault = getString(R.string.pref_startvideobitrate_default);
    String bitrateType = sharedPref.getString(keyprefVideoBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefVideoBitrateValue,
                getString(R.string.pref_startvideobitratevalue_default));
        videoStartBitrate = Integer.parseInt(bitrateValue);
    }
    int audioStartBitrate = 0;
    bitrateTypeDefault = getString(R.string.pref_startaudiobitrate_default);
    bitrateType = sharedPref.getString(keyprefAudioBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefAudioBitrateValue,
                getString(R.string.pref_startaudiobitratevalue_default));
        audioStartBitrate = Integer.parseInt(bitrateValue);
    }

    // Check statistics display option.
    boolean displayHud = sharedPref.getBoolean(keyprefDisplayHud,
            Boolean.valueOf(getString(R.string.pref_displayhud_default)));

    boolean tracing = sharedPref.getBoolean(keyprefTracing,
            Boolean.valueOf(getString(R.string.pref_tracing_default)));

    Log.d(TAG, "Connecting from " + from + " at URL " + Configs.ROOM_URL);

    if (validateUrl(Configs.ROOM_URL)) {
        Uri uri = Uri.parse(Configs.ROOM_URL);
        intent = new Intent(this, ConnectActivity.class);
        intent.setData(uri);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CALL, videoCallEnabled);
        intent.putExtra(CallActivity.EXTRA_VIDEO_WIDTH, videoWidth);
        intent.putExtra(CallActivity.EXTRA_VIDEO_HEIGHT, videoHeight);
        intent.putExtra(CallActivity.EXTRA_VIDEO_FPS, cameraFps);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CAPTUREQUALITYSLIDER_ENABLED, captureQualitySlider);
        intent.putExtra(CallActivity.EXTRA_VIDEO_BITRATE, videoStartBitrate);
        intent.putExtra(CallActivity.EXTRA_VIDEOCODEC, videoCodec);
        intent.putExtra(CallActivity.EXTRA_HWCODEC_ENABLED, hwCodec);
        intent.putExtra(CallActivity.EXTRA_CAPTURETOTEXTURE_ENABLED, captureToTexture);
        intent.putExtra(CallActivity.EXTRA_NOAUDIOPROCESSING_ENABLED, noAudioProcessing);
        intent.putExtra(CallActivity.EXTRA_AECDUMP_ENABLED, aecDump);
        intent.putExtra(CallActivity.EXTRA_OPENSLES_ENABLED, useOpenSLES);
        intent.putExtra(CallActivity.EXTRA_AUDIO_BITRATE, audioStartBitrate);
        intent.putExtra(CallActivity.EXTRA_AUDIOCODEC, audioCodec);
        intent.putExtra(CallActivity.EXTRA_DISPLAY_HUD, displayHud);
        intent.putExtra(CallActivity.EXTRA_TRACING, tracing);
        intent.putExtra(CallActivity.EXTRA_CMDLINE, commandLineRun);
        intent.putExtra(CallActivity.EXTRA_RUNTIME, runTimeMs);
    }

    roomListView = (ListView) findViewById(R.id.room_listview);
    roomListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    connectButton = (ImageButton) findViewById(R.id.connect_button);
    connectButton.setOnClickListener(connectListener);

    // If an implicit VIEW intent is launching the app, go directly to that URL.
    //final Intent intent = getIntent();
    Uri wsurl = Uri.parse(Configs.ROOM_URL);
    //intent.getData();
    Log.d(TAG, "connecting to:" + wsurl.toString());
    if (wsurl == null) {
        logAndToast(getString(R.string.missing_wsurl));
        Log.e(TAG, "Didn't get any URL in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    if (from == null || from.length() == 0) {
        logAndToast(getString(R.string.missing_from));
        Log.e(TAG, "Incorrect from in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    peerConnectionParameters = new PeerConnectionClient.PeerConnectionParameters(videoCallEnabled, tracing,
            videoWidth, videoHeight, cameraFps, videoStartBitrate, videoCodec, hwCodec, captureToTexture,
            audioStartBitrate, audioCodec, noAudioProcessing, aecDump, useOpenSLES);

    roomConnectionParameters = new AppRTCClient.RoomConnectionParameters(wsurl.toString(), from, false);

    Log.i(TAG, "creating appRtcClient with roomUri:" + wsurl.toString() + " from:" + from);
    // Create connection client and connection parameters.
    appRtcClient = new WebSocketRTCClient(this, new LooperExecutor());

    connectToWebsocket();
    // 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:support.plus.reportit.MainActivity.java

private void shareAppLinkViaFacebook(String content) {

    try {//from w w w  .ja  v a  2s  . com
        Intent intent1 = new Intent();
        intent1.setClassName("com.facebook.katana",
                "com.facebook.katana.activity.composer.ImplicitShareIntentHandler");
        intent1.setAction("android.intent.action.SEND");
        intent1.setType("text/plain");
        intent1.putExtra(Intent.EXTRA_TEXT, content);
        intent1.addCategory(Intent.CATEGORY_LAUNCHER);
        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(intent1);
    } catch (Exception e) {
        // If we failed (no native FB app installed), try share through SEND
        Intent intent = new Intent(Intent.ACTION_SEND);
        String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + content;
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
        startActivity(intent);
    }
}

From source file:com.andernity.launcher2.InstallShortcutReceiver.java

private static boolean installShortcut(Context context, Intent data, ArrayList<ItemInfo> items, String name,
        final Intent intent, final int screen, boolean shortcutExists, final SharedPreferences sharedPrefs,
        int[] result) {
    int[] tmpCoordinates = new int[2];
    if (findEmptyCell(context, items, tmpCoordinates, screen)) {
        if (intent != null) {
            if (intent.getAction() == null) {
                intent.setAction(Intent.ACTION_VIEW);
            } else if (intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories() != null
                    && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            }//from w  w  w.ja v a2  s.c  o m

            // By default, we allow for duplicate entries (located in
            // different places)
            boolean duplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);
            if (duplicate || !shortcutExists) {
                new Thread("setNewAppsThread") {
                    public void run() {
                        synchronized (sLock) {
                            // If the new app is going to fall into the same page as before,
                            // then just continue adding to the current page
                            final int newAppsScreen = sharedPrefs.getInt(NEW_APPS_PAGE_KEY, screen);
                            SharedPreferences.Editor editor = sharedPrefs.edit();
                            if (newAppsScreen == -1 || newAppsScreen == screen) {
                                addToStringSet(sharedPrefs, editor, NEW_APPS_LIST_KEY, intent.toUri(0));
                            }
                            editor.putInt(NEW_APPS_PAGE_KEY, screen);
                            editor.commit();
                        }
                    }
                }.start();

                // Update the Launcher db
                LauncherApplication app = (LauncherApplication) context.getApplicationContext();
                ShortcutInfo info = app.getModel().addShortcut(context, data,
                        LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, tmpCoordinates[0],
                        tmpCoordinates[1], true);
                if (info == null) {
                    return false;
                }
            } else {
                result[0] = INSTALL_SHORTCUT_IS_DUPLICATE;
            }

            return true;
        }
    } else {
        result[0] = INSTALL_SHORTCUT_NO_SPACE;
    }

    return false;
}

From source file:cc.flydev.launcher.InstallShortcutReceiver.java

private static ShortcutInfo getShortcutInfo(Context context, Intent data, Intent launchIntent) {
    if (launchIntent.getAction() == null) {
        launchIntent.setAction(Intent.ACTION_VIEW);
    } else if (launchIntent.getAction().equals(Intent.ACTION_MAIN) && launchIntent.getCategories() != null
            && launchIntent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    }//from  w ww . ja  va  2 s.co  m
    LauncherAppState app = LauncherAppState.getInstance();
    return app.getModel().infoFromShortcutIntent(context, data, null);
}

From source file:com.androzic.location.LocationService.java

private Notification getNotification() {
    int msgId = R.string.notif_loc_started;
    int ntfId = R.drawable.ic_stat_locating;
    if (trackingEnabled) {
        msgId = R.string.notif_trk_started;
        ntfId = R.drawable.ic_stat_tracking;
    }/*www  .  j  a v a2s  .  co  m*/
    if (gpsStatus != LocationService.GPS_OK) {
        msgId = R.string.notif_loc_waiting;
        ntfId = R.drawable.ic_stat_waiting;
    }
    if (gpsStatus == LocationService.GPS_OFF) {
        ntfId = R.drawable.ic_stat_off;
    }
    if (errorTime > 0) {
        msgId = R.string.notif_trk_failure;
        ntfId = R.drawable.ic_stat_failure;
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setWhen(errorTime);
    builder.setSmallIcon(ntfId);
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    intent.setComponent(new ComponentName(getApplicationContext(), Splash.class));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, intent, 0);
    builder.setContentIntent(contentIntent);
    builder.setContentTitle(getText(R.string.notif_loc_short));
    if (errorTime > 0 && DEBUG_ERRORS)
        builder.setContentText(errorMsg);
    else
        builder.setContentText(getText(msgId));
    builder.setOngoing(true);

    Notification notification = builder.getNotification();
    return notification;
}

From source file:nl.vanvianen.android.gcm.GCMIntentService.java

@Override
@SuppressWarnings("unchecked")
protected void onMessage(Context context, Intent intent) {
    Log.d(LCAT, "Push notification received");

    boolean isTopic = false;

    HashMap<String, Object> data = new HashMap<String, Object>();
    for (String key : intent.getExtras().keySet()) {
        Object value = intent.getExtras().get(key);
        Log.d(LCAT, "Message key: \"" + key + "\" value: \"" + value + "\"");

        if (key.equals("from") && value instanceof String && ((String) value).startsWith("/topics/")) {
            isTopic = true;/*  w w w .j  ava  2 s.c  om*/
        }

        String eventKey = key.startsWith("data.") ? key.substring(5) : key;
        data.put(eventKey, intent.getExtras().get(key));

        if (value instanceof String && ((String) value).startsWith("{")) {
            Log.d(LCAT, "Parsing JSON string...");
            try {
                JSONObject json = new JSONObject((String) value);

                Iterator<String> keys = json.keys();
                while (keys.hasNext()) {
                    String jKey = keys.next();
                    String jValue = json.getString(jKey);
                    Log.d(LCAT, "JSON key: \"" + jKey + "\" value: \"" + jValue + "\"");

                    data.put(jKey, jValue);
                }
            } catch (JSONException ex) {
                Log.d(LCAT, "JSON error: " + ex.getMessage());
            }
        }
    }

    /* Store data to be retrieved when resuming app as a JSON object, serialized as a String, otherwise
     * Ti.App.Properties.getString(GCMModule.LAST_DATA) doesn't work. */
    JSONObject json = new JSONObject(data);
    TiApplication.getInstance().getAppProperties().setString(GCMModule.LAST_DATA, json.toString());

    /* Get settings from notification object */
    int smallIcon = 0;
    int largeIcon = 0;
    String sound = null;
    boolean vibrate = false;
    boolean insistent = false;
    String group = null;
    boolean localOnly = true;
    int priority = 0;
    boolean bigText = false;
    int notificationId = 1;

    Integer ledOn = null;
    Integer ledOff = null;

    String titleKey = DEFAULT_TITLE_KEY;
    String messageKey = DEFAULT_MESSAGE_KEY;
    String tickerKey = DEFAULT_TICKER_KEY;
    String title = null;
    String message = null;
    String ticker = null;

    boolean backgroundOnly = false;

    Map<String, Object> notificationSettings = new Gson().fromJson(
            TiApplication.getInstance().getAppProperties().getString(GCMModule.NOTIFICATION_SETTINGS, null),
            Map.class);
    if (notificationSettings != null) {
        if (notificationSettings.get("smallIcon") instanceof String) {
            smallIcon = getResource("drawable", (String) notificationSettings.get("smallIcon"));
        } else {
            Log.e(LCAT, "Invalid setting smallIcon, should be String");
        }

        if (notificationSettings.get("largeIcon") instanceof String) {
            largeIcon = getResource("drawable", (String) notificationSettings.get("largeIcon"));
        } else {
            Log.e(LCAT, "Invalid setting largeIcon, should be String");
        }

        if (notificationSettings.get("sound") != null) {
            if (notificationSettings.get("sound") instanceof String) {
                sound = (String) notificationSettings.get("sound");
            } else {
                Log.e(LCAT, "Invalid setting sound, should be String");
            }
        }

        if (notificationSettings.get("vibrate") != null) {
            if (notificationSettings.get("vibrate") instanceof Boolean) {
                vibrate = (Boolean) notificationSettings.get("vibrate");
            } else {
                Log.e(LCAT, "Invalid setting vibrate, should be Boolean");
            }
        }

        if (notificationSettings.get("insistent") != null) {
            if (notificationSettings.get("insistent") instanceof Boolean) {
                insistent = (Boolean) notificationSettings.get("insistent");
            } else {
                Log.e(LCAT, "Invalid setting insistent, should be Boolean");
            }
        }

        if (notificationSettings.get("group") != null) {
            if (notificationSettings.get("group") instanceof String) {
                group = (String) notificationSettings.get("group");
            } else {
                Log.e(LCAT, "Invalid setting group, should be String");
            }
        }

        if (notificationSettings.get("localOnly") != null) {
            if (notificationSettings.get("localOnly") instanceof Boolean) {
                localOnly = (Boolean) notificationSettings.get("localOnly");
            } else {
                Log.e(LCAT, "Invalid setting localOnly, should be Boolean");
            }
        }

        if (notificationSettings.get("priority") != null) {
            if (notificationSettings.get("priority") instanceof Integer) {
                priority = (Integer) notificationSettings.get("priority");
            } else if (notificationSettings.get("priority") instanceof Double) {
                priority = ((Double) notificationSettings.get("priority")).intValue();
            } else {
                Log.e(LCAT,
                        "Invalid setting priority, should be an integer, between PRIORITY_MIN ("
                                + NotificationCompat.PRIORITY_MIN + ") and PRIORITY_MAX ("
                                + NotificationCompat.PRIORITY_MAX + ")");
            }
        }

        if (notificationSettings.get("bigText") != null) {
            if (notificationSettings.get("bigText") instanceof Boolean) {
                bigText = (Boolean) notificationSettings.get("bigText");
            } else {
                Log.e(LCAT, "Invalid setting bigText, should be Boolean");
            }
        }

        if (notificationSettings.get("titleKey") != null) {
            if (notificationSettings.get("titleKey") instanceof String) {
                titleKey = (String) notificationSettings.get("titleKey");
            } else {
                Log.e(LCAT, "Invalid setting titleKey, should be String");
            }
        }

        if (notificationSettings.get("messageKey") != null) {
            if (notificationSettings.get("messageKey") instanceof String) {
                messageKey = (String) notificationSettings.get("messageKey");
            } else {
                Log.e(LCAT, "Invalid setting messageKey, should be String");
            }
        }

        if (notificationSettings.get("tickerKey") != null) {
            if (notificationSettings.get("tickerKey") instanceof String) {
                tickerKey = (String) notificationSettings.get("tickerKey");
            } else {
                Log.e(LCAT, "Invalid setting tickerKey, should be String");
            }
        }

        if (notificationSettings.get("title") != null) {
            if (notificationSettings.get("title") instanceof String) {
                title = (String) notificationSettings.get("title");
            } else {
                Log.e(LCAT, "Invalid setting title, should be String");
            }
        }

        if (notificationSettings.get("message") != null) {
            if (notificationSettings.get("message") instanceof String) {
                message = (String) notificationSettings.get("message");
            } else {
                Log.e(LCAT, "Invalid setting message, should be String");
            }
        }

        if (notificationSettings.get("ticker") != null) {
            if (notificationSettings.get("ticker") instanceof String) {
                ticker = (String) notificationSettings.get("ticker");
            } else {
                Log.e(LCAT, "Invalid setting ticker, should be String");
            }
        }

        if (notificationSettings.get("ledOn") != null) {
            if (notificationSettings.get("ledOn") instanceof Integer) {
                ledOn = (Integer) notificationSettings.get("ledOn");
                if (ledOn < 0) {
                    Log.e(LCAT, "Invalid setting ledOn, should be positive");
                    ledOn = null;
                }
            } else {
                Log.e(LCAT, "Invalid setting ledOn, should be Integer");
            }
        }

        if (notificationSettings.get("ledOff") != null) {
            if (notificationSettings.get("ledOff") instanceof Integer) {
                ledOff = (Integer) notificationSettings.get("ledOff");
                if (ledOff < 0) {
                    Log.e(LCAT, "Invalid setting ledOff, should be positive");
                    ledOff = null;
                }
            } else {
                Log.e(LCAT, "Invalid setting ledOff, should be Integer");
            }
        }

        if (notificationSettings.get("backgroundOnly") != null) {
            if (notificationSettings.get("backgroundOnly") instanceof Boolean) {
                backgroundOnly = (Boolean) notificationSettings.get("backgroundOnly");
            } else {
                Log.e(LCAT, "Invalid setting backgroundOnly, should be Boolean");
            }
        }

        if (notificationSettings.get("notificationId") != null) {
            if (notificationSettings.get("notificationId") instanceof Integer) {
                notificationId = (Integer) notificationSettings.get("notificationId");
            } else {
                Log.e(LCAT, "Invalid setting notificationId, should be Integer");
            }
        }

    } else {
        Log.d(LCAT, "No notification settings found");
    }

    /* If icon not found, default to appicon */
    if (smallIcon == 0) {
        smallIcon = getResource("drawable", "appicon");
    }

    /* If large icon not found, default to icon */
    if (largeIcon == 0) {
        largeIcon = smallIcon;
    }

    /* Create intent to (re)start the app's root activity */
    String pkg = TiApplication.getInstance().getApplicationContext().getPackageName();
    Intent launcherIntent = TiApplication.getInstance().getApplicationContext().getPackageManager()
            .getLaunchIntentForPackage(pkg);
    launcherIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    /* Grab notification content from data according to provided keys if not already set */
    if (title == null && titleKey != null) {
        title = (String) data.get(titleKey);
    }
    if (message == null && messageKey != null) {
        message = (String) data.get(messageKey);
    }
    if (ticker == null && tickerKey != null) {
        ticker = (String) data.get(tickerKey);
    }

    Log.i(LCAT, "Title: " + title);
    Log.i(LCAT, "Message: " + message);
    Log.i(LCAT, "Ticker: " + ticker);

    /* Check for app state */
    if (GCMModule.getInstance() != null) {
        /* Send data to app */
        if (isTopic) {
            GCMModule.getInstance().sendTopicMessage(data);
        } else {
            GCMModule.getInstance().sendMessage(data);
        }
        /* Do not create notification if backgroundOnly and app is in foreground */
        if (backgroundOnly && GCMModule.getInstance().isInForeground()) {
            Log.d(LCAT, "Notification received in foreground, no need for notification.");
            return;
        }
    }

    if (message == null) {
        Log.d(LCAT,
                "Message received but no 'message' specified in push notification payload, so will make this silent");
    } else {
        Log.d(LCAT, "Creating notification...");

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), largeIcon);
        if (bitmap == null) {
            Log.d(LCAT, "No large icon found");
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(title)
                .setContentText(message).setTicker(ticker)
                .setContentIntent(
                        PendingIntent.getActivity(this, 0, launcherIntent, PendingIntent.FLAG_ONE_SHOT))
                .setSmallIcon(smallIcon).setLargeIcon(bitmap);

        /* Name of group to group similar notifications together, can also be set in the push notification payload */
        if (data.get("group") != null) {
            group = (String) data.get("group");
        }
        if (group != null) {
            builder.setGroup(group);
        }
        Log.i(LCAT, "Group: " + group);

        /* Whether notification should be for this device only or bridged to other devices, can also be set in the push notification payload */
        if (data.get("localOnly") != null) {
            localOnly = Boolean.valueOf((String) data.get("localOnly"));
        }
        builder.setLocalOnly(localOnly);
        Log.i(LCAT, "LocalOnly: " + localOnly);

        /* Specify notification priority, can also be set in the push notification payload */
        if (data.get("priority") != null) {
            priority = Integer.parseInt((String) data.get("priority"));
        }
        if (priority >= NotificationCompat.PRIORITY_MIN && priority <= NotificationCompat.PRIORITY_MAX) {
            builder.setPriority(priority);
            Log.i(LCAT, "Priority: " + priority);
        } else {
            Log.e(LCAT, "Ignored invalid priority " + priority);
        }

        /* Specify whether bigtext should be used, can also be set in the push notification payload */
        if (data.get("bigText") != null) {
            bigText = Boolean.valueOf((String) data.get("bigText"));
        }
        if (bigText) {
            builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        }
        Log.i(LCAT, "bigText: " + bigText);

        Notification notification = builder.build();

        /* Sound, can also be set in the push notification payload */
        if (data.get("sound") != null) {
            Log.d(LCAT, "Sound specified in notification");
            sound = (String) data.get("sound");
        }

        if ("default".equals(sound)) {
            Log.i(LCAT, "Sound: default sound");
            notification.defaults |= Notification.DEFAULT_SOUND;
        } else if (sound != null) {
            Log.i(LCAT, "Sound " + sound);
            notification.sound = Uri.parse("android.resource://" + pkg + "/" + getResource("raw", sound));
        }

        /* Vibrate, can also be set in the push notification payload */
        if (data.get("vibrate") != null) {
            vibrate = Boolean.valueOf((String) data.get("vibrate"));
        }
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }
        Log.i(LCAT, "Vibrate: " + vibrate);

        /* Insistent, can also be set in the push notification payload */
        if ("true".equals(data.get("insistent"))) {
            insistent = true;
        }
        if (insistent) {
            notification.flags |= Notification.FLAG_INSISTENT;
        }
        Log.i(LCAT, "Insistent: " + insistent);

        /* notificationId, set in push payload to specify multiple notifications should be shown. If not specified, subsequent notifications "override / overwrite" the older ones */
        if (data.get("notificationId") != null) {
            if (data.get("notificationId") instanceof Integer) {
                notificationId = (Integer) data.get("notificationId");
            } else if (data.get("notificationId") instanceof String) {
                try {
                    notificationId = Integer.parseInt((String) data.get("notificationId"));
                } catch (NumberFormatException ex) {
                    Log.e(LCAT, "Invalid setting notificationId, should be Integer");
                }
            } else {
                Log.e(LCAT, "Invalid setting notificationId, should be Integer");
            }
        }
        Log.i(LCAT, "Notification ID: " + notificationId);

        /* Specify LED flashing */
        if (ledOn != null || ledOff != null) {
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
            if (ledOn != null) {
                notification.ledOnMS = ledOn;
            }
            if (ledOff != null) {
                notification.ledOffMS = ledOff;
            }
        } else {
            notification.defaults |= Notification.DEFAULT_LIGHTS;
        }

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(notificationId,
                notification);
    }
}

From source file:com.android.launcher4.InstallShortcutReceiver.java

private static ShortcutInfo getShortcutInfo(Context context, Intent data, Intent launchIntent) {
    if (launchIntent.getAction() == null) {
        launchIntent.setAction(Intent.ACTION_VIEW);
    } else if (launchIntent.getAction().equals(Intent.ACTION_MAIN) && launchIntent.getCategories() != null
            && launchIntent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    }/*  w  w  w.j a  v a2 s .  c  om*/
    LauncherAppState app = LauncherAppState.getInstance();
    ShortcutInfo info = app.getModel().infoFromShortcutIntent(context, data, null);
    info.title = ensureValidName(context, launchIntent, info.title);
    return info;
}

From source file:com.nbplus.vbroadlauncher.HomeLauncherActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    boolean isTablet = DisplayUtils.isTabletDevice(this);
    LauncherSettings.getInstance(this).setIsSmartPhone(!isTablet);
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    setContentView(R.layout.activity_home_launcher);

    DeviceUtils.showDeviceInformation();

    Log.d(TAG, ">>>DisplayUtils.getScreenDensity(this) = " + DisplayUtils.getScreenDensity(this));

    // vitamio library load
    if (!LibsChecker.checkVitamioLibs(this)) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
            @Override/*w ww.j a v  a2 s . c o m*/
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        alert.setMessage(R.string.alert_media_message);
        alert.show();
        return;
    }

    mCurrentLocale = getResources().getConfiguration().locale;
    if (BuildConfig.DEBUG) {
        Point p = DisplayUtils.getScreenSize(this);
        Log.d(TAG, "Screen size px = " + p.x + ", py = " + p.y);
        Point screen = p;
        p = DisplayUtils.getScreenDp(this);
        Log.d(TAG, "Screen dp x = " + p.x + ", y = " + p.y);
        int density = DisplayUtils.getScreenDensity(this);
        Log.d(TAG, "Screen density = " + density);
    }

    if (isTablet) {
        //is tablet
        Log.d(TAG, "Tablet");
    } else {
        //is phone
        Log.d(TAG, "isTabletDevice() returns Phone.. now check display inches");
        double diagonalInches = DisplayUtils.getDisplayInches(this);
        if (diagonalInches >= 6.4) {
            // 800x400 ? portrait ? 6.43 ? .
            // 6.5inch device or bigger
            Log.d(TAG, "DisplayUtils.getDisplayInches() bigger than 6.5");
        } else {
            if (!Constants.OPEN_BETA_PHONE) {
                // smaller device
                Log.d(TAG, "DisplayUtils.getDisplayInches() smaller than 6.5");
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                alert.setMessage(R.string.alert_phone_message);
                alert.show();

                return;
            }
        }
    }

    if (!Constants.OPEN_BETA_PHONE || !LauncherSettings.getInstance(this).isSmartPhone()) {
        if (isMyLauncherDefault()) {
            Log.d(TAG, "isMyLauncherDefault() == true");
            // fake home key event.
            Intent fakeIntent = new Intent();
            fakeIntent.setAction(Intent.ACTION_MAIN);
            fakeIntent.addCategory(Intent.CATEGORY_HOME);
            fakeIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_FORWARD_RESULT
                    | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(fakeIntent);
        } else {
            Log.d(TAG, "Constants.OPEN_BETA_PHONE == false || isMyLauncherDefault() == false");
            //resetPreferredLauncherAndOpenChooser();
        }
    }

    // ?  .. ?   ?   ?.
    // ?  ?.
    IntentFilter filter = new IntentFilter();
    filter.addAction(Constants.ACTION_LAUNCHER_ACTIVITY_RUNNING);
    filter.addAction(IoTConstants.ACTION_RECEIVE_EMERGENCY_CALL_DEVICE_BROADCAST);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);

    Intent intent = new Intent(Constants.ACTION_LAUNCHER_ACTIVITY_RUNNING);
    mActivityRunningTime = System.currentTimeMillis();
    intent.putExtra(Constants.EXTRA_LAUNCHER_ACTIVITY_RUNNING, mActivityRunningTime);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    // set background image
    setContentViewByOrientation();
    if (LauncherSettings.getInstance(this).getPreferredUserLocation() == null) {
        Location defaultLocation = new Location("stub");

        defaultLocation.setLongitude(126.929810);
        defaultLocation.setLatitude(37.488201);

        LauncherSettings.getInstance(this).setPreferredUserLocation(defaultLocation);
    }

    // First we need to check availability of play services
    mResultReceiver = new AddressResultReceiver(mActivityHandler);
    // Set defaults, then update using values stored in the Bundle.
    mAddressRequested = false;
    mAddressOutput = null;

    // Update values using data stored in the Bundle.
    updateValuesFromBundle(savedInstanceState);

    /**
     *   ?  ??? ?  .
     * ?? ? .
     */
    mBroadcastFramelayout = (FrameLayout) findViewById(R.id.realtimeBroadcastFragment);
    if (mBroadcastFramelayout != null) {
        mBroadcastFramelayout.setVisibility(View.GONE);
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Bundle bundle;

    // check installation or bind to service
    VBroadcastServer serverInfo = LauncherSettings.getInstance(this).getServerInformation();
    if (serverInfo == null || !Constants.VBROAD_INITIAL_PAGE.equals(serverInfo.getInitialServerPage())) {
        // ?   ?.
        //  ?  Registration ?  .
        LauncherSettings.getInstance(this).setServerInformation(null);
        LauncherSettings.getInstance(this).setIsCompletedSetup(false);
        // open user register fragment
        RegisterFragment registerFragment = new RegisterFragment();
        bundle = new Bundle();
        registerFragment.setArguments(bundle);

        fragmentTransaction.replace(R.id.launcherFragment, registerFragment);
    } else {
        if (LauncherSettings.getInstance(this).isCompletedSetup() == false) {

            LauncherSettings.getInstance(this).setServerInformation(null);
            // open user register fragment
            RegisterFragment registerFragment = new RegisterFragment();
            bundle = new Bundle();
            registerFragment.setArguments(bundle);

            fragmentTransaction.replace(R.id.launcherFragment, registerFragment);
        } else {
            // open main launcher fragment
            LauncherFragment launcherFragment = new LauncherFragment();
            bundle = new Bundle();
            launcherFragment.setArguments(bundle);

            fragmentTransaction.replace(R.id.launcherFragment, launcherFragment);
        }
    }
    fragmentTransaction.commit();

    // initialize iot interface.
    String collectServerAddress = null;
    if (serverInfo != null) {
        String apiServer = serverInfo.getApiServer();
        if (StringUtils.isEmptyString(apiServer)) {
            collectServerAddress = null;
        } else {
            collectServerAddress = apiServer + Constants.API_COLLECTED_IOT_DATA_CONTEXT;
        }
    }
    IoTResultCodes resCode = IoTInterface.getInstance().initialize(this,
            LauncherSettings.getInstance(this).getDeviceID(), collectServerAddress);
    if (!resCode.equals(IoTResultCodes.SUCCESS)) {
        if (resCode.equals(IoTResultCodes.BIND_SERVICE_FAILED)) {
            Toast.makeText(getApplicationContext(), "Bind IoT Service failed!!!", Toast.LENGTH_SHORT).show();
        }
    }
}

From source file:edu.mit.mobile.android.demomode.DemoMode.java

@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    switch (adapter.getId()) {
    case R.id.grid: {
        final Intent launch = new Intent();
        final Cursor c = mAdapter.getCursor();
        launch.setClassName(c.getString(c.getColumnIndex(LauncherItem.PACKAGE_NAME)),
                c.getString(c.getColumnIndex(LauncherItem.ACTIVITY_NAME)));
        launch.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(launch);/*from   w  ww  . j av  a 2s . c  om*/
    }
        break;

    case R.id.all_apps: {
        final ApplicationInfo appInfo = (ApplicationInfo) mAllApps.getAdapter().getItem(position);
        startActivity(appInfo.intent);
    }
        break;
    }

}

From source file:com.example.android.home.Home.java

/**
 * Loads the list of installed applications in mApplications.
 *//*ww  w  .  java  2 s  . c o m*/
private void loadApplications(boolean isLaunching) {
    if (isLaunching && mApplications != null) {
        return;
    }

    PackageManager manager = getPackageManager();

    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
    Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));

    if (apps != null) {
        final int count = apps.size();

        if (mApplications == null) {
            mApplications = new ArrayList<ApplicationInfo>(count);
        }
        mApplications.clear();

        for (int i = 0; i < count; i++) {
            //for (int i = 0; i < 6; i++) {            // show only 6 apps
            ApplicationInfo application = new ApplicationInfo();
            ResolveInfo info = apps.get(i);

            application.title = info.loadLabel(manager);
            application.setActivity(
                    new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name),
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

            Log.v("Home APP", "package neme= " + info.activityInfo.applicationInfo.packageName);
            Log.v("Home APP", "neme= " + info.activityInfo.name);
            Log.v("Home APP", "title= " + application.title);

            application.icon = info.activityInfo.loadIcon(manager);

            // TODO
            // Replace Icons
            //if((application.title+"").equals("Calculator")) application.icon = getResources().getDrawable(R.drawable.ic_launcher_home_big);

            // Add Application
            if ((application.title + "").equals("Browser"))
                mApplications.add(application);
            if ((application.title + "").equals("Phone"))
                mApplications.add(application);
            if ((application.title + "").equals("People"))
                mApplications.add(application);
            if ((application.title + "").equals("Messaging"))
                mApplications.add(application);
            if ((application.title + "").equals("Settings"))
                mApplications.add(application);

        }

        // Took from http://hi-android.info/src/index.html
        // ********************* ADD Call Log
        ApplicationInfo application = new ApplicationInfo();
        application.title = "Call Log";
        application.icon = getResources().getDrawable(R.drawable.ic_launcher_home);
        application.setActivity(
                new ComponentName("com.android.contacts", "com.android.contacts.RecentCallsListActivity"),
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        mApplications.add(application);
    }
}