List of usage examples for android.content Intent getSerializableExtra
public Serializable getSerializableExtra(String name)
From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case LOCATION_CONNECTION_FAILURE_RESOLUTION_REQUEST: // If the result code is Activity.RESULT_OK, try to connect again switch (resultCode) { case Activity.RESULT_OK: // Try the request again // TODO - check google developers documentation again // and implement it correctly }/*www. j a va2 s. c o m*/ break; case SEARCH_POI_ACTIVITY_RESULT: if (resultCode == Activity.RESULT_OK) { // search activity finished OK if (data == null) return; // PoisModel poi_to = (PoisModel) // data.getSerializableExtra("pmodel"); // startNavigationTask(poi_to); IPoisClass place = (IPoisClass) data.getSerializableExtra("ianyplace"); handleSearchPlaceSelection(place); } else if (resultCode == Activity.RESULT_CANCELED) { // CANCELLED if (data == null) return; String msg = (String) data.getSerializableExtra("message"); if (msg != null) Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show(); } break; case SELECT_PLACE_ACTIVITY_RESULT: if (resultCode == Activity.RESULT_OK) { if (data == null) return; String fpf = data.getStringExtra("floor_plan_path"); if (fpf == null) { Toast.makeText(getBaseContext(), "You haven't selected both building and floor...!", Toast.LENGTH_SHORT).show(); return; } try { BuildingModel b = mAnyplaceCache.getSpinnerBuildings().get(data.getIntExtra("bmodel", 0)); FloorModel f = b.getFloors().get(data.getIntExtra("fmodel", 0)); selectPlaceActivityResult(b, f); } catch (Exception ex) { Toast.makeText(getBaseContext(), "You haven't selected both building and floor...!", Toast.LENGTH_SHORT).show(); } } else if (resultCode == Activity.RESULT_CANCELED) { // CANCELLED if (data == null) return; String msg = (String) data.getSerializableExtra("message"); if (msg != null) Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show(); } break; case PREFERENCES_ACTIVITY_RESULT: if (resultCode == RESULT_OK) { AnyplacePrefs.Action result = (Action) data.getSerializableExtra("action"); switch (result) { case REFRESH_BUILDING: if (!userData.isFloorSelected()) { Toast.makeText(getBaseContext(), "Load a map before performing this action!", Toast.LENGTH_SHORT).show(); break; } if (progressBar.getVisibility() == View.VISIBLE) { Toast.makeText(getBaseContext(), "Building Loading in progress. Please Wait!", Toast.LENGTH_SHORT).show(); break; } try { final BuildingModel b = userData.getSelectedBuilding(); // clear_floorplans File floorsRoot = new File(AnyplaceUtils.getFloorPlansRootFolder(this), b.buid); // clear radiomaps File radiomapsRoot = AnyplaceUtils.getRadioMapsRootFolder(this); final String[] radiomaps = radiomapsRoot.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.startsWith(b.buid)) return true; else return false; } }); for (int i = 0; i < radiomaps.length; i++) { radiomaps[i] = radiomapsRoot.getAbsolutePath() + File.separator + radiomaps[i]; } floorSelector.Stop(); disableAnyplaceTracker(); DeleteFolderBackgroundTask task = new DeleteFolderBackgroundTask( new DeleteFolderBackgroundTask.DeleteFolderBackgroundTaskListener() { @Override public void onSuccess() { // clear any markers that might have already // been added to the map visiblePois.clearAll(); // clear and resets the cached POIS inside // AnyplaceCache mAnyplaceCache.setPois(new HashMap<String, PoisModel>(), ""); mAnyplaceCache.fetchAllFloorsRadiomapReset(); bypassSelectBuildingActivity(b, b.getSelectedFloor()); } }, UnifiedNavigationActivity.this, true); task.setFiles(floorsRoot); task.setFiles(radiomaps); task.execute(); } catch (Exception e) { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } break; } break; } }
From source file:org.appspot.apprtc.CallActivity.java
void handleIntent(Intent intent) { if (intent == null || intent.getAction() == null) { return;/*from ww w . j a va2 s. c om*/ } if (intent.hasExtra(WebsocketService.EXTRA_ADDRESS)) { mServer = intent.getStringExtra(WebsocketService.EXTRA_ADDRESS); } if (intent.getAction().equals(ACTION_SHARE_FILE)) { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); mFileRecipient = user.Id; Intent i; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { i = new Intent(); i.setAction(Intent.ACTION_GET_CONTENT); i.setType("*/*"); } else { i = new Intent(Intent.ACTION_OPEN_DOCUMENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); i.setType("*/*"); } startActivityForResult(i, FILE_CODE); } else if (intent.getAction().equals(ACTION_HANG_UP)) { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); if (mAdditionalPeers.containsKey(user.Id)) { mAdditionalPeers.get(user.Id).getRemoteViews().setId(""); updateRemoteViewList(mAdditionalPeers.get(user.Id).getRemoteViews()); mAdditionalPeers.get(user.Id).close(); mAdditionalPeers.remove(user.Id); } else if (mPeerId.equals(user.Id)) { onCallHangUp(); } } else if (intent.getAction().equals(ACTION_TOGGLE_VIDEO)) { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); boolean enabled = intent.getBooleanExtra(CallActivity.EXTRA_VIDEO_CALL, true); if (mAdditionalPeers.containsKey(user.Id)) { mAdditionalPeers.get(user.Id).setVideoEnabled(enabled); } else if (mPeerId.equals(user.Id)) { onToggleVideo(); } } else if (intent.getAction().equals(ACTION_TOGGLE_MIC)) { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); boolean enabled = intent.getBooleanExtra(CallActivity.EXTRA_MIC_ENABLED, true); if (mAdditionalPeers.containsKey(user.Id)) { mAdditionalPeers.get(user.Id).setAudioEnabled(enabled); } else if (mPeerId.equals(user.Id)) { onToggleMic(); } } else if (intent.getAction().equals(ACTION_SEND_MESSAGE)) { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); String messageText = intent.getStringExtra(CallActivity.EXTRA_MESSAGE); if (mService != null) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); String time = fmt.format(new Date()); mService.sendChatMessage(time, mService.getAccountName(), "Self", messageText, user.Id, mService.getCurrentRoomName()); } } else if (intent.getAction().equals(ACTION_NEW_CALL)) { String signaling = intent.getStringExtra(EXTRA_SIGNALING); if (signaling != null) { mSignaling = signaling; } if (mSignaling.equals("xmpp")) { mOwnJid = intent.getStringExtra(BroadcastTypes.EXTRA_ACCOUNT_JID); mPeerId = intent.getStringExtra(BroadcastTypes.EXTRA_JID); mPeerName = mPeerId; initiator = true; signalingParameters = new SignalingParameters(WebsocketService.getIceServers(), initiator, "", "", "", null, null); } else { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); if (intent.hasExtra(WebsocketService.EXTRA_USERACTION)) { if (mConferenceId == null) { SessionIdentifierGenerator gen = new SessionIdentifierGenerator(); mConferenceId = mOwnId + "_" + gen.nextSessionId(); } } if (mPeerId.length() == 0) { callUser(user); } else if (!mPeerId.equals(user.Id)) { // don't call if already in call AdditionalPeerConnection additionalPeerConnection = new AdditionalPeerConnection(this, this, this, true, user.Id, WebsocketService.getIceServers(), peerConnectionParameters, rootEglBase, localRender, getRemoteRenderScreen(user.Id, user.displayName, getUrl(user.buddyPicture)), peerConnectionClient.getMediaStream(), "", peerConnectionClient.getPeerConnectionFactory()); mAdditionalPeers.put(user.Id, additionalPeerConnection); updateVideoView(); } } } else if (intent.getAction().equals(WebsocketService.ACTION_ADD_ALL_CONFERENCE)) { ArrayList<User> users = getUsers(); for (User user : users) { boolean added = false; if (!mPeerId.equals(user.Id) && !mAdditionalPeers.containsKey(user.Id) && (mOwnId.compareTo(user.Id) < 0)) { AdditionalPeerConnection additionalPeerConnection = new AdditionalPeerConnection(this, this, this, true, user.Id, WebsocketService.getIceServers(), peerConnectionParameters, rootEglBase, localRender, getRemoteRenderScreen(user.Id, user.displayName, getUrl(user.buddyPicture)), peerConnectionClient.getMediaStream(), mConferenceId, peerConnectionClient.getPeerConnectionFactory()); mAdditionalPeers.put(user.Id, additionalPeerConnection); updateVideoView(); added = true; } } if (mConferenceId == null) { SessionIdentifierGenerator gen = new SessionIdentifierGenerator(); mConferenceId = mOwnId + "_" + gen.nextSessionId(); } } else if (intent.getAction().equals(WebsocketService.ACTION_ADD_CONFERENCE_USER)) { User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); String conferenceId = intent.getStringExtra(WebsocketService.EXTRA_CONFERENCE_ID); mOwnId = intent.getStringExtra(WebsocketService.EXTRA_OWN_ID); String userId = intent.getStringExtra(WebsocketService.EXTRA_ID); if (mConferenceId == null) { mConferenceId = conferenceId; } boolean added = false; if ((!mPeerId.equals(userId) && !mAdditionalPeers.containsKey(userId) && (mOwnId.compareTo(userId) < 0))) { if (user != null) { Log.d(TAG, "Calling conference: " + user.displayName); } if (peerConnectionClient.getMediaStream() != null) { String displayName = getString(R.string.unknown); String imgUrl = ""; if (user != null) { displayName = user.displayName; imgUrl = getUrl(user.buddyPicture); } AdditionalPeerConnection additionalPeerConnection = new AdditionalPeerConnection(this, this, this, true, userId, WebsocketService.getIceServers(), peerConnectionParameters, rootEglBase, localRender, getRemoteRenderScreen(userId, displayName, imgUrl), peerConnectionClient.getMediaStream(), mConferenceId, peerConnectionClient.getPeerConnectionFactory()); mAdditionalPeers.put(userId, additionalPeerConnection); updateVideoView(); added = true; } else if (mPeerId.length() == 0) { // show the call as incoming String displayName = getString(R.string.unknown); String imgUrl = ""; if (user != null) { displayName = user.displayName; imgUrl = getUrl(user.buddyPicture); } mPeerId = userId; mPeerName = displayName; ThumbnailsCacheManager.LoadImage(imgUrl, remoteUserImage, displayName, true, true); initiator = true; signalingParameters = new SignalingParameters(WebsocketService.getIceServers(), initiator, "", "", "", null, null); } else { mQueuedPeers.add(user); } } } else if (intent.getAction().equals(WebsocketService.ACTION_REMOTE_ICE_CANDIDATE)) { SerializableIceCandidate candidate = (SerializableIceCandidate) intent .getParcelableExtra(WebsocketService.EXTRA_CANDIDATE); String id = intent.getStringExtra(WebsocketService.EXTRA_ID); String token = intent.getStringExtra(WebsocketService.EXTRA_TOKEN); if (token != null && token.length() != 0) { if (mTokenPeers.containsKey(candidate.from)) { IceCandidate ic = new IceCandidate(candidate.sdpMid, candidate.sdpMLineIndex, candidate.sdp); mTokenPeers.get(candidate.from).addRemoteIceCandidate(ic); } } else if (mAdditionalPeers.containsKey(candidate.from)) { IceCandidate ic = new IceCandidate(candidate.sdpMid, candidate.sdpMLineIndex, candidate.sdp); mAdditionalPeers.get(candidate.from).addRemoteIceCandidate(ic); } else if (id.equals(mSdpId)) { onRemoteIceCandidate(candidate, id, candidate.from); } } else if (intent.getAction().equals(WebsocketService.ACTION_REMOTE_DESCRIPTION)) { SerializableSessionDescription sdp = (SerializableSessionDescription) intent .getSerializableExtra(WebsocketService.EXTRA_REMOTE_DESCRIPTION); String token = intent.getStringExtra(WebsocketService.EXTRA_TOKEN); String id = intent.getStringExtra(WebsocketService.EXTRA_ID); String conferenceId = intent.getStringExtra(WebsocketService.EXTRA_CONFERENCE_ID); String signaling = intent.getStringExtra(EXTRA_SIGNALING); String ownJid = intent.getStringExtra(BroadcastTypes.EXTRA_ACCOUNT_JID); mSid = intent.getStringExtra(BroadcastTypes.EXTRA_SID); User user = (User) intent.getSerializableExtra(WebsocketService.EXTRA_USER); if (mConferenceId == null && conferenceId != null && conferenceId.length() != 0) { mConferenceId = conferenceId; } /*else if (conferenceId != null && mConferenceId != null && !mConferenceId.equals(conferenceId)) { // already in a conference, reject the invite return; }*/ if (ownJid != null) { mOwnJid = ownJid; } if (signaling != null && signaling.equals("xmpp")) { mSignaling = signaling; } if (token != null && token.length() != 0) { if (mTokenPeers.containsKey(sdp.from)) { mTokenPeers.get(sdp.from) .setRemoteDescription(new SessionDescription(sdp.type, sdp.description)); } } else if (mPeerId.length() == 0 || mPeerId.equals(sdp.from)) { mSdpId = id; mPeerId = sdp.from; String imgUrl = ""; if (user != null) { mPeerName = user.displayName; imgUrl = getUrl(user.buddyPicture); } else { mPeerName = getString(R.string.unknown); } ThumbnailsCacheManager.LoadImage(imgUrl, remoteUserImage, mPeerName, true, true); if (peerConnectionClient.isConnected()) { onRemoteDescription(sdp, token, id, conferenceId, "", "", ""); } else { mRemoteSdp = sdp; mToken = token; } } else { if (mAdditionalPeers.containsKey(sdp.from)) { mAdditionalPeers.get(sdp.from) .setRemoteDescription(new SessionDescription(sdp.type, sdp.description)); } else { if (iceConnected && peerConnectionClient.getMediaStream() != null) { addToCall(sdp, user); } else { mQueuedRemoteConnections.add(new RemoteConnection(sdp, user)); } } } } }
From source file:org.appspot.apprtc.CallActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler(this)); // Set window styles for fullscreen-window size. Needs to be done before // adding content. requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD | LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_TURN_SCREEN_ON); getWindow().getDecorView()/*from www . j a va 2 s .c o m*/ .setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); setContentView(R.layout.activity_call); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WebsocketService.ACTION_BYE); mIntentFilter.addAction(WebsocketService.ACTION_USER_ENTERED); mIntentFilter.addAction(WebsocketService.ACTION_USER_LEFT); mIntentFilter.addAction(WebsocketService.ACTION_SCREENSHARE); mIntentFilter.addAction(CustomPhoneStateListener.ACTION_HOLD_ON); mIntentFilter.addAction(CustomPhoneStateListener.ACTION_HOLD_OFF); mIntentFilter.addAction(WebsocketService.ACTION_CHAT_MESSAGE); mIntentFilter.addAction(WebsocketService.ACTION_FILE_MESSAGE); registerReceiver(mReceiver, mIntentFilter); // Get setting keys. PreferenceManager.setDefaultValues(this, R.xml.webrtc_preferences, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); keyprefVideoCallEnabled = getString(R.string.pref_videocall_key); keyprefScreencapture = getString(R.string.pref_screencapture_key); keyprefCamera2 = getString(R.string.pref_camera2_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_maxvideobitrate_key); keyprefVideoBitrateValue = getString(R.string.pref_maxvideobitratevalue_key); keyprefVideoCodec = getString(R.string.pref_videocodec_key); keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key); keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key); keyprefFlexfec = getString(R.string.pref_flexfec_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); keyprefDisableBuiltInAec = getString(R.string.pref_disable_built_in_aec_key); keyprefDisableBuiltInAgc = getString(R.string.pref_disable_built_in_agc_key); keyprefDisableBuiltInNs = getString(R.string.pref_disable_built_in_ns_key); keyprefEnableLevelControl = getString(R.string.pref_enable_level_control_key); keyprefDisplayHud = getString(R.string.pref_displayhud_key); keyprefTracing = getString(R.string.pref_tracing_key); keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key); keyprefEnableDataChannel = getString(R.string.pref_enable_datachannel_key); keyprefOrdered = getString(R.string.pref_ordered_key); keyprefMaxRetransmitTimeMs = getString(R.string.pref_max_retransmit_time_ms_key); keyprefMaxRetransmits = getString(R.string.pref_max_retransmits_key); keyprefDataProtocol = getString(R.string.pref_data_protocol_key); keyprefNegotiated = getString(R.string.pref_negotiated_key); keyprefDataId = getString(R.string.pref_data_id_key); readPrefs(); final Intent intent = getIntent(); if (intent.getAction().equals(WebsocketService.ACTION_REMOTE_ICE_CANDIDATE)) { finish(); // don't start the activity on this intent } else if (intent.getAction().equals(WebsocketService.ACTION_REMOTE_DESCRIPTION)) { SerializableSessionDescription sdp = (SerializableSessionDescription) intent .getSerializableExtra(WebsocketService.EXTRA_REMOTE_DESCRIPTION); mVideoCallEnabled = sdp.description.contains("m=video"); } iceConnected = false; signalingParameters = new SignalingParameters(WebsocketService.getIceServers(), initiator, "", "", "", null, null); scalingType = ScalingType.SCALE_ASPECT_FILL; // Create UI controls. localRender = (SurfaceViewRenderer) findViewById(R.id.local_video_view); screenshareRender = (SurfaceViewRenderer) findViewById(R.id.screenshare_video_view); remoteRenderScreen = (SurfaceViewRenderer) findViewById(R.id.remote_video_view); remoteRenderScreen2 = (SurfaceViewRenderer) findViewById(R.id.remote_video_view2); remoteRenderScreen3 = (SurfaceViewRenderer) findViewById(R.id.remote_video_view3); remoteRenderScreen4 = (SurfaceViewRenderer) findViewById(R.id.remote_video_view4); remoteVideoLabel = (TextView) findViewById(R.id.remote_video_label); remoteVideoLabel2 = (TextView) findViewById(R.id.remote_video_label2); remoteVideoLabel3 = (TextView) findViewById(R.id.remote_video_label3); remoteVideoLabel4 = (TextView) findViewById(R.id.remote_video_label4); remoteUserImage = (ImageView) findViewById(R.id.remote_user_image1); remoteUserImage2 = (ImageView) findViewById(R.id.remote_user_image2); remoteUserImage3 = (ImageView) findViewById(R.id.remote_user_image3); remoteUserImage4 = (ImageView) findViewById(R.id.remote_user_image4); remoteUserHoldStatus = (ImageView) findViewById(R.id.remote_user_hold_status); remoteUserHoldStatus2 = (ImageView) findViewById(R.id.remote_user_hold_status2); remoteUserHoldStatus3 = (ImageView) findViewById(R.id.remote_user_hold_status3); remoteUserHoldStatus4 = (ImageView) findViewById(R.id.remote_user_hold_status4); localRenderLayout = (PercentFrameLayout) findViewById(R.id.local_video_layout); screenshareRenderLayout = (PercentFrameLayout) findViewById(R.id.screenshare_video_layout); remoteRenderLayout = (PercentFrameLayout) findViewById(R.id.remote_video_layout); remoteRenderLayout2 = (PercentFrameLayout) findViewById(R.id.remote_video_layout2); remoteRenderLayout3 = (PercentFrameLayout) findViewById(R.id.remote_video_layout3); remoteRenderLayout4 = (PercentFrameLayout) findViewById(R.id.remote_video_layout4); initiateCallFragment = new InitiateCallFragment(); callListFragment = new CallListFragment(); callFragment = new CallFragment(); hudFragment = new HudFragment(); chatFragment = new ChatFragment(); screenshareRemoteView = new RemoteConnectionViews("screenshare", screenshareRenderLayout, screenshareRender, null, null, null); remoteViewsInUseList.add(new RemoteConnectionViews("remote 1", remoteRenderLayout, remoteRenderScreen, remoteUserImage, remoteVideoLabel, remoteUserHoldStatus)); // first one is always in use remoteViewsList.add(new RemoteConnectionViews("remote 2", remoteRenderLayout2, remoteRenderScreen2, remoteUserImage2, remoteVideoLabel2, remoteUserHoldStatus2)); remoteViewsList.add(new RemoteConnectionViews("remote 3", remoteRenderLayout3, remoteRenderScreen3, remoteUserImage3, remoteVideoLabel3, remoteUserHoldStatus3)); remoteViewsList.add(new RemoteConnectionViews("remote 4", remoteRenderLayout4, remoteRenderScreen4, remoteUserImage4, remoteVideoLabel4, remoteUserHoldStatus4)); // Show/hide call control fragment on view click. View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { toggleCallControlFragmentVisibility(); } }; View.OnClickListener screenshareListener = new View.OnClickListener() { @Override public void onClick(View view) { maximizeScreenshare = !maximizeScreenshare; updateVideoView(); } }; localRender.setOnClickListener(listener); screenshareRender.setOnClickListener(screenshareListener); remoteRenderScreen.setOnClickListener(listener); remoteRenderScreen2.setOnClickListener(listener); remoteRenderScreen3.setOnClickListener(listener); remoteRenderScreen4.setOnClickListener(listener); remoteRenderers.add(remoteRenderScreen); // Create video renderers. if (rootEglBase == null) { rootEglBase = EglBase.create(); } localRender.init(rootEglBase.getEglBaseContext(), null); screenshareRender.init(rootEglBase.getEglBaseContext(), null); String saveRemoteVideoToFile = intent.getStringExtra(EXTRA_SAVE_REMOTE_VIDEO_TO_FILE); // When saveRemoteVideoToFile is set we save the video from the remote to a file. if (saveRemoteVideoToFile != null) { int videoOutWidth = intent.getIntExtra(EXTRA_SAVE_REMOTE_VIDEO_TO_FILE_WIDTH, 0); int videoOutHeight = intent.getIntExtra(EXTRA_SAVE_REMOTE_VIDEO_TO_FILE_HEIGHT, 0); try { videoFileRenderer = new VideoFileRenderer(saveRemoteVideoToFile, videoOutWidth, videoOutHeight, rootEglBase.getEglBaseContext()); remoteRenderers.add(videoFileRenderer); } catch (IOException e) { throw new RuntimeException("Failed to open video file for output: " + saveRemoteVideoToFile, e); } } remoteRenderScreen.init(rootEglBase.getEglBaseContext(), null); remoteRenderScreen2.init(rootEglBase.getEglBaseContext(), null); remoteRenderScreen3.init(rootEglBase.getEglBaseContext(), null); remoteRenderScreen4.init(rootEglBase.getEglBaseContext(), null); localRender.setZOrderMediaOverlay(true); localRender.setEnableHardwareScaler(true /* enabled */); screenshareRender.getHolder().setFormat(PixelFormat.TRANSLUCENT); screenshareRenderLayout.setVisibility(View.GONE); screenshareRender.setVisibility(View.GONE); if (intent.getAction().equals(ACTION_RESUME_CALL)) { iceConnected = true; } updateVideoView(); // If capturing format is not specified for screencapture, use screen resolution. if (screencaptureEnabled && mVideoWidth == 0 && mVideoHeight == 0) { DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { windowManager.getDefaultDisplay().getRealMetrics(displayMetrics); } mVideoWidth = displayMetrics.widthPixels; mVideoHeight = displayMetrics.heightPixels; } DataChannelParameters dataChannelParameters = null; if (mDataChannelEnabled) { dataChannelParameters = new DataChannelParameters(mOrdered, mMaxRetrMs, mMaxRetr, mProtocol, mNegotiated, mId); } peerConnectionParameters = new PeerConnectionParameters(mVideoCallEnabled, false, false, mVideoWidth, mVideoHeight, mCameraFps, mVideoStartBitrate, mVideoCodec, mHwCodecEnabled, mFlexfecEnabled, mAudioStartBitrate, mAudioCodec, mNoAudioProcessing, mAecDump, mUseOpenSLES, mDisableBuiltInAEC, mDisableBuiltInAGC, mDisableBuiltInNS, mEnableLevelControl, dataChannelParameters); commandLineRun = intent.getBooleanExtra(EXTRA_CMDLINE, false); runTimeMs = intent.getIntExtra(EXTRA_RUNTIME, 0); Log.d(TAG, "VIDEO_FILE: '" + intent.getStringExtra(EXTRA_VIDEO_FILE_AS_CAMERA) + "'"); // Create connection client. Use DirectRTCClient if room name is an IP otherwise use the // standard WebSocketRTCClient. //if (loopback || !DirectRTCClient.IP_PATTERN.matcher(roomId).matches()) { // appRtcClient = new WebSocketRTCClient(this); // } else { // Log.i(TAG, "Using DirectRTCClient because room name looks like an IP."); // appRtcClient = new DirectRTCClient(this); // } // Create connection parameters. //roomConnectionParameters = new RoomConnectionParameters(roomUri.toString(), roomId, loopback); // Create CPU monitor //cpuMonitor = new CpuMonitor(this); //hudFragment.setCpuMonitor(cpuMonitor); Bundle extras = intent.getExtras(); extras.putBoolean(CallActivity.EXTRA_VIDEO_CALL, mVideoCallEnabled); // Send intent arguments to fragments. chatFragment.setArguments(getIntent().getExtras()); initiateCallFragment.setArguments(extras); callFragment.setArguments(extras); callListFragment.setArguments(extras); hudFragment.setArguments(intent.getExtras()); // Activate call and HUD fragments and start the call. remoteUserImage.setVisibility(View.INVISIBLE); FragmentTransaction ft = getFragmentManager().beginTransaction(); if (intent.getAction().equals(ACTION_RESUME_CALL)) { ft.add(R.id.call_fragment_container, callFragment); } else { ft.add(R.id.call_fragment_container, initiateCallFragment); } ft.add(R.id.hud_fragment_container, hudFragment); ft.commit(); // For command line execution run connection for <runTimeMs> and exit. if (commandLineRun && runTimeMs > 0) { (new Handler()).postDelayed(new Runnable() { @Override public void run() { disconnect(); } }, runTimeMs); } if (!intent.getAction().equals(ACTION_RESUME_CALL)) { peerConnectionClient = PeerConnectionClient.getInstance(); PeerConnectionFactory.Options options = new PeerConnectionFactory.Options(); options.disableNetworkMonitor = true; peerConnectionClient.setPeerConnectionFactoryOptions(options); if (mForceTurn) { peerConnectionParameters.forceTurn = true; } peerConnectionClient.createPeerConnectionFactory(CallActivity.this, peerConnectionParameters, CallActivity.this); peerConnectionClient.setDataChannelCallback(this); ThumbnailsCacheManager.ThumbnailsCacheManagerInit(this); handleIntent(intent); if (screencaptureEnabled) { /*MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService( Context.MEDIA_PROJECTION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { startActivityForResult( mediaProjectionManager.createScreenCaptureIntent(), CAPTURE_PERMISSION_REQUEST_CODE); }*/ } else { startCall(); } } else { mPeerId = intent.getStringExtra(EXTRA_PEER_ID); iceConnected = true; if (peerConnectionClient != null) { peerConnectionClient.updateActivity(this, this); peerConnectionClient.updateLocalRenderer(localRender); peerConnectionClient.updateRemoteRenderers(remoteRenderers); } } AddRunningIntent(); }
From source file:com.kaichaohulian.baocms.ecdemo.ui.chatting.ChattingFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); LogUtil.d(TAG,//w w w . java 2 s . c om "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data); // If there's no data (because the user didn't select a picture and // just hit BACK, for example), there's nothing to do. if (requestCode == 111 && resultCode == 111) { ContactFriendsEntity data1 = (ContactFriendsEntity) data.getSerializableExtra("data"); handleSendIDCardMessage(data1.getUsername(), data1.getAvatar(), data1.getId() + "", data1.getId()); } if (requestCode == 0x2a || requestCode == SELECT_AT_SOMONE) { if (data == null) { return; } } else if (resultCode != ChattingActivity.RESULT_OK) { LogUtil.d("onActivityResult: bail due to resultCode=" + resultCode); isFireMsg = false; return; } if (data != null && 0x2a == requestCode) { handleAttachUrl(data.getStringExtra("choosed_file_path")); return; } if (requestCode == REQUEST_CODE_TAKE_PICTURE || requestCode == REQUEST_CODE_LOAD_IMAGE) { if (requestCode == REQUEST_CODE_LOAD_IMAGE) { ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT); if (result != null && !result.isEmpty()) { mFilePath = result.get(0); } else { mFilePath = DemoUtils.resolvePhotoFromIntent(this.getActivity(), data, FileAccessor.IMESSAGE_IMAGE); } } if (TextUtils.isEmpty(mFilePath)) { return; } File file = new File(mFilePath); if (file == null || !file.exists()) { return; } try { ECPreferences.savePreference(ECPreferenceSettings.SETTINGS_CROPIMAGE_OUTPUTPATH, file.getAbsolutePath(), true); Intent intent = new Intent(getChattingActivity(), ImagePreviewActivity.class); getActivity().startActivityForResult(intent, REQUEST_CODE_IMAGE_CROP); } catch (Exception e1) { e1.printStackTrace(); } return; } if (requestCode == REQUEST_VIEW_CARD && data != null) { boolean exit = data.getBooleanExtra(GroupInfoActivity.EXTRA_QUEIT, false); if (exit) { finish(); return; } boolean reload = data.getBooleanExtra(GroupInfoActivity.EXTRA_RELOAD, false); if (reload) { mThread = mChattingAdapter.setUsername(mRecipients); queryUIMessage(); } } if (requestCode == SELECT_AT_SOMONE) { String selectUser = data.getStringExtra(AtSomeoneUI.EXTRA_SELECT_CONV_USER); if (TextUtils.isEmpty(selectUser)) { mChattingFooter.setAtSomebody(""); LogUtil.d(TAG, "@ [nobody]"); return; } LogUtil.d(TAG, "@ " + selectUser); ECContacts contact = ContactSqlManager.getContact(selectUser); if (contact == null) { return; } if (TextUtils.isEmpty(contact.getNickname())) { contact.setNickname(contact.getContactid()); } mChattingFooter.setAtSomebody(contact.getNickname()); mChattingFooter.putSomebody(contact); postSetAtSome(); return; } if (requestCode == GlobalConstant.ACTIVITY_FOR_RESULT_VIDEORECORD) { handleVideoRecordSend(data); } if (requestCode == REQUEST_CODE_TAKE_LOCATION) { locationInfo = (LocationInfo) data.getSerializableExtra("location"); handleSendLocationMessage(locationInfo); } if (requestCode == REQUEST_CODE_REDPACKET) { if (data != null) { handlesendRedPacketMessage(data); } } }
From source file:com.ferid.app.frequentcontacts.MainActivity.java
/** * After photo process return//from w ww . j a v a 2 s .c o m */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE) { //a photo picked from the gallery if (resultCode == RESULT_OK) { try { Uri photoUri = data.getData(); InputStream is = this.getContentResolver().openInputStream(photoUri); BitmapFactory.Options dbo = new BitmapFactory.Options(); dbo.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, dbo); if (is != null) is.close(); int rotatedWidth, rotatedHeight; int orientation = getOrientation(this, photoUri); if (orientation == 90 || orientation == 270) { rotatedWidth = dbo.outHeight; rotatedHeight = dbo.outWidth; } else { rotatedWidth = dbo.outWidth; rotatedHeight = dbo.outHeight; } Bitmap srcBitmap; is = this.getContentResolver().openInputStream(photoUri); int MAX_IMAGE_HEIGHT = 250; int MAX_IMAGE_WIDTH = 250; if (rotatedWidth > MAX_IMAGE_WIDTH || rotatedHeight > MAX_IMAGE_HEIGHT) { float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_WIDTH); float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_HEIGHT); float maxRatio = Math.max(widthRatio, heightRatio); // Create the bitmap from file BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = (int) maxRatio; srcBitmap = BitmapFactory.decodeStream(is, null, options); } else { srcBitmap = BitmapFactory.decodeStream(is); } if (is != null) is.close(); //if the orientation is not 0 (or -1, which means we don't know), we have to do a rotation. if (orientation > 0) { Matrix matrix = new Matrix(); matrix.postRotate(orientation); srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); } //srcBitmap is ready now ByteArrayOutputStream stream = new ByteArrayOutputStream(); srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] byteArray = stream.toByteArray(); // byte[] to String convert. String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT); //anti-memory leak srcBitmap.recycle(); //ready to set photo contact.setPhoto(encodedImage); save_refresh(); } catch (IOException e) { e.printStackTrace(); } } } else if (requestCode == SELECT_NUMBER) { //a contact selected from the list if (resultCode == RESULT_OK) { try { Contact contact = (Contact) data.getSerializableExtra("contact"); if (contact != null) { contactsList.add(contact); save_refresh(); } } catch (Exception e) { e.printStackTrace(); } } } }
From source file:it.geosolutions.geocollect.android.map.GeoCollectMapActivity.java
/** * Opena the Data List activity//from w w w . j a v a 2 s. c o m * * @param item * @return */ /* * (non-Javadoc) * * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent incomingIntent) { super.onActivityResult(requestCode, resultCode, incomingIntent); Log.d(TAG, "onActivityResult"); if (requestCode == LoginActivity.REQUEST_LOGIN) { if (resultCode == RESULT_CANCELED) { // user cancelled to enter credentials Toast.makeText(getBaseContext(), getString(R.string.login_canceled), Toast.LENGTH_LONG).show(); finish(); return; } } if (requestCode == LogoutActivity.REQUEST_LOGOUT) { if (resultCode == LogoutActivity.LOGGED_OUT) { // there is a notification in LogoutActivity already startActivityForResult(new Intent(this, LoginActivity.class), LoginActivity.REQUEST_LOGIN); return; } } if (requestCode == LayerSwitcherFragment.OPACITY_SETTIN_REQUEST_ID) { final int newValue = PreferenceManager.getDefaultSharedPreferences(getBaseContext()) .getInt(MBTilesLayerOpacitySettingActivity.MBTILES_OPACITY_ID, 192); ArrayList<Layer> layers = layerManager.getLayers(); for (Layer l : layers) { if (l instanceof MbTilesLayer) { l.setOpacity(newValue); layerManager.redrawLayer(l); } } // its not necessary to handle the other stuff return; } if (requestCode == GetFeatureInfoLayerListActivity.BBOX_REQUEST && resultCode == RESULT_OK) { // the response can contain a feature to use to replace the current marker // on the map manageMarkerSubstitutionAction(incomingIntent); } // controls can be refreshed getting the result of an intent, in this case // each control knows which intent he sent with their requestCode/resultCode for (MapControl control : mapView.getControls()) { control.refreshControl(requestCode, resultCode, incomingIntent); } // reload stores in the panel (we do it everyTime, maybe there is a better way SourcesFragment sf = (SourcesFragment) getSupportFragmentManager().findFragmentById(R.id.right_drawer); if (sf != null) { sf.reloadStores(); } // manager mapstore configuration load if (incomingIntent == null) { return; } Bundle b = incomingIntent.getExtras(); if (requestCode == MapsActivity.DATAPROPERTIES_REQUEST_CODE) { mapView.getOverlayController().redrawOverlays(); // close right drawer if (mLayerMenu != null) { if (mDrawerLayout.isDrawerOpen(mLayerMenu)) { mDrawerLayout.closeDrawer(mLayerMenu); } } } Resource resource = (Resource) incomingIntent .getSerializableExtra(GeoStoreResourceDetailActivity.PARAMS.RESOURCE); if (resource != null) { String geoStoreUrl = incomingIntent.getStringExtra(GeoStoreResourcesActivity.PARAMS.GEOSTORE_URL); loadGeoStoreResource(resource, geoStoreUrl); } if (b.containsKey(MapsActivity.MAPSTORE_CONFIG)) { overlayManager .loadMapStoreConfig((MapStoreConfiguration) b.getSerializable(MapsActivity.MAPSTORE_CONFIG)); } if (b.containsKey(MapsActivity.MSM_MAP)) { layerManager.loadMap((MSMMap) b.getSerializable(MapsActivity.MSM_MAP)); } ArrayList<Layer> layersToAdd = (ArrayList<Layer>) b.getSerializable(MapsActivity.LAYERS_TO_ADD); if (layersToAdd != null) { addLayers(layersToAdd); } }
From source file:im.vector.activity.VectorHomeActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vector_home); if (CommonActivityUtils.shouldRestartApp(this)) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); return;//from w w w . jav a2s . com } if (CommonActivityUtils.isGoingToSplash(this)) { Log.d(LOG_TAG, "onCreate : Going to splash screen"); return; } sharedInstance = this; mWaitingView = findViewById(R.id.listView_spinner_views); mVectorPendingCallView = (VectorPendingCallView) findViewById(R.id.listView_pending_callview); mVectorPendingCallView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IMXCall call = VectorCallViewActivity.getActiveCall(); if (null != call) { final Intent intent = new Intent(VectorHomeActivity.this, VectorCallViewActivity.class); intent.putExtra(VectorCallViewActivity.EXTRA_MATRIX_ID, call.getSession().getCredentials().userId); intent.putExtra(VectorCallViewActivity.EXTRA_CALL_ID, call.getCallId()); VectorHomeActivity.this.runOnUiThread(new Runnable() { @Override public void run() { VectorHomeActivity.this.startActivity(intent); } }); } } }); // use a toolbar instead of the actionbar mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.home_toolbar); this.setSupportActionBar(mToolbar); mToolbar.setTitle(R.string.title_activity_home); this.setTitle(R.string.title_activity_home); mRoomCreationFab = (FloatingActionButton) findViewById(R.id.listView_create_room_view); mRoomCreationFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ignore any action if there is a pending one if (View.VISIBLE != mWaitingView.getVisibility()) { Context context = VectorHomeActivity.this; AlertDialog.Builder dialog = new AlertDialog.Builder(context); CharSequence items[] = new CharSequence[] { context.getString(R.string.room_recents_start_chat), context.getString(R.string.room_recents_create_room) }; dialog.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int n) { d.cancel(); if (0 == n) { invitePeopleToNewRoom(); } else { createRoom(); } } }); dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { invitePeopleToNewRoom(); } }); dialog.setNegativeButton(R.string.cancel, null); dialog.show(); } } }); mSession = Matrix.getInstance(this).getDefaultSession(); // process intent parameters final Intent intent = getIntent(); if (intent.hasExtra(EXTRA_CALL_SESSION_ID) && intent.hasExtra(EXTRA_CALL_ID)) { startCall(intent.getStringExtra(EXTRA_CALL_SESSION_ID), intent.getStringExtra(EXTRA_CALL_ID)); } // the activity could be started with a spinner // because there is a pending action (like universalLink processing) if (intent.getBooleanExtra(EXTRA_WAITING_VIEW_STATUS, VectorHomeActivity.WAITING_VIEW_STOP)) { showWaitingView(); } else { stopWaitingView(); } mAutomaticallyOpenedRoomParams = (Map<String, Object>) intent .getSerializableExtra(EXTRA_JUMP_TO_ROOM_PARAMS); mUniversalLinkToOpen = intent.getParcelableExtra(EXTRA_JUMP_TO_UNIVERSAL_LINK); // the home activity has been launched with an universal link if (intent.hasExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI)) { Log.d(LOG_TAG, "Has an universal link"); final Uri uri = intent.getParcelableExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI); intent.removeExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI); // detect the room could be opened without waiting the next sync HashMap<String, String> params = VectorUniversalLinkReceiver.parseUniversalLink(uri); if ((null != params) && params.containsKey(VectorUniversalLinkReceiver.ULINK_ROOM_ID_KEY)) { Log.d(LOG_TAG, "Has a valid universal link"); final String roomIdOrAlias = params.get(VectorUniversalLinkReceiver.ULINK_ROOM_ID_KEY); // it is a room ID ? if (roomIdOrAlias.startsWith("!")) { Log.d(LOG_TAG, "Has a valid universal link to the room ID " + roomIdOrAlias); Room room = mSession.getDataHandler().getRoom(roomIdOrAlias, false); if (null != room) { Log.d(LOG_TAG, "Has a valid universal link to a known room"); // open the room asap mUniversalLinkToOpen = uri; } else { Log.d(LOG_TAG, "Has a valid universal link but the room is not yet known"); // wait the next sync intent.putExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI, uri); } } else { Log.d(LOG_TAG, "Has a valid universal link of the room Alias " + roomIdOrAlias); // it is a room alias // convert the room alias to room Id mSession.getDataHandler().roomIdByAlias(roomIdOrAlias, new SimpleApiCallback<String>() { @Override public void onSuccess(String roomId) { Log.d(LOG_TAG, "Retrieve the room ID " + roomId); getIntent().putExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI, uri); // the room exists, opens it if (null != mSession.getDataHandler().getRoom(roomId, false)) { Log.d(LOG_TAG, "Find the room from room ID : process it"); processIntentUniversalLink(); } else { Log.d(LOG_TAG, "Don't know the room"); } } }); } } } else { Log.d(LOG_TAG, "create with no universal link"); } if (intent.hasExtra(EXTRA_SHARED_INTENT_PARAMS)) { final Intent sharedFilesIntent = intent.getParcelableExtra(EXTRA_SHARED_INTENT_PARAMS); if (mSession.getDataHandler().getStore().isReady()) { this.runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.sendFilesTo(VectorHomeActivity.this, sharedFilesIntent); } }); } else { mSharedFilesIntent = sharedFilesIntent; } // ensure that it should be called once intent.removeExtra(EXTRA_SHARED_INTENT_PARAMS); } // check if there is some valid session // the home activity could be relaunched after an application crash // so, reload the sessions before displaying the history Collection<MXSession> sessions = Matrix.getMXSessions(VectorHomeActivity.this); if (sessions.size() == 0) { Log.e(LOG_TAG, "Weird : onCreate : no session"); if (null != Matrix.getInstance(this).getDefaultSession()) { Log.e(LOG_TAG, "No loaded session : reload them"); // start splash activity and stop here startActivity(new Intent(VectorHomeActivity.this, SplashActivity.class)); VectorHomeActivity.this.finish(); return; } } FragmentManager fm = getSupportFragmentManager(); mRecentsListFragment = (VectorRecentsListFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECENTS_LIST); if (mRecentsListFragment == null) { // this fragment displays messages and handles all message logic //String matrixId, int layoutResId) mRecentsListFragment = VectorRecentsListFragment.newInstance(mSession.getCredentials().userId, R.layout.fragment_vector_recents_list); fm.beginTransaction() .add(R.id.home_recents_list_anchor, mRecentsListFragment, TAG_FRAGMENT_RECENTS_LIST).commit(); } // clear the notification if they are not anymore valid // i.e the event has been read from another client // or deleted it // + other actions which require a background listener mLiveEventListener = new MXEventListener() { @Override public void onLiveEventsChunkProcessed() { // treat any pending URL link workflow, that was started previously processIntentUniversalLink(); if (mClearCacheRequired) { mClearCacheRequired = false; Matrix.getInstance(VectorHomeActivity.this).reloadSessions(VectorHomeActivity.this); } } @Override public void onStoreReady() { if (null != mSharedFilesIntent) { VectorHomeActivity.this.runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.sendFilesTo(VectorHomeActivity.this, mSharedFilesIntent); mSharedFilesIntent = null; } }); } } }; mSession.getDataHandler().addListener(mLiveEventListener); // initialize the public rooms list PublicRoomsManager.setSession(mSession); PublicRoomsManager.refresh(null); }
From source file:im.neon.activity.VectorHomeActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vector_home); if (CommonActivityUtils.shouldRestartApp(this)) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); return;// ww w . j ava2 s .co m } if (CommonActivityUtils.isGoingToSplash(this)) { Log.d(LOG_TAG, "onCreate : Going to splash screen"); return; } sharedInstance = this; mWaitingView = findViewById(R.id.listView_spinner_views); mVectorPendingCallView = (VectorPendingCallView) findViewById(R.id.listView_pending_callview); mSyncInProgressView = findViewById(R.id.home_recents_sync_in_progress); mVectorPendingCallView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IMXCall call = VectorCallViewActivity.getActiveCall(); if (null != call) { final Intent intent = new Intent(VectorHomeActivity.this, VectorCallViewActivity.class); intent.putExtra(VectorCallViewActivity.EXTRA_MATRIX_ID, call.getSession().getCredentials().userId); intent.putExtra(VectorCallViewActivity.EXTRA_CALL_ID, call.getCallId()); VectorHomeActivity.this.runOnUiThread(new Runnable() { @Override public void run() { VectorHomeActivity.this.startActivity(intent); } }); } } }); // use a toolbar instead of the actionbar mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.home_toolbar); this.setSupportActionBar(mToolbar); mToolbar.setTitle(R.string.title_activity_home); this.setTitle(R.string.title_activity_home); mRoomCreationFab = (FloatingActionButton) findViewById(R.id.listView_create_room_view); mRoomCreationFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ignore any action if there is a pending one if (View.VISIBLE != mWaitingView.getVisibility()) { Context context = VectorHomeActivity.this; AlertDialog.Builder dialog = new AlertDialog.Builder(context); CharSequence items[] = new CharSequence[] { context.getString(R.string.room_recents_start_chat), context.getString(R.string.room_recents_create_room) }; dialog.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int n) { d.cancel(); if (0 == n) { invitePeopleToNewRoom(); } else { createRoom(); } } }); dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { invitePeopleToNewRoom(); } }); dialog.setNegativeButton(R.string.cancel, null); dialog.show(); } } }); mSession = Matrix.getInstance(this).getDefaultSession(); // track if the application update SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int version = preferences.getInt("VERSION_BUILD", 0); if (version != VectorApp.VERSION_BUILD) { Log.d(LOG_TAG, "The application has been updated from version " + version + " to version " + VectorApp.VERSION_BUILD); // TODO add some dedicated actions here SharedPreferences.Editor editor = preferences.edit(); editor.putInt("VERSION_BUILD", VectorApp.VERSION_BUILD); editor.commit(); } // process intent parameters final Intent intent = getIntent(); if (intent.hasExtra(EXTRA_CALL_SESSION_ID) && intent.hasExtra(EXTRA_CALL_ID)) { startCall(intent.getStringExtra(EXTRA_CALL_SESSION_ID), intent.getStringExtra(EXTRA_CALL_ID), (MXUsersDevicesMap<MXDeviceInfo>) intent.getSerializableExtra(EXTRA_CALL_UNKNOWN_DEVICES)); intent.removeExtra(EXTRA_CALL_SESSION_ID); intent.removeExtra(EXTRA_CALL_ID); intent.removeExtra(EXTRA_CALL_UNKNOWN_DEVICES); } // the activity could be started with a spinner // because there is a pending action (like universalLink processing) if (intent.getBooleanExtra(EXTRA_WAITING_VIEW_STATUS, WAITING_VIEW_STOP)) { showWaitingView(); } else { stopWaitingView(); } intent.removeExtra(EXTRA_WAITING_VIEW_STATUS); mAutomaticallyOpenedRoomParams = (Map<String, Object>) intent .getSerializableExtra(EXTRA_JUMP_TO_ROOM_PARAMS); intent.removeExtra(EXTRA_JUMP_TO_ROOM_PARAMS); mUniversalLinkToOpen = intent.getParcelableExtra(EXTRA_JUMP_TO_UNIVERSAL_LINK); intent.removeExtra(EXTRA_JUMP_TO_UNIVERSAL_LINK); mMemberIdToOpen = intent.getStringExtra(EXTRA_MEMBER_ID); intent.removeExtra(EXTRA_MEMBER_ID); // the home activity has been launched with an universal link if (intent.hasExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI)) { Log.d(LOG_TAG, "Has an universal link"); final Uri uri = intent.getParcelableExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI); intent.removeExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI); // detect the room could be opened without waiting the next sync HashMap<String, String> params = VectorUniversalLinkReceiver.parseUniversalLink(uri); if ((null != params) && params.containsKey(VectorUniversalLinkReceiver.ULINK_ROOM_ID_OR_ALIAS_KEY)) { Log.d(LOG_TAG, "Has a valid universal link"); final String roomIdOrAlias = params.get(VectorUniversalLinkReceiver.ULINK_ROOM_ID_OR_ALIAS_KEY); // it is a room ID ? if (MXSession.isRoomId(roomIdOrAlias)) { Log.d(LOG_TAG, "Has a valid universal link to the room ID " + roomIdOrAlias); Room room = mSession.getDataHandler().getRoom(roomIdOrAlias, false); if (null != room) { Log.d(LOG_TAG, "Has a valid universal link to a known room"); // open the room asap mUniversalLinkToOpen = uri; } else { Log.d(LOG_TAG, "Has a valid universal link but the room is not yet known"); // wait the next sync intent.putExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI, uri); } } else if (MXSession.isRoomAlias(roomIdOrAlias)) { Log.d(LOG_TAG, "Has a valid universal link of the room Alias " + roomIdOrAlias); // it is a room alias // convert the room alias to room Id mSession.getDataHandler().roomIdByAlias(roomIdOrAlias, new SimpleApiCallback<String>() { @Override public void onSuccess(String roomId) { Log.d(LOG_TAG, "Retrieve the room ID " + roomId); getIntent().putExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI, uri); // the room exists, opens it if (null != mSession.getDataHandler().getRoom(roomId, false)) { Log.d(LOG_TAG, "Find the room from room ID : process it"); processIntentUniversalLink(); } else { Log.d(LOG_TAG, "Don't know the room"); } } }); } } } else { Log.d(LOG_TAG, "create with no universal link"); } if (intent.hasExtra(EXTRA_SHARED_INTENT_PARAMS)) { final Intent sharedFilesIntent = intent.getParcelableExtra(EXTRA_SHARED_INTENT_PARAMS); if (mSession.getDataHandler().getStore().isReady()) { this.runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.sendFilesTo(VectorHomeActivity.this, sharedFilesIntent); } }); } else { mSharedFilesIntent = sharedFilesIntent; } // ensure that it should be called once intent.removeExtra(EXTRA_SHARED_INTENT_PARAMS); } // check if there is some valid session // the home activity could be relaunched after an application crash // so, reload the sessions before displaying the history Collection<MXSession> sessions = Matrix.getMXSessions(VectorHomeActivity.this); if (sessions.size() == 0) { Log.e(LOG_TAG, "Weird : onCreate : no session"); if (null != Matrix.getInstance(this).getDefaultSession()) { Log.e(LOG_TAG, "No loaded session : reload them"); // start splash activity and stop here startActivity(new Intent(VectorHomeActivity.this, SplashActivity.class)); VectorHomeActivity.this.finish(); return; } } FragmentManager fm = getSupportFragmentManager(); mRecentsListFragment = (VectorRecentsListFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECENTS_LIST); if (mRecentsListFragment == null) { // this fragment displays messages and handles all message logic //String matrixId, int layoutResId) mRecentsListFragment = VectorRecentsListFragment.newInstance(mSession.getCredentials().userId, R.layout.fragment_vector_recents_list); fm.beginTransaction() .add(R.id.home_recents_list_anchor, mRecentsListFragment, TAG_FRAGMENT_RECENTS_LIST).commit(); } // clear the notification if they are not anymore valid // i.e the event has been read from another client // or deleted it // + other actions which require a background listener mLiveEventListener = new MXEventListener() { @Override public void onLiveEventsChunkProcessed(String fromToken, String toToken) { // treat any pending URL link workflow, that was started previously processIntentUniversalLink(); if (mClearCacheRequired) { mClearCacheRequired = false; Matrix.getInstance(VectorHomeActivity.this).reloadSessions(VectorHomeActivity.this); } } @Override public void onStoreReady() { if (null != mSharedFilesIntent) { VectorHomeActivity.this.runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.sendFilesTo(VectorHomeActivity.this, mSharedFilesIntent); mSharedFilesIntent = null; } }); } } }; mSession.getDataHandler().addListener(mLiveEventListener); // initialize the public rooms list PublicRoomsManager.setSession(mSession); PublicRoomsManager.refreshPublicRoomsCount(null); }
From source file:com.owncloud.android.services.OperationsService.java
/** * Creates a new operation, as described by operationIntent. * /*from ww w. j av a 2 s . co m*/ * TODO - move to ServiceHandler (probably) * * @param operationIntent Intent describing a new operation to queue and execute. * @return Pair with the new operation object and the information about its * target server. */ private Pair<Target, RemoteOperation> newOperation(Intent operationIntent) { RemoteOperation operation = null; Target target = null; try { if (!operationIntent.hasExtra(EXTRA_ACCOUNT) && !operationIntent.hasExtra(EXTRA_SERVER_URL)) { Log_OC.e(TAG, "Not enough information provided in intent"); } else { Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT); String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL); String cookie = operationIntent.getStringExtra(EXTRA_COOKIE); target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl), cookie); String action = operationIntent.getAction(); if (action.equals(ACTION_CREATE_SHARE_VIA_LINK)) { // Create public share via link String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); if (remotePath != null && remotePath.length() > 0) { operation = new CreateShareViaLinkOperation(remotePath); String name = operationIntent.getStringExtra(EXTRA_SHARE_NAME); ((CreateShareViaLinkOperation) operation).setName(name); String password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD); ((CreateShareViaLinkOperation) operation).setPassword(password); long expirationDateMillis = operationIntent .getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0); ((CreateShareViaLinkOperation) operation).setExpirationDateInMillis(expirationDateMillis); Boolean uploadToFolderPermission = operationIntent .getBooleanExtra(EXTRA_SHARE_PUBLIC_UPLOAD, false); ((CreateShareViaLinkOperation) operation).setPublicUpload(uploadToFolderPermission); int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, OCShare.DEFAULT_PERMISSION); ((CreateShareViaLinkOperation) operation).setPermissions(permissions); } } else if (ACTION_UPDATE_SHARE_VIA_LINK.equals(action)) { long shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1); operation = new UpdateShareViaLinkOperation(shareId); String name = operationIntent.getStringExtra(EXTRA_SHARE_NAME); ((UpdateShareViaLinkOperation) operation).setName(name); String password = operationIntent.getStringExtra(EXTRA_SHARE_PASSWORD); ((UpdateShareViaLinkOperation) operation).setPassword(password); long expirationDate = operationIntent.getLongExtra(EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS, 0); ((UpdateShareViaLinkOperation) operation).setExpirationDate(expirationDate); if (operationIntent.hasExtra(EXTRA_SHARE_PUBLIC_UPLOAD)) { ((UpdateShareViaLinkOperation) operation) .setPublicUpload(operationIntent.getBooleanExtra(EXTRA_SHARE_PUBLIC_UPLOAD, false)); } if (operationIntent.hasExtra(EXTRA_SHARE_PERMISSIONS)) { ((UpdateShareViaLinkOperation) operation).setPermissions( operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, OCShare.DEFAULT_PERMISSION)); } } else if (ACTION_UPDATE_SHARE_WITH_SHAREE.equals(action)) { // Update private share, only permissions long shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1); operation = new UpdateSharePermissionsOperation(shareId); int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, 1); ((UpdateSharePermissionsOperation) operation).setPermissions(permissions); } else if (action.equals(ACTION_CREATE_SHARE_WITH_SHAREE)) { // Create private share with user or group String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); String shareeName = operationIntent.getStringExtra(EXTRA_SHARE_WITH); ShareType shareType = (ShareType) operationIntent.getSerializableExtra(EXTRA_SHARE_TYPE); int permissions = operationIntent.getIntExtra(EXTRA_SHARE_PERMISSIONS, -1); if (remotePath.length() > 0) { operation = new CreateShareWithShareeOperation(remotePath, shareeName, shareType, permissions); } } else if (action.equals(ACTION_UNSHARE)) { // Unshare file long shareId = operationIntent.getLongExtra(EXTRA_SHARE_ID, -1); operation = new RemoveShareOperation(shareId); } else if (action.equals(ACTION_GET_SERVER_INFO)) { // check OC server and get basic information from it operation = new GetServerInfoOperation(serverUrl, OperationsService.this); } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) { // CREATE ACCESS TOKEN to the OAuth server String code = operationIntent.getStringExtra(EXTRA_OAUTH2_AUTHORIZATION_CODE); OAuth2Provider oAuth2Provider = OAuth2ProvidersRegistry.getInstance().getProvider(); OAuth2RequestBuilder builder = oAuth2Provider.getOperationBuilder(); builder.setGrantType(OAuth2GrantType.AUTHORIZATION_CODE); builder.setRequest(OAuth2RequestBuilder.OAuthRequest.CREATE_ACCESS_TOKEN); builder.setAuthorizationCode(code); operation = builder.buildOperation(); } else if (action.equals(ACTION_GET_USER_NAME)) { // Get User Name operation = new GetRemoteUserInfoOperation(); } else if (action.equals(ACTION_RENAME)) { // Rename file or folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); String newName = operationIntent.getStringExtra(EXTRA_NEWNAME); operation = new RenameFileOperation(remotePath, newName); } else if (action.equals(ACTION_REMOVE)) { // Remove file or folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false); operation = new RemoveFileOperation(remotePath, onlyLocalCopy); } else if (action.equals(ACTION_CREATE_FOLDER)) { // Create Folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true); operation = new CreateFolderOperation(remotePath, createFullPath); } else if (action.equals(ACTION_SYNC_FILE)) { // Sync file String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); operation = new SynchronizeFileOperation(remotePath, account, getApplicationContext()); } else if (action.equals(ACTION_SYNC_FOLDER)) { // Sync folder (all its descendant files are sync'ed) String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); boolean pushOnly = operationIntent.getBooleanExtra(EXTRA_PUSH_ONLY, false); boolean syncContentOfRegularFiles = operationIntent.getBooleanExtra(EXTRA_SYNC_REGULAR_FILES, false); operation = new SynchronizeFolderOperation(this, // TODO remove this dependency from construction time remotePath, account, System.currentTimeMillis(), // TODO remove this dependency from construction time pushOnly, false, syncContentOfRegularFiles); } else if (action.equals(ACTION_MOVE_FILE)) { // Move file/folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH); operation = new MoveFileOperation(remotePath, newParentPath); } else if (action.equals(ACTION_COPY_FILE)) { // Copy file/folder String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH); String newParentPath = operationIntent.getStringExtra(EXTRA_NEW_PARENT_PATH); operation = new CopyFileOperation(remotePath, newParentPath, account); } else if (action.equals(ACTION_CHECK_CURRENT_CREDENTIALS)) { // Check validity of currently stored credentials for a given account operation = new CheckCurrentCredentialsOperation(account); } } } catch (IllegalArgumentException e) { Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage()); operation = null; } if (operation != null) { return new Pair<>(target, operation); } else { return null; } }