List of usage examples for android.content Intent getLongExtra
public long getLongExtra(String name, long defaultValue)
From source file:com.klinker.android.launcher.launcher3.Launcher.java
private boolean startActivity(View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try {//from ww w . j a v a2 s . com // Only launch using the new animation if the shortcut has not opted out (this is a // private contract between launcher and may be ignored in the future). boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION); LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this); UserManagerCompat userManager = UserManagerCompat.getInstance(this); UserHandleCompat user = null; if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) { long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1); user = userManager.getUserForSerialNumber(serialNumber); } Bundle optsBundle = null; if (useLaunchAnimation) { ActivityOptions opts = null; if (sClipRevealMethod != null) { // TODO: call method directly when Launcher3 can depend on M APIs int left = 0, top = 0; int width = v.getMeasuredWidth(), height = v.getMeasuredHeight(); if (v instanceof TextView) { // Launch from center of icon, not entire view Drawable icon = Workspace.getTextViewIcon((TextView) v); if (icon != null) { Rect bounds = icon.getBounds(); left = (width - bounds.width()) / 2; top = v.getPaddingTop(); width = bounds.width(); height = bounds.height(); } } try { opts = (ActivityOptions) sClipRevealMethod.invoke(null, v, left, top, width, height); } catch (IllegalAccessException e) { Log.d(TAG, "Could not call makeClipRevealAnimation: " + e); sClipRevealMethod = null; } catch (InvocationTargetException e) { Log.d(TAG, "Could not call makeClipRevealAnimation: " + e); sClipRevealMethod = null; } } if (opts == null && !Utilities.isLmpOrAbove()) { // Below L, we use a scale up animation opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); } else if (opts == null && Utilities.isLmpMR1()) { // On L devices, we use the device default slide-up transition. // On L MR1 devices, we a custom version of the slide-up transition which // doesn't have the delay present in the device default. opts = ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim); } optsBundle = opts != null ? opts.toBundle() : null; } if (user == null || user.equals(UserHandleCompat.myUserHandle())) { // Could be launching some bookkeeping activity startActivity(intent, optsBundle); } else { // TODO Component can be null when shortcuts are supported for secondary user launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(), optsBundle); } return true; } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e); } return false; }
From source file:com.android.mms.ui.ComposeMessageActivity.java
private void initActivityState(Bundle bundle) { Intent intent = getIntent(); if (bundle != null) { setIntent(getIntent().setAction(Intent.ACTION_VIEW)); String recipients = bundle.getString(RECIPIENTS); if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients); mConversation = Conversation.get(this, ContactList.getByNumbers(recipients, false /* don't block */, true /* replace number */), false);// w ww .jav a2 s . c om addRecipientsListeners(); mSendDiscreetMode = bundle.getBoolean(KEY_EXIT_ON_SENT, false); mForwardMessageMode = bundle.getBoolean(KEY_FORWARDED_MESSAGE, false); if (mSendDiscreetMode) { mMsgListView.setVisibility(View.INVISIBLE); } mWorkingMessage.readStateFromBundle(bundle); return; } // If we have been passed a thread_id, use that to find our conversation. long threadId = intent.getLongExtra(THREAD_ID, 0); if (threadId > 0) { if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId); mConversation = Conversation.get(this, threadId, false); } else { Uri intentData = intent.getData(); if (intentData != null) { // try to get a conversation based on the data URI passed to our intent. if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData); mConversation = Conversation.get(this, intentData, false); mWorkingMessage.setText(getBody(intentData)); } else { // special intent extra parameter to specify the address String address = intent.getStringExtra("address"); if (!TextUtils.isEmpty(address)) { if (LogTag.VERBOSE) log("get mConversation by address " + address); mConversation = Conversation.get(this, ContactList.getByNumbers(address, false /* don't block */, true /* replace number */), false); } else { if (LogTag.VERBOSE) log("create new conversation"); mConversation = Conversation.createNew(this); } } } addRecipientsListeners(); updateThreadIdIfRunning(); mSendDiscreetMode = intent.getBooleanExtra(KEY_EXIT_ON_SENT, false); mForwardMessageMode = intent.getBooleanExtra(KEY_FORWARDED_MESSAGE, false); if (mSendDiscreetMode) { mMsgListView.setVisibility(View.INVISIBLE); } if (intent.hasExtra("sms_body")) { mWorkingMessage.setText(intent.getStringExtra("sms_body")); } mWorkingMessage.setSubject(intent.getStringExtra("subject"), false); }
From source file:xyz.klinker.blur.launcher3.Launcher.java
private boolean startActivity(View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try {//from w w w .java2 s.c o m // Only launch using the new animation if the shortcut has not opted out (this is a // private contract between launcher and may be ignored in the future). boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION); LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this); UserManagerCompat userManager = UserManagerCompat.getInstance(this); UserHandleCompat user = null; if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) { long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1); user = userManager.getUserForSerialNumber(serialNumber); } Bundle optsBundle = null; if (useLaunchAnimation) { ActivityOptions opts = null; if (Utilities.ATLEAST_MARSHMALLOW) { int left = 0, top = 0; int width = v.getMeasuredWidth(), height = v.getMeasuredHeight(); if (v instanceof TextView) { // Launch from center of icon, not entire view Drawable icon = Workspace.getTextViewIcon((TextView) v); if (icon != null) { Rect bounds = icon.getBounds(); left = (width - bounds.width()) / 2; top = v.getPaddingTop(); width = bounds.width(); height = bounds.height(); } } opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height); } else if (!Utilities.ATLEAST_LOLLIPOP) { // Below L, we use a scale up animation opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); } else if (Utilities.ATLEAST_LOLLIPOP_MR1) { // On L devices, we use the device default slide-up transition. // On L MR1 devices, we a custom version of the slide-up transition which // doesn't have the delay present in the device default. opts = ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim); } optsBundle = opts != null ? opts.toBundle() : null; } if (user == null || user.equals(UserHandleCompat.myUserHandle())) { StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy(); try { // Temporarily disable deathPenalty on all default checks. For eg, shortcuts // containing file Uris would cause a crash as penaltyDeathOnFileUriExposure // is enabled by default on NYC. StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()); // Could be launching some bookkeeping activity startActivity(intent, optsBundle); } finally { StrictMode.setVmPolicy(oldPolicy); } } else { // TODO Component can be null when shortcuts are supported for secondary user launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(), optsBundle); } return true; } catch (SecurityException e) { if (Utilities.ATLEAST_MARSHMALLOW && tag instanceof ItemInfo) { // Due to legacy reasons, direct call shortcuts require Launchers to have the // corresponding permission. Show the appropriate permission prompt if that // is the case. if (intent.getComponent() == null && Intent.ACTION_CALL.equals(intent.getAction()) && checkSelfPermission( Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // TODO: Rename sPendingAddItem to a generic name. sPendingAddItem = preparePendingAddArgs(REQUEST_PERMISSION_CALL_PHONE, intent, 0, (ItemInfo) tag); requestPermissions(new String[] { Manifest.permission.CALL_PHONE }, REQUEST_PERMISSION_CALL_PHONE); return false; } } Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e); } return false; }
From source file:mp.teardrop.LibraryActivity.java
@Override public boolean onContextItemSelected(MenuItem item) { if (item.getGroupId() == MENU_GROUP_ROUND_BUTTON) { Limiter limiter = mPagerAdapter.getCurrentLimiter(); Intent intent = null; switch (mPagerAdapter.getCurrentType()) { case MediaUtils.TYPE_FILE: intent = new Intent(); intent.putExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_FILE); intent.putExtra("file", limiter == null ? "/" : limiter.data.toString()); break; case MediaUtils.TYPE_UNIFIED: if (limiter != null && limiter.type <= 20) { intent = new Intent(); intent.putExtra(LibraryAdapter.DATA_TYPE, limiter.type); intent.putExtra(LibraryAdapter.DATA_ID, (Long) limiter.data); } //else continue with null limiter, which will play the entire MediaStore break; }//from w w w . j a va 2 s .com mRoundPlayAllButton.setVisibility(View.GONE); pickSongs(intent, item.getItemId() == MENU_PLAY_ALL ? ACTION_PLAY_ALL : ACTION_ENQUEUE_ALL); return true; } if (item.getGroupId() != 0) { return super.onContextItemSelected(item); } final Intent intent = item.getIntent(); switch (item.getItemId()) { case MENU_EXPAND: expand(intent); if (mDefaultAction == ACTION_LAST_USED && mLastAction != ACTION_EXPAND) { mLastAction = ACTION_EXPAND; } break; case MENU_ENQUEUE: pickSongs(intent, ACTION_ENQUEUE); break; case MENU_PLAY: pickSongs(intent, ACTION_PLAY); break; case MENU_PLAY_ALL: pickSongs(intent, ACTION_PLAY_ALL); break; case MENU_ENQUEUE_ALL: pickSongs(intent, ACTION_ENQUEUE_ALL); break; case MENU_NEW_PLAYLIST: { NewPlaylistDialog dialog = new NewPlaylistDialog(this, null, R.string.create, intent); dialog.setDismissMessage(mHandler.obtainMessage(MSG_NEW_PLAYLIST, dialog)); dialog.show(); break; } case MENU_RENAME_PLAYLIST: { NewPlaylistDialog dialog = new NewPlaylistDialog(this, intent.getStringExtra("title"), R.string.rename, intent); dialog.setDismissMessage(mHandler.obtainMessage(MSG_RENAME_PLAYLIST, dialog)); dialog.show(); break; } case MENU_DELETE: String delete_message = getString(R.string.delete_item, intent.getStringExtra("title")); AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.delete); dialog.setMessage(delete_message) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mHandler.sendMessage(mHandler.obtainMessage(MSG_DELETE, intent)); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); dialog.create().show(); break; case MENU_ADD_TO_PLAYLIST: { SubMenu playlistMenu = item.getSubMenu(); playlistMenu.add(0, MENU_NEW_PLAYLIST, 0, R.string.new_playlist).setIntent(intent); Cursor cursor = Playlist.queryPlaylists(getContentResolver()); if (cursor != null) { for (int i = 0, count = cursor.getCount(); i != count; ++i) { cursor.moveToPosition(i); long id = cursor.getLong(0); String name = cursor.getString(1); Intent copy = new Intent(intent); copy.putExtra("playlist", id); copy.putExtra("playlistName", name); playlistMenu.add(0, MENU_SELECT_PLAYLIST, 0, name).setIntent(copy); } cursor.close(); } break; } case MENU_SELECT_PLAYLIST: mHandler.sendMessage(mHandler.obtainMessage(MSG_ADD_TO_PLAYLIST, intent)); break; case MENU_MORE_FROM_ARTIST: { String selection = "_id="; selection += intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID); setLimiter(-1, selection); updateLimiterViews(); break; } case MENU_MORE_FROM_ALBUM: setLimiter(-1, "_id=" + intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID)); updateLimiterViews(); break; } return true; }
From source file:org.tvbrowser.tvbrowser.TvBrowser.java
@Override protected void onCreate(Bundle savedInstanceState) { handler = new Handler(); PrefUtils.initialize(TvBrowser.this); Intent start = getIntent(); if (start != null && start.hasExtra(SettingConstants.CHANNEL_ID_EXTRA)) { mProgramListChannelId = start.getIntExtra(SettingConstants.CHANNEL_ID_EXTRA, FragmentProgramsList.NO_CHANNEL_SELECTION_ID); mProgramListScrollTime = start.getLongExtra(SettingConstants.START_TIME_EXTRA, -1); }//from ww w .j ava 2 s . com /* * Hack to force overflow menu button to be shown from: * http://stackoverflow.com/questions/9286822/how-to-force-use-of-overflow-menu-on-devices-with-menu-button */ try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // Ignore } try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); int oldVersion = PrefUtils.getIntValueWithDefaultKey(R.string.OLD_VERSION, R.integer.old_version_default); //FAVORITE_LIST if (oldVersion > getResources().getInteger(R.integer.old_version_default) && oldVersion < 309) { new Thread("READ REMINDERS ONCE FOR ICON") { @Override public void run() { Cursor reminders = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA, new String[] { TvBrowserContentProvider.KEY_ID }, TvBrowserContentProvider.DATA_KEY_MARKING_REMINDER + " OR " + TvBrowserContentProvider.DATA_KEY_MARKING_FAVORITE_REMINDER, null, TvBrowserContentProvider.KEY_ID); try { reminders.moveToPosition(-1); int idColumn = reminders.getColumnIndex(TvBrowserContentProvider.KEY_ID); ArrayList<String> reminderIdList = new ArrayList<String>(); while (reminders.moveToNext()) { reminderIdList.add(String.valueOf(reminders.getLong(idColumn))); } ProgramUtils.addReminderIds(getApplicationContext(), reminderIdList); } finally { IOUtils.closeCursor(reminders); } }; }.start(); } if (oldVersion < 304) { Set<String> favoritesSet = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this) .getStringSet("FAVORITE_LIST", new HashSet<String>()); int id = 1000; for (String favorite : favoritesSet) { Favorite fav = new Favorite(id++, favorite); if (fav.isValid()) { fav.save(getApplicationContext()); } else { Favorite.handleFavoriteMarking(TvBrowser.this, fav, Favorite.TYPE_MARK_REMOVE); } } Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit(); edit.remove("FAVORITE_LIST"); edit.commit(); } if (oldVersion < 204) { int firstTime = PrefUtils.getStringValueAsInt(R.string.PREF_REMINDER_TIME, R.string.pref_reminder_time_default); boolean remindAgain = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this) .getBoolean("PREF_REMIND_AGAIN_AT_START", false); Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit(); edit.remove("PREF_REMIND_AGAIN_AT_START"); edit.commit(); if (remindAgain && firstTime > 0) { edit.putString(getString(R.string.PREF_REMINDER_TIME_SECOND), getString(R.string.pref_reminder_time_default)); edit.commit(); Intent updateAlarmValues = new Intent(UpdateAlarmValue.class.getCanonicalName()); sendBroadcast(updateAlarmValues); } } if (oldVersion < 218) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this); Editor edit = pref.edit(); boolean userDefined = addUserColor(pref, edit, R.color.pref_color_on_air_background_tvb_style_default, R.string.PREF_COLOR_ON_AIR_BACKGROUND, R.string.PREF_COLOR_ON_AIR_BACKGROUND_USER_DEFINED); userDefined = addUserColor(pref, edit, R.color.pref_color_on_air_progress_tvb_style_default, R.string.PREF_COLOR_ON_AIR_PROGRESS, R.string.PREF_COLOR_ON_AIR_PROGRESS_USER_DEFINED) || userDefined; userDefined = addUserColor(pref, edit, R.color.pref_color_mark_tvb_style_default, R.string.PREF_COLOR_MARKED, R.string.PREF_COLOR_MARKED_USER_DEFINED) || userDefined; userDefined = addUserColor(pref, edit, R.color.pref_color_mark_favorite_tvb_style_default, R.string.PREF_COLOR_FAVORITE, R.string.PREF_COLOR_FAVORITE) || userDefined; userDefined = addUserColor(pref, edit, R.color.pref_color_mark_reminder_tvb_style_default, R.string.PREF_COLOR_REMINDER, R.string.PREF_COLOR_REMINDER_USER_DEFINED) || userDefined; userDefined = addUserColor(pref, edit, R.color.pref_color_mark_sync_tvb_style_favorite_default, R.string.PREF_COLOR_SYNC, R.string.PREF_COLOR_SYNC_USER_DEFINED) || userDefined; if (userDefined) { edit.putString(getString(R.string.PREF_COLOR_STYLE), "0"); } edit.commit(); } if (oldVersion < 242) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this); Editor edit = pref.edit(); if (pref.contains("PREF_WIDGET_BACKGROUND_TRANSPARENCY") && !pref.getBoolean("PREF_WIDGET_BACKGROUND_TRANSPARENCY", true)) { edit.remove("PREF_WIDGET_BACKGROUND_TRANSPARENCY"); edit.putString(getString(R.string.PREF_WIDGET_BACKGROUND_TRANSPARENCY_HEADER), "0"); edit.putString(getString(R.string.PREF_WIDGET_BACKGROUND_TRANSPARENCY_LIST), "0"); edit.putBoolean(getString(R.string.PREF_WIDGET_BACKGROUND_ROUNDED_CORNERS), false); } if (pref.contains("SELECTED_TV_CHANNELS_LIST")) { edit.remove("SELECTED_TV_CHANNELS_LIST"); } if (pref.contains("SELECTED_RADIO_CHANNELS_LIST")) { edit.remove("SELECTED_RADIO_CHANNELS_LIST"); } if (pref.contains("SELECTED_CINEMA_CHANNELS_LIST")) { edit.remove("SELECTED_CINEMA_CHANNELS_LIST"); } edit.commit(); } if (oldVersion < 284 && PrefUtils .getStringValue(R.string.PREF_PROGRAM_LISTS_DIVIDER_SIZE, R.string.pref_program_lists_divider_size_default) .equals(getString(R.string.divider_small))) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this); Editor edit = pref.edit(); edit.remove(getString(R.string.PREF_PROGRAM_LISTS_DIVIDER_SIZE)); edit.commit(); } if (oldVersion < 287 && PrefUtils.getBooleanValue(R.string.PREF_WIDGET_BACKGROUND_ROUNDED_CORNERS, true)) { Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit(); edit.remove(getString(R.string.PREF_WIDGET_BACKGROUND_ROUNDED_CORNERS)); edit.commit(); UiUtils.updateImportantProgramsWidget(getApplicationContext()); UiUtils.updateRunningProgramsWidget(getApplicationContext()); } if (oldVersion > getResources().getInteger(R.integer.old_version_default) && oldVersion < pInfo.versionCode) { handler.postDelayed(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this); builder.setTitle(R.string.info_version); builder.setMessage(Html.fromHtml(getString(R.string.info_version_new))); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } }, 5000); } else if (oldVersion != getResources().getInteger(R.integer.old_version_default)) { handler.postDelayed(new Runnable() { @Override public void run() { showNews(); } }, 5000); } if (oldVersion != pInfo.versionCode) { Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit(); edit.putInt(getString(R.string.OLD_VERSION), pInfo.versionCode); edit.commit(); } } catch (NameNotFoundException e) { } super.onCreate(savedInstanceState); SettingConstants.initializeLogoMap(TvBrowser.this, false); setContentView(R.layout.activity_tv_browser); mProgamListStateStack = new Stack<ProgramsListState>(); ALL_VALUE = getResources().getString(R.string.filter_channel_all); if (savedInstanceState != null) { updateRunning = savedInstanceState.getBoolean(SettingConstants.UPDATE_RUNNING_KEY, false); selectingChannels = savedInstanceState.getBoolean(SettingConstants.SELECTION_CHANNELS_KEY, false); } // Set up the action bar. actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOffscreenPageLimit(3); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); Fragment fragment = mSectionsPagerAdapter.getRegisteredFragment(position); if (fragment instanceof ProgramTableFragment) { ((ProgramTableFragment) fragment).firstLoad(getLayoutInflater()); ((ProgramTableFragment) fragment).scrollToTime(0, mScrollTimeItem); } if (mFilterItem != null) { mFilterItem.setVisible(!(fragment instanceof FragmentFavorites) && !mSearchExpanded); } if (mCreateFavorite != null) { mCreateFavorite.setVisible(fragment instanceof FragmentFavorites && !mSearchExpanded); } mProgramsListWasShow = false; if (position != 1) { mProgamListStateStack.clear(); } } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this)); } int startTab = Integer.parseInt( PrefUtils.getStringValue(R.string.TAB_TO_SHOW_AT_START, R.string.tab_to_show_at_start_default)); if (mSectionsPagerAdapter.getCount() > startTab) { mViewPager.setCurrentItem(startTab); } PluginHandler.loadPlugins(getApplicationContext(), handler); IOUtils.handleDataUpdatePreferences(TvBrowser.this); }
From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //Log.d("AlerteVoirie_PM", "Result : " + requestCode); switch (requestCode) { case R.id.existing_incidents_add_picture: case R.id.ImageView_far: case R.id.ImageView_close: if (resultCode == RESULT_OK) { try { String finalPath; if (data != null) { Uri path = data.getData(); // OI FILE Manager String filemanagerString = path.getPath(); // MEDIA GALLERY String selectedImagePath = getPath(path); if (selectedImagePath != null) { finalPath = selectedImagePath; System.out.println("selectedImagePath is the right one for you! " + finalPath); } else { finalPath = filemanagerString; System.out.println("filemanagerstring is the right one for you!" + finalPath); }//from w w w .j av a2 s .c o m // boolean isImage = true; } else { finalPath = uriOfPicFromCamera.getPath(); } // if (data == null || getMimeType(finalPath).startsWith("image")) { InputStream in; BitmapFactory.Options opt = new BitmapFactory.Options(); // get the sample size to have a smaller image in = getContentResolver().openInputStream(Uri.fromFile(new File(finalPath))); opt.inSampleSize = getSampleSize( getContentResolver().openInputStream(Uri.fromFile(new File(finalPath)))); in.close(); // decode a sampled version of the picture in = getContentResolver().openInputStream(Uri.fromFile(new File(finalPath))); Bitmap picture = BitmapFactory.decodeStream(in, null, opt); // Bitmap picture = BitmapFactory.decodeFile(finalPath); in.close(); File f = new File(uriOfPicFromCamera.getPath()); f.delete(); // save the new image String pictureName = requestCode == R.id.ImageView_close ? CAPTURE_CLOSE : CAPTURE_FAR; FileOutputStream fos = openFileOutput(pictureName, MODE_PRIVATE); picture.compress(CompressFormat.JPEG, 80, fos); fos.close(); if (requestCode == R.id.ImageView_far || mAdditionalImageType == ADDITIONAL_IMAGE_TYPE_FAR) { loadZoom(); } else if (mAdditionalImageType == ADDITIONAL_IMAGE_TYPE_CLOSE) { File img = new File(getFilesDir() + "/" + CAPTURE_FAR); mCurrentAction = ACTION_ADD_IMAGE; timeoutHandler.postDelayed(timeout, TIMEOUT); AVService.getInstance(this).postImage(this, Utils.getUdid(this), "", Long.toString(currentIncident.id), null, img, false); } if (requestCode != R.id.existing_incidents_add_picture) { setPictureToImageView(pictureName, (ImageView) findViewById(requestCode)); } if (requestCode == R.id.ImageView_far && ((TextView) findViewById(R.id.TextView_address)).getText().length() > 0) { ((Button) findViewById(R.id.Button_validate)).setEnabled(true); } // } // FileOutputStream fos = openFileOutput("capture", MODE_WORLD_READABLE); // InputStream in = getContentResolver().openInputStream(uriOfPicFromCamera); // Utils.fromInputToOutput(in, fos); // fos.close(); // in.close(); mAdditionalImageType = 0; } catch (FileNotFoundException e) { Log.e("AlerteVoirie_PM", "", e); } catch (IOException e) { Log.e("AlerteVoirie_PM", "", e); } catch (NullPointerException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog alert; builder.setMessage("Image invalide").setCancelable(false).setPositiveButton("Ok", null); alert = builder.create(); alert.show(); } } else if (resultCode == RESULT_CANCELED) { if (uriOfPicFromCamera != null) { File tmpFile = new File(uriOfPicFromCamera.getPath()); tmpFile.delete(); uriOfPicFromCamera = null; } } break; case REQUEST_CATEGORY: if (resultCode == RESULT_OK) { setCategory(data.getLongExtra(IntentData.EXTRA_CATEGORY_ID, -1)); // TODO do this when update request ready findViewById(R.id.Button_validate).setVisibility(View.VISIBLE); } break; case REQUEST_POSITION: if (resultCode == RESULT_OK) { currentIncident.address = data.getStringExtra(IntentData.EXTRA_ADDRESS); currentIncident.longitude = data.getDoubleExtra(IntentData.EXTRA_LONGITUDE, 0); currentIncident.latitude = data.getDoubleExtra(IntentData.EXTRA_LATITUDE, 0); ((TextView) findViewById(R.id.TextView_address)).setText(currentIncident.address); if (currentIncident.address != null && currentIncident.address.length() > 0 && canvalidate) { ((Button) findViewById(R.id.Button_validate)).setEnabled(true); } findViewById(R.id.Button_validate).setVisibility(View.VISIBLE); } break; case REQUEST_COMMENT: if (resultCode == RESULT_OK) { currentIncident.description = data.getStringExtra(IntentData.EXTRA_COMMENT); ((TextView) findViewById(R.id.TextView_comment)).setText(currentIncident.description); if (currentIncident.description != null) findViewById(R.id.TextView_nocomment).setVisibility(View.GONE); // findViewById(R.id.Button_validate).setVisibility(View.VISIBLE); } break; case REQUEST_IMAGE_COMMENT: if (resultCode == RESULT_OK) { showDialog(DIALOG_PROGRESS); File img = new File(getFilesDir() + "/arrowed.jpg"); mCurrentAction = ACTION_ADD_IMAGE; timeoutHandler.postDelayed(timeout, TIMEOUT); AVService.getInstance(this).postImage(this, Utils.getUdid(this), data.getStringExtra(IntentData.EXTRA_COMMENT), Long.toString(currentIncident.id), img, null, false); } break; case REQUEST_COMMENT_BEFORE_EXIT: if (resultCode == RESULT_OK) { currentIncident.description = data.getStringExtra(IntentData.EXTRA_COMMENT); ((TextView) findViewById(R.id.TextView_comment)).setText(currentIncident.description); postNewIncident(); } break; case REQUEST_DETAILS: if (resultCode == RESULT_OK) { // startActivityForResult(data, requestCode) if (mCurrentAction == ACTION_ADD_IMAGE) { Intent i = new Intent(getApplicationContext(), AddCommentActivity.class); startActivityForResult(i, REQUEST_IMAGE_COMMENT); } else { // set new img setPictureToImageView("arrowed.jpg", (ImageView) findViewById(R.id.ImageView_far)); loadComment(REQUEST_COMMENT); } } break; default: super.onActivityResult(requestCode, resultCode, data); break; } }
From source file:org.tvbrowser.tvbrowser.TvBrowser.java
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent);/*from w ww . j av a2 s. co m*/ if (mProgamListStateStack != null) { mProgamListStateStack.clear(); } if (intent != null && intent.hasExtra(SettingConstants.CHANNEL_ID_EXTRA)) { int channelId = intent.getIntExtra(SettingConstants.CHANNEL_ID_EXTRA, 0); if (!getChannelFilterSelection().contains(String.valueOf(channelId)) && !mCurrentChannelFilterId.equals(SettingConstants.ALL_FILTER_ID)) { updateChannelFilter(mAllFilter, R.drawable.ic_filter_default); } final Intent showChannel = new Intent(SettingConstants.SHOW_ALL_PROGRAMS_FOR_CHANNEL_INTENT); showChannel.putExtra(SettingConstants.CHANNEL_ID_EXTRA, channelId); showChannel.putExtra(SettingConstants.START_TIME_EXTRA, intent.getLongExtra(SettingConstants.START_TIME_EXTRA, 0)); showChannel.putExtra(SettingConstants.NO_BACK_STACKUP_EXTRA, true); handler.postDelayed(new Runnable() { @Override public void run() { LocalBroadcastManager.getInstance(TvBrowser.this).sendBroadcastSync(showChannel); } }, 1000); } }
From source file:de.tubs.ibr.dtn.service.DaemonService.java
/** * Incoming Intents are handled here//from w w w .j ava 2s . c o m * * @param intent */ @SuppressWarnings("deprecation") public void onHandleIntent(Intent intent, int startId) { String action = intent.getAction(); if (ACTION_STARTUP.equals(action)) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // only start if the daemon is offline or in error state // and if the daemon switch is on if ((mDaemonProcess.getState().equals(DaemonState.OFFLINE) || mDaemonProcess.getState().equals(DaemonState.ERROR)) && prefs.getBoolean(Preferences.KEY_ENABLED, true)) { // start-up the daemon mDaemonProcess.start(); final Intent storeStatsIntent = new Intent(this, DaemonService.class); storeStatsIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STORE_STATS); startService(storeStatsIntent); } } else if (ACTION_SHUTDOWN.equals(action)) { // stop main loop mDaemonProcess.stop(); } else if (ACTION_RESTART.equals(action)) { Integer level = intent.getIntExtra("runlevel", 0); // restart the daemon into the given runlevel mDaemonProcess.restart(level, new DaemonProcess.OnRestartListener() { @Override public void OnStop(DaemonRunLevel previous, DaemonRunLevel next) { if (next.swigValue() < DaemonRunLevel.RUNLEVEL_API.swigValue() && previous.swigValue() >= DaemonRunLevel.RUNLEVEL_API.swigValue()) { // shutdown the session manager mSessionManager.destroy(); } } @Override public void OnStart(DaemonRunLevel previous, DaemonRunLevel next) { if (previous.swigValue() < DaemonRunLevel.RUNLEVEL_API.swigValue() && next.swigValue() >= DaemonRunLevel.RUNLEVEL_API.swigValue()) { // re-initialize the session manager mSessionManager.initialize(); } } @Override public void OnReloadConfiguration() { } }); final Intent storeStatsIntent = new Intent(this, DaemonService.class); storeStatsIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STORE_STATS); startService(storeStatsIntent); } else if (ACTION_UPDATE_NOTIFICATION.equals(action)) { if (intent.hasExtra("text")) { // update state text in the notification updateNotification(intent.getStringExtra("text")); } else { // update state text in the notification updateNotification(null); } } else if (de.tubs.ibr.dtn.Intent.REGISTER.equals(action)) { final Registration reg = (Registration) intent.getParcelableExtra("registration"); final PendingIntent pi = (PendingIntent) intent.getParcelableExtra("app"); mSessionManager.register(pi.getTargetPackage(), reg); } else if (de.tubs.ibr.dtn.Intent.UNREGISTER.equals(action)) { final PendingIntent pi = (PendingIntent) intent.getParcelableExtra("app"); mSessionManager.unregister(pi.getTargetPackage()); } else if (ACTION_INITIATE_CONNECTION.equals(action)) { if (intent.hasExtra("endpoint")) { mDaemonProcess.initiateConnection(intent.getStringExtra("endpoint")); } } else if (ACTION_CLEAR_STORAGE.equals(action)) { mDaemonProcess.clearStorage(); Toast.makeText(this, R.string.toast_storage_cleared, Toast.LENGTH_SHORT).show(); } else if (ACTION_NETWORK_CHANGED.equals(action)) { // This intent tickle the service if something has changed in the // network configuration. If the service was enabled but terminated // before, // it will be started now. final Intent storeStatsIntent = new Intent(this, DaemonService.class); storeStatsIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STORE_STATS); startService(storeStatsIntent); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // if discovery is configured as "smart" if ("smart".equals(prefs.getString(Preferences.KEY_DISCOVERY_MODE, "smart"))) { // enable discovery for 2 minutes final Intent discoIntent = new Intent(DaemonService.this, DaemonService.class); discoIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_START_DISCOVERY); discoIntent.putExtra(EXTRA_DISCOVERY_DURATION, 120L); startService(discoIntent); } } else if (ACTION_STORE_STATS.equals(action)) { // cancel the next scheduled collection mServiceHandler.removeCallbacks(mCollectStats); if (mStatsLastAction != null) { Calendar now = Calendar.getInstance(); now.roll(Calendar.MINUTE, -1); if (mStatsLastAction.before(now.getTime())) { refreshStats(); } } else { refreshStats(); } // schedule next collection in 15 minutes mServiceHandler.postDelayed(mCollectStats, 900000); } else if (ACTION_INITIALIZE.equals(action)) { // initialize the daemon service initialize(); } else if (ACTION_START_DISCOVERY.equals(action)) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String discoMode = prefs.getString(Preferences.KEY_DISCOVERY_MODE, "smart"); boolean stayOn = "on".equals(discoMode) && mDiscoveryState; // create stop discovery intent Intent stopIntent = new Intent(this, DaemonService.class); stopIntent.setAction(DaemonService.ACTION_STOP_DISCOVERY); if (intent.hasExtra(EXTRA_DISCOVERY_DURATION) && !stayOn) { Long duration = intent.getLongExtra(EXTRA_DISCOVERY_DURATION, 120); Message msg = mServiceHandler.obtainMessage(); msg.what = MSG_WHAT_STOP_DISCOVERY; msg.arg1 = startId; msg.obj = stopIntent; mServiceHandler.sendMessageDelayed(msg, duration * 1000); Log.i(TAG, "Discovery stop scheduled in " + duration + " seconds."); } else { mServiceHandler.removeMessages(MSG_WHAT_STOP_DISCOVERY); Log.i(TAG, "Scheduled discovery stop removed."); } // only start discovery if not active if (!mDiscoveryState) { // start P2P discovery and enable IPND mDaemonProcess.startDiscovery(); // start Wi-Fi P2P discovery if (mP2pManager != null) mP2pManager.startDiscovery(); // set global discovery state mDiscoveryState = true; // request notification update requestNotificationUpdate(getResources().getString(R.string.ticker_discovery_started)); } } else if (ACTION_STOP_DISCOVERY.equals(action)) { // only stop discovery if active if (mDiscoveryState) { // stop P2P discovery and disable IPND mDaemonProcess.stopDiscovery(); // stop Wi-Fi P2P discovery if (mP2pManager != null) mP2pManager.stopDiscovery(); // set global discovery state mDiscoveryState = false; // request notification update requestNotificationUpdate(getResources().getString(R.string.ticker_discovery_stopped)); } // remove all stop discovery messages mServiceHandler.removeMessages(MSG_WHAT_STOP_DISCOVERY); Log.i(TAG, "Scheduled discovery stop removed."); } // stop the daemon if it should be offline if (mDaemonProcess.getState().equals(DaemonState.OFFLINE) && (startId != -1)) stopSelf(startId); }
From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { DraftData d = DraftData.INSTANCE;// w ww . ja v a2 s .c o m switch (requestCode) { case VIEW_FINDCONTACT_ID: case VIEW_PASSPHRASE_CHANGE_ID: case VIEW_PASSPHRASE_ID: SafeSlinger.setPassphraseOpen(false); switch (resultCode) { case RESULT_OK: if (data != null) { if (requestCode == VIEW_FINDCONTACT_ID) { String passNew = data.getStringExtra(extra.PASS_PHRASE_NEW); boolean preExistingKey = doPassEntryCheck(passNew, null, false); if (!preExistingKey) { CreateKeyTask createKey = new CreateKeyTask(); createKey.execute(passNew); break; } } else if (requestCode == VIEW_PASSPHRASE_CHANGE_ID) { String passOld = data.getStringExtra(extra.PASS_PHRASE_OLD); String passNew = data.getStringExtra(extra.PASS_PHRASE_NEW); doPassEntryCheck(passNew, passOld, true); } else { // login String passOld = data.getStringExtra(extra.PASS_PHRASE_OLD); doPassEntryCheck(passOld, null, false); } if (loadCurrentPassPhrase()) { processIntent(getIntent()); } // if requested, and logged in, try to decrypt // messages String passCached = SafeSlinger.getCachedPassPhrase(SafeSlingerPrefs.getKeyIdString()); if (SafeSlingerPrefs.getAutoDecrypt() && !TextUtils.isEmpty(passCached)) { DecryptPendingTask decryptPending = new DecryptPendingTask(); decryptPending.execute(passCached); } } isSetupCheckComplete(); break; case PassPhraseActivity.RESULT_CLOSEANDCONTINUE: isSetupCheckComplete(); break; case RESULT_CANCELED: if (requestCode == VIEW_FINDCONTACT_ID) { // if cancel setting up new profile, save nothing // and push user selection back one int user = SafeSlingerPrefs.getUser(); if (user > 0) { SafeSlingerPrefs.setUser(user - 1); deleteUser(user); } } // this separate task is now finished showExit(RESULT_CANCELED); break; case PassPhraseActivity.RESULT_BACKPRESSED: // this separate task is now finished showExit(RESULT_CANCELED); break; } break; case REQUEST_QRECEIVE_MGS: switch (resultCode) { case RESULT_OK: doGetPushRegistration(); break; case RESULT_CANCELED: SafeSlingerPrefs.setPushRegistrationIdWriteOnlyC2dm(SafeSlingerConfig.NOTIFY_NOPUSH_TOKENDATA); isSetupCheckComplete(); break; } break; case VIEW_RECIPSEL_ID: switch (resultCode) { case PickRecipientsActivity.RESULT_SLINGKEYS: setTab(Tabs.SLINGKEYS); refreshView(); break; case PickRecipientsActivity.RESULT_RECIPSEL: RecipientDbAdapter dbRecipient = RecipientDbAdapter.openInstance(getApplicationContext()); long rowIdRecipient = data.getLongExtra(extra.RECIPIENT_ROW_ID, -1L); Cursor c = dbRecipient.fetchRecipient(rowIdRecipient); if (c != null) { try { if (c.moveToFirst()) { d.setRecip(new RecipientRow(c)); CheckRegistrationStateTask task = new CheckRegistrationStateTask(); task.execute(d.getRecip()); setTab(Tabs.COMPOSE); refreshView(); } else { showNote(R.string.error_InvalidRecipient); setTab(Tabs.COMPOSE); refreshView(); break; } } finally { c.close(); } } break; case Activity.RESULT_CANCELED: // clear the selection d.clearRecip(); setTab(Tabs.COMPOSE); refreshView(); break; } break; case VIEW_RECIPSEL1: switch (resultCode) { case PickRecipientsActivity.RESULT_SLINGKEYS: setTab(Tabs.SLINGKEYS); refreshView(); break; case PickRecipientsActivity.RESULT_RECIPSEL: long rowIdRecipient1 = data.getLongExtra(extra.RECIPIENT_ROW_ID, -1); if (d.existsRecip2() && rowIdRecipient1 == d.getRecip2RowId()) { showNote(R.string.error_InvalidRecipient); break; } RecipientDbAdapter dbRecipient = RecipientDbAdapter.openInstance(getApplicationContext()); Cursor c = dbRecipient.fetchRecipient(rowIdRecipient1); if (c != null) { try { if (c.moveToFirst()) { d.setRecip1(new RecipientRow(c)); refreshView(); } else { showNote(R.string.error_InvalidRecipient); break; } } finally { c.close(); } } break; case Activity.RESULT_CANCELED: // clear the selection d.clearRecip1(); setTab(Tabs.INTRO); refreshView(); break; } break; case VIEW_RECIPSEL2: switch (resultCode) { case PickRecipientsActivity.RESULT_SLINGKEYS: setTab(Tabs.SLINGKEYS); refreshView(); break; case PickRecipientsActivity.RESULT_RECIPSEL: long rowIdRecipient2 = data.getLongExtra(extra.RECIPIENT_ROW_ID, -1); if (d.existsRecip1() && rowIdRecipient2 == d.getRecip1RowId()) { showNote(R.string.error_InvalidRecipient); break; } RecipientDbAdapter dbRecipient = RecipientDbAdapter.openInstance(getApplicationContext()); Cursor c = dbRecipient.fetchRecipient(rowIdRecipient2); if (c != null) { try { if (c.moveToFirst()) { d.setRecip2(new RecipientRow(c)); refreshView(); } else { showNote(R.string.error_InvalidRecipient); break; } } finally { c.close(); } } break; case Activity.RESULT_CANCELED: // clear the selection d.clearRecip2(); setTab(Tabs.INTRO); refreshView(); break; } break; case VIEW_SETTINGS_ID: // handle potential language change if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { recreate(); } else { // TODO: find better update for <= 2.3 // startActivity(getIntent()); // finish(); } switch (resultCode) { case SettingsActivity.RESULT_NEW_PASSPHRASE: // remove cached pass SafeSlinger.removeCachedPassPhrase(SafeSlingerPrefs.getKeyIdString()); SafeSlinger.startCacheService(HomeActivity.this); showPassPhrase(false, true); break; case SettingsActivity.RESULT_LOGOUT: doManualLogout(); break; case SettingsActivity.RESULT_DELETE_KEYS: // allow deletion of newer keys only showManagePassphrases(getMoreRecentKeys()); break; case SettingsActivity.RESULT_CHANGE_PASSTTL: // update timer since ttl has changed updatePassCacheTimer(); break; case Activity.RESULT_CANCELED: // nothing to change... break; } break; case VIEW_FILESAVE_ID: switch (resultCode) { case RESULT_OK: try { String chosenFile = data.getStringExtra(extra.FNAME); String chosenPath = data.getStringExtra(extra.FPATH); MessageData recvMsg = new MessageData(); recvMsg.setFileName(chosenFile); doSaveDownloadedFile(new File(chosenPath, chosenFile), recvMsg); } catch (OutOfMemoryError e) { showNote(R.string.error_OutOfMemoryError); refreshView(); break; } break; case RESULT_CANCELED: refreshView(); break; } break; case VIEW_EXCHANGE_ID: switch (resultCode) { case ExchangeActivity.RESULT_EXCHANGE_OK: showSave(data.getExtras()); break; case ExchangeActivity.RESULT_EXCHANGE_CANCELED: refreshView(); break; } break; case VIEW_SAVE_ID: switch (resultCode) { case SaveActivity.RESULT_SAVE: SafeSlingerPrefs.setFirstExchangeComplete(true); // locally store trusted exchanged items Bundle args = data.getExtras(); args.putInt(extra.RECIP_SOURCE, RecipientDbAdapter.RECIP_SOURCE_EXCHANGE); ImportFromExchangeTask importFromExchange = new ImportFromExchangeTask(); importFromExchange.execute(args); break; case SaveActivity.RESULT_SELNONE: SafeSlingerPrefs.setFirstExchangeComplete(true); int exchanged = data.getExtras().getInt(extra.EXCHANGED_TOTAL); showNote(String.format(getString(R.string.state_SomeContactsImported), "0/" + exchanged)); break; case RESULT_CANCELED: showNote(String.format(getString(R.string.state_SomeContactsImported), "0")); break; default: showNote(String.format(getString(R.string.state_SomeContactsImported), "?")); break; } break; case RESULT_PICK_CONTACT_SENDER: // parse newly selected sender contact switch (resultCode) { case RESULT_OK: Uri contactData = data.getData(); Cursor c = getContentResolver().query(contactData, null, null, null, null); if (c != null) { try { if (c.moveToFirst()) { String contactLookupKey = c .getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); // save these for lookup and display // purposes SafeSlingerPrefs.setContactLookupKey(contactLookupKey); SafeSlingerPrefs.setContactName(name); } } finally { c.close(); } } refreshView(); break; case RESULT_CANCELED: refreshView(); break; default: break; } break; case VIEW_FILEATTACH_ID: // file should be assigned for real now switch (resultCode) { case RESULT_OK: try { String path = null; if (data == null) { // capture camera data from 1st non-standard // return from hardware path = SafeSlinger.getTempCameraFileUri().getPath(); doLoadAttachment(path); } else { String chosenFile = data.getStringExtra(extra.FNAME); String chosenPath = data.getStringExtra(extra.FPATH); if (chosenFile != null || chosenPath != null) { // from our own File Manager path = chosenPath + File.separator + chosenFile; doLoadAttachment(path); } else if (data.getData() != null) { // String action = data.getAction(); // act=null // act=android.intent.action.GET_CONTENT long filesize = getOutStreamSizeAndData(data.getData(), null); if (filesize <= 0) { showNote(R.string.error_CannotSendEmptyFile); refreshView(); break; } } else { // capture camera data from 2nd non-standard // return from hardware path = SafeSlinger.getTempCameraFileUri().getPath(); doLoadAttachment(path); } } } catch (OutOfMemoryError e) { showNote(R.string.error_OutOfMemoryError); refreshView(); break; } catch (FileNotFoundException e) { showNote(e); refreshView(); break; } catch (IOException e) { showNote(e); refreshView(); break; } setTab(Tabs.COMPOSE); refreshView(); break; case RESULT_CANCELED: d.removeFile(); setTab(Tabs.COMPOSE); refreshView(); break; default: break; } break; case RESULT_PICK_MSGAPP: setTab(Tabs.COMPOSE); refreshView(); break; case RESULT_ERROR: showExit(RESULT_CANCELED); break; } super.onActivityResult(requestCode, resultCode, data); }
From source file:com.nbplus.vbroadlauncher.BroadcastPushReceiver.java
@Override public void onReceive(Context context, Intent intent) { if (intent == null) { return;/*from ww w .ja va 2s .c o m*/ } Intent pi; String action = intent.getAction(); if (PushConstants.ACTION_PUSH_STATUS_CHANGED.equals(action)) { LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } else if (PushConstants.ACTION_PUSH_MESSAGE_RECEIVED.equals(action)) { Log.d(TAG, "Receive.. broadcast ACTION_PUSH_MESSAGE_RECEIVED from push service. re-direct to activity!!!"); //TODO: iot ?. // int i = 0; // if (i == 0) { // return; // } PushMessageData data = null; try { data = (PushMessageData) intent.getParcelableExtra(PushConstants.EXTRA_PUSH_MESSAGE_DATA); if (data == null || StringUtils.isEmptyString(data.getPayload())) { Log.d(TAG, "empty push message string !!"); return; } } catch (Exception e) { e.printStackTrace(); return; } PushPayloadData payloadData = null; try { Gson gson = new GsonBuilder().create(); payloadData = gson.fromJson(data.getPayload(), new TypeToken<PushPayloadData>() { }.getType()); } catch (Exception e) { e.printStackTrace(); } if (payloadData == null) { Log.d(TAG, "empty push message data !!"); return; } String type = payloadData.getServiceType(); Log.d(TAG, "HANDLER_MESSAGE_PUSH_MESAGE_RECEIVED received type = " + type + ", messageId = " + payloadData.getMessageId()); payloadData.setAlertMessage(data.getAlert()); switch (type) { // case Constants.PUSH_PAYLOAD_TYPE_REALTIME_BROADCAST: case Constants.PUSH_PAYLOAD_TYPE_NORMAL_BROADCAST: case Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST: TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int callState = telephonyManager.getCallState(); boolean isOutdoor = LauncherSettings.getInstance(context).isOutdoorMode(); playNotificationAlarm(context, R.string.notification_broadcast_push); if (isOutdoor || callState == TelephonyManager.CALL_STATE_OFFHOOK) { // ? ? ?. Log.d(TAG, "Broadcast notification.. isOutdoor mode... "); pi = new Intent(); pi.setAction(action); pi.putExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, intent.getIntExtra( PushConstants.EXTRA_PUSH_STATUS_VALUE, PushConstants.PUSH_STATUS_VALUE_DISCONNECTED)); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); LocalBroadcastManager.getInstance(context).sendBroadcast(pi); return; } if (Constants.OPEN_BETA_PHONE) { String activePackageName = PackageUtils.getActivePackage(context); if (activePackageName != null && !StringUtils.isEmptyString(activePackageName)) { if (Constants.VBROAD_SEND_APP_PACKAGE.equals(activePackageName)) { Log.d(TAG, Constants.VBROAD_SEND_APP_PACKAGE + " is top running application...."); pi = new Intent(); pi.setAction(action); pi.putExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, intent.getIntExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, PushConstants.PUSH_STATUS_VALUE_DISCONNECTED)); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); LocalBroadcastManager.getInstance(context).sendBroadcast(pi); return; } } } // ?? ?. ? Domain url ?? . if (PackageUtils.isActivePackage(context, Constants.GOOGLE_CHROME_PACKAGE_NAME)) { Log.d(TAG, "chrome browser is active...."); // get the last visited URL from the Browser.BOOKMARKS_URI database String url = ""; Uri chromeUri = Uri.parse("content://com.android.chrome.browser/bookmarks"); Cursor cur = context.getContentResolver().query(chromeUri/*Browser.BOOKMARKS_URI*/, new String[] { Browser.BookmarkColumns.URL }, null, null, Browser.BookmarkColumns.DATE + " DESC"); if (cur != null && cur.getCount() > 0) { cur.moveToFirst(); url = cur.getString(cur.getColumnIndex(Browser.BookmarkColumns.URL)); cur.close(); } else { if (cur != null) { cur.close(); } } Log.d(TAG, "Last activated url = " + url); if (!StringUtils.isEmptyString(url) && (url.startsWith(Constants.VBROAD_HTTP_DOMAIN) || url.startsWith(Constants.VBROAD_HTTPS_DOMAIN))) { Log.w(TAG, ">> Village broadcast is running... do not show!!!!"); pi = new Intent(); pi.setAction(action); pi.putExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, intent.getIntExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, PushConstants.PUSH_STATUS_VALUE_DISCONNECTED)); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); LocalBroadcastManager.getInstance(context).sendBroadcast(pi); return; } } // android version check. if (Constants.PUSH_PAYLOAD_TYPE_REALTIME_BROADCAST.equals(type) || Constants.PUSH_PAYLOAD_TYPE_NORMAL_BROADCAST.equals(type)) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Log.d(TAG, ">> This device version code = " + Build.VERSION.SDK_INT + ", not supported version !!"); Toast.makeText(context, R.string.notification_broadcast_not_support, Toast.LENGTH_SHORT); pi = new Intent(); pi.setAction(action); pi.putExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, intent.getIntExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, PushConstants.PUSH_STATUS_VALUE_DISCONNECTED)); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); LocalBroadcastManager.getInstance(context).sendBroadcast(pi); break; } } /*boolean useServiceChatHead = false; if (useServiceChatHead) { i = new Intent(context, RealtimeBroadcastProxyActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setAction(action); i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); context.startActivity(i); } else*/ String playingType = LauncherSettings.getInstance(context).getCurrentPlayingBroadcastType(); if (StringUtils.isEmptyString(playingType) || !Constants.PUSH_PAYLOAD_TYPE_REALTIME_BROADCAST.equals(playingType)) { // ??? ... ? . ??? pi = new Intent(context, RealtimeBroadcastActivity.class); pi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi.setAction(action); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, System.currentTimeMillis()); Log.d(TAG, "1. sendBroadcast() >> ACTION_PUSH_MESSAGE_RECEIVED : idx = " + pi.getLongExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, -1)); // ? ms ? ?? ? ? ? ???? // broadcast ? . // ?? ?? ??. //LocalBroadcastManager.getInstance(context).sendBroadcast(pi); try { //Thread.sleep(30); context.startActivity(pi); } catch (Exception e) { e.printStackTrace(); } } else { // ?? ? ??... ? ?.. ? . if (Constants.PUSH_PAYLOAD_TYPE_REALTIME_BROADCAST.equals(playingType) && Constants.PUSH_PAYLOAD_TYPE_REALTIME_BROADCAST.equals(type)) { pi = new Intent(context, RealtimeBroadcastActivity.class); pi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi.setAction(action); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, System.currentTimeMillis()); Log.d(TAG, "2. sendBroadcast() >> ACTION_PUSH_MESSAGE_RECEIVED : idx = " + pi.getLongExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, -1)); // ? ms ? ?? ? ? ? ???? // broadcast ? . // ?? ?? ??. //LocalBroadcastManager.getInstance(context).sendBroadcast(pi); try { //Thread.sleep(30); context.startActivity(pi); } catch (Exception e) { e.printStackTrace(); } } else { // ? ? ? ??. Log.d(TAG, "? ? ? ??."); Toast.makeText(context, payloadData.getAlertMessage(), Toast.LENGTH_SHORT).show(); } } break; // case Constants.PUSH_PAYLOAD_TYPE_EMERGENCY_CALL: break; // case Constants.PUSH_PAYLOAD_TYPE_INHABITANTS_POLL: // ? case Constants.PUSH_PAYLOAD_TYPE_COOPERATIVE_BUYING: int strId = Constants.PUSH_PAYLOAD_TYPE_INHABITANTS_POLL.equals(payloadData.getServiceType()) ? R.string.notification_inhabitant_push : R.string.notification_cooperative_buying_push; playNotificationAlarm(context, strId); pi = new Intent(); pi.setAction(action); pi.putExtra(PushConstants.EXTRA_PUSH_STATUS_VALUE, intent.getIntExtra( PushConstants.EXTRA_PUSH_STATUS_VALUE, PushConstants.PUSH_STATUS_VALUE_DISCONNECTED)); pi.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, payloadData); Log.d(TAG, "3. sendBroadcast() >> ACTION_PUSH_MESSAGE_RECEIVED : idx = " + 0); LocalBroadcastManager.getInstance(context).sendBroadcast(pi); break; // IOT DEVICE ( ) case Constants.PUSH_PAYLOAD_TYPE_IOT_DEVICE_CONTROL: Log.d(TAG, "startService >> ACTION_SEND_IOT_COMMAND"); IoTInterface.getInstance().controlDevice(payloadData.getIotControlDeviceId(), payloadData.getMessage()); break; // PUSH_PAYLOAD_TYPE_PUSH_NOTIFICATION case Constants.PUSH_PAYLOAD_TYPE_PUSH_NOTIFICATION: // ?... // pi = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(payloadData.getMessage())); // showNotification(context, Constants.SYSTEM_ADMIN_NOTIFICATION_ID, PackageUtils.getApplicationName(context), payloadData.getAlertMessage(), null, pi); // bigText showNotification(context, Constants.SYSTEM_ADMIN_NOTIFICATION_ID, PackageUtils.getApplicationName(context), payloadData.getAlertMessage(), PackageUtils.getApplicationName(context), payloadData.getMessage(), null, null, null); break; // IOT DEVICE ( ) case Constants.PUSH_PAYLOAD_TYPE_FIND_PASSWORD: pi = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(payloadData.getMessage())); showNotification(context, Constants.PW_FIND_NOTIFICATION_ID, PackageUtils.getApplicationName(context), payloadData.getAlertMessage(), null, pi); break; default: Log.d(TAG, "Unknown push payload type !!!"); break; } } }