List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)
From source file:org.apache.rya.accumulo.mr.merge.CopyTool.java
public static void main(final String[] args) { final String log4jConfiguration = System.getProperties().getProperty("log4j.configuration"); if (StringUtils.isNotBlank(log4jConfiguration)) { final String parsedConfiguration = StringUtils.removeStart(log4jConfiguration, "file:"); final File configFile = new File(parsedConfiguration); if (configFile.exists()) { DOMConfigurator.configure(parsedConfiguration); } else {//from w w w . j a v a 2 s. co m BasicConfigurator.configure(); } } log.info("Starting Copy Tool"); Thread.setDefaultUncaughtExceptionHandler( (thread, throwable) -> log.error("Uncaught exception in " + thread.getName(), throwable)); final CopyTool copyTool = new CopyTool(); final int returnCode = copyTool.setupAndRun(args); log.info("Finished running Copy Tool"); System.exit(returnCode); }
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 w w w . j a va 2s . com*/ .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:org.apache.storm.utils.Utils.java
public static void setupDefaultUncaughtExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread thread, Throwable thrown) { try { handleUncaughtException(thrown); } catch (Error err) { LOG.error("Received error in main thread.. terminating server...", err); Runtime.getRuntime().exit(-2); }/*from w w w. j a v a2 s . co m*/ } }); }
From source file:com.mibr.android.intelligentreminder.INeedToo.java
/** Called when the activity is first created. */ @Override/*from w ww.java2 s. c o m*/ public void onCreate(Bundle savedInstanceState) { /* this was just a test if(mLocationManager==null) { mLocationManager=(android.location.LocationManager) getSystemService(Context.LOCATION_SERVICE); } */ // TabHost host=this.getTabHost(); // host.setOnTabChangedListener(new TabHost.OnTabChangeListener() { // // @Override // public void onTabChanged(String tabId) { // if(INeedToo.this._doingCreatingTabs==false) { // if(tabId.equals("tab1")) { // INeedToo.this._forceNonCompany=true; // } // } // } // }); super.onCreate(savedInstanceState); mLocationClient = new LocationClient(this, this, this); mLocationClient.connect(); try { if (getIntent().getAction() != null && getIntent().getAction().equals("doPrimitiveDeletedNeed")) { transmitNetwork(getIntent().getStringExtra("phoneid")); return; } } catch (Exception eieio) { return; } try { /* putExtra("needId",needId). putExtra("foreignNeedId",foreignNeedId). putExtra("phoneid",phoneid). putExtra("foreignLocationId",foreignLocationId) */ if (getIntent().getAction() != null && getIntent().getAction().equals("transmitNetworkDeletedThisNeedByOnBehalfOf")) { long needId = getIntent().getLongExtra("needId", -11); long foreignNeedId = getIntent().getLongExtra("foreignNeedId", -11); String phoneId = getIntent().getStringExtra("phoneid"); long foreignLocationId = getIntent().getLongExtra("foreignLocationId", -11); if (needId != -11 && foreignNeedId != -11 && foreignLocationId != -11 && isNothingNot(phoneId)) transmitNetworkDeletedThisNeedByOnBehalfOf(needId, foreignNeedId, phoneId, foreignLocationId); return; } } catch (Exception ei3) { return; } /*bbhbb 2011-03-26*/ /*bbhbb2013_05_01 isn't this being done below? * Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler("")); */ mHandler = new Handler(); doBindService(); mSingleton = this; ///////////mSingleton.log("onCreating_INeedToo", 1); if (getPackageName().toLowerCase().indexOf("trial") != -1 && !isSpecialPhone()) { if (!iveCheckedAuthorizationStatusForThisPhone) { doViewCount = true; iveCheckedAuthorizationStatusForThisPhone = true; final Timer jdTimer = new Timer("Registering"); jdTimer.schedule(new TimerTask() { public void run() { Thread thread = new Thread(new Runnable() { public void run() { Intent intent = new Intent(INeedToo.this, INeedWebService.class) .setAction("CheckStatus"); startService(intent); jdTimer.cancel(); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.run(); } }, 3000, 1000 * 60 * 10); } } else { if (IS_ANDROID_VERSION) { if (!isSpecialPhone() || INeedToo.mSingleton.getPhoneId().toLowerCase().equals("20013fc135cd6097xx")) { final Timer jdTimer = new Timer("Licensing"); jdTimer.schedule(new TimerTask() { public void run() { Thread thread = new Thread(new Runnable() { public void run() { // Construct the LicenseCheckerCallback. The library calls this when done. mLicenseCheckerCallback = new MyLicenseCheckerCallback(); // Construct the LicenseChecker with a Policy. mChecker = new LicenseChecker(INeedToo.this, new ServerManagedPolicy(INeedToo.this, new AESObfuscator(SALT, getPackageName(), // "com.mibr.android.intelligentreminder", getDeviceId())), BASE64_PUBLIC_KEY // Your public licensing key. ); mChecker.checkAccess(mLicenseCheckerCallback); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.run(); } }, 3000, 1000 * 60 * 10); } } } try { _logFilter = Integer .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getString("LoggingLevel", "3")); } catch (Exception e) { } if (!INeedLocationService.USING_LOCATION_SERVICES) { int logFilter = 3; try { logFilter = Integer .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getString("LoggingLevel", "3")); } catch (Exception e) { } Intent jdIntent = new Intent(this, INeedTimerServices.class).putExtra("logFilter", logFilter); getApplicationContext().startService(jdIntent); } Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler("")); if (INeedToo.mSingleton.getPhoneId().toLowerCase().equals("22a100000d9f25c5")) { DELAYPOSTTTS = 100; } // I don't need this because IHaveNeeds.onresume does it getApplicationContext().startService(new Intent(this, INeedLocationService.class)); if (!_doneSplashy) { _doneSplashy = true; if (!getVersionFile()) { stampVersion(); showDialog(DIALOG_SPLASH); } else { //showDialog(DIALOG_SPLASH); } } if (allItems != null) { whereImAtInAllItems++; if (whereImAtInAllItems < allItems.size()) { showDialog(DOING_SAMPLE_NEEDS_DIALOG); } else { allItems = null; } } setTitle(getHeading()); Bundle bundle = getIntent().getExtras(); if (bundle != null) { _initialTabIndex = bundle.getInt("initialtabindex", 0); _didContact = bundle.getBoolean("iscontact", false); if (_initialTabIndex == 1) { _doingLocationCompany = bundle.getString("doingcompany"); } else { _doingLocationCompany = null; } } else { _doingLocationCompany = null; } final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Need", getResources().getDrawable(R.drawable.status_bar2_blackwhite)) .setContent(new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact))); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("Location", (BitmapDrawable) getResources().getDrawable(android.R.drawable.ic_menu_mapmode)) .setContent( new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany))); Intent intent = new Intent(this, NeedMap.class).putExtra("doingcompany", _doingLocationCompany); tabHost.addTab(tabHost.newTabSpec("tab2a") .setIndicator("Map", (BitmapDrawable) getResources().getDrawable(R.drawable.ic_dialog_map)) .setContent(intent)); /* tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator( "History",(BitmapDrawable) getResources().getDrawable( R.drawable.chart)).setContent( new Intent(this, IHaveHistory.class))); */ tabHost.addTab(tabHost.newTabSpec("tab4") .setIndicator("System", (BitmapDrawable) getResources().getDrawable(R.drawable.status_bar1_blackwhite)) .setContent(new Intent(this, ListPlus.class))); /* tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator( "Need", scaleTo((BitmapDrawable) getResources().getDrawable( R.drawable.status_bar2_blackwhite), 36f)).setContent( new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact))); tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator( "Location", scaleTo((BitmapDrawable) getResources().getDrawable( android.R.drawable.ic_menu_mapmode), 36f)).setContent( new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany))); tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator( "History", scaleTo((BitmapDrawable) getResources().getDrawable( R.drawable.chart), 36f)).setContent( new Intent(this, IHaveHistory.class))); tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator( "System", scaleTo((BitmapDrawable) getResources().getDrawable( R.drawable.status_bar1_blackwhite), 31f)).setContent( new Intent(this, ListPlus.class))); */ tabHost.setCurrentTab(_initialTabIndex); boolean networkingOutbound = getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getBoolean("Networking_Outbound_Enabled", false); if (INeedWebService.mSingleton == null) { if (networkingOutbound) { enableTransmitting(); } if (getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getBoolean("Networking_Inbound_Enabled", false)) { enableReceiving(); } } }
From source file:com.brainflow.application.toplevel.Brainflow.java
private void initExceptionHandler() { LookAndFeelFactory.UIDefaultsCustomizer uiDefaultsCustomizer = new LookAndFeelFactory.UIDefaultsCustomizer() { public void customize(UIDefaults defaults) { ThemePainter painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter"); defaults.put("OptionPaneUI", "com.jidesoft.plaf.basic.BasicJideOptionPaneUI"); defaults.put("OptionPane.showBanner", Boolean.TRUE); // show banner or not. default is true //defaults.put("OptionPane.bannerIcon", JideIconsFactory.getImageIcon(JideIconsFactory.JIDE50)); defaults.put("OptionPane.bannerFontSize", 13); defaults.put("OptionPane.bannerFontStyle", Font.BOLD); defaults.put("OptionPane.bannerMaxCharsPerLine", 60); defaults.put("OptionPane.bannerForeground", painter != null ? painter.getOptionPaneBannerForeground() : null); // you should adjust this if banner background is not the default gradient paint defaults.put("OptionPane.bannerBorder", null); // use default border // set both bannerBackgroundDk and // set both bannerBackgroundLt to null if you don't want gradient defaults.put("OptionPane.bannerBackgroundDk", painter != null ? painter.getOptionPaneBannerDk() : null); defaults.put("OptionPane.bannerBackgroundLt", painter != null ? painter.getOptionPaneBannerLt() : null); defaults.put("OptionPane.bannerBackgroundDirection", Boolean.TRUE); // default is true // optionally, you can set a Paint object for BannerPanel. If so, the three UIDefaults related to banner background above will be ignored. defaults.put("OptionPane.bannerBackgroundPaint", null); defaults.put("OptionPane.buttonAreaBorder", BorderFactory.createEmptyBorder(6, 6, 6, 6)); defaults.put("OptionPane.buttonOrientation", SwingConstants.RIGHT); }//from www . j a v a2 s .co m }; uiDefaultsCustomizer.customize(UIManager.getDefaults()); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); JideOptionPane optionPane = new JideOptionPane( "Click \"Details\" button to see more information ... ", JOptionPane.ERROR_MESSAGE, JideOptionPane.CLOSE_OPTION); optionPane.setTitle("An " + e.getClass().getName() + " occurred in Brainflow : " + e.getMessage()); JTextArea textArea = new JTextArea(); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); e.printStackTrace(out); // Add string to end of text area textArea.append(sw.toString()); textArea.setRows(10); optionPane.setDetails(new JScrollPane(textArea)); JDialog dialog = optionPane.createDialog(brainFrame, "Warning"); dialog.setResizable(true); dialog.pack(); dialog.setVisible(true); } }); }
From source file:org.spontaneous.trackservice.RemoteService.java
private void registerExceptionHandler() { if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) { Thread.setDefaultUncaughtExceptionHandler( new CustomExceptionHandler(getExternalCacheDir().toString(), null)); }// w w w .ja v a 2 s . c o m }
From source file:org.apache.storm.util.CoreUtil.java
/** * Set a default uncaught exception handler to handle exceptions not caught in * other threads.//from w w w .ja va 2s . c o m */ @ClojureClass(className = "backtype.storm.util#setup-default-uncaught-exception-handler") public static void setupDefaultUncaughtExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable thrown) { try { Utils.handleUncaughtException(thrown); } catch (Error err) { LOG.error("Received error in main thread.. terminating server..."); Runtime.getRuntime().exit(-2); } } }); }
From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java
/** * Creates and attaches the UnhandledException handler for piping them to the dialog *///from w w w . ja v a2s . c o m @SuppressWarnings("unused") private static void attachUnhandledException() { log.debug("attachUnhandledException " + Thread.currentThread().getName() + " " + Thread.currentThread().hashCode()); Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { processUnhandledException(e); } }); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { log.debug("attachUnhandledException " + Thread.currentThread().getName() + " " + Thread.currentThread().hashCode()); Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { processUnhandledException(e); } }); } }); } catch (InterruptedException e1) { e1.printStackTrace(); } catch (InvocationTargetException e1) { e1.printStackTrace(); } Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { processUnhandledException(e); } }); }
From source file:com.updetector.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /**/*from ww w. j a v a 2 s. c o m*/ * Set the views */ // Set the main layout setContentView(R.layout.activity_main); // get a handle to the console textview consoleTextView = (TextView) findViewById(R.id.console_text_id); consoleTextView.setMovementMethod(new ScrollingMovementMethod()); //setup monitoring fields environTextView = (TextView) findViewById(R.id.environment); environTextView.setText(ENVIRONMENT_PREFIX + CommonUtils.eventCodeToString(lastEnvironment)); stateTextView = (TextView) findViewById(R.id.state); //stateTextView.setText(STATE_PREFIX+"unknown"); googleStateTextView = (TextView) findViewById(R.id.google_state); googleStateTextView.setText(GOOGLE_MOBILITY_STATE_PREFIX + "unknown"); //indicatorTextView=(TextView) findViewById(R.id.indicator); //indicatorTextView.setText(INDICATOR_PREFIX); // set up the map view setupMapIfNeeded(); //set up the location client setupLocationClientIfNeeded(); /** * set up color coded map */ if (parkingBlocks == null) { parkingBlocks = ParkingBlocks.GetParkingBlocks(); showAvailabilityMap(); } mTextToSpeech = new TextToSpeech(this, this); mCalendar = Calendar.getInstance(); /* * Initialize managers */ // Instantiate an adapter to store update data from the log /* mStatusAdapter = new ArrayAdapter<Spanned>( this, R.layout.item_layout, R.id.log_text );*/ // Set the broadcast receiver intent filer mBroadcastManager = LocalBroadcastManager.getInstance(this); // Create a new Intent filter for the broadcast receiver mBroadcastFilter = new IntentFilter(Constants.ACTION_REFRESH_STATUS_LIST); mBroadcastFilter.addCategory(Constants.CATEGORY_LOCATION_SERVICES); mBroadcastFilter.addAction(Constants.BLUETOOTH_CONNECTION_UPDATE); mBroadcastFilter.addAction(Constants.GOOGLE_ACTIVITY_RECOGNITION_UPDATE); mBroadcastManager.registerReceiver(mBroadcastReceiver, mBroadcastFilter); // Get the instance of the customized notification manager mDetectionNotificationManager = DetectionNotificationManager.getInstance(this); //Get the FusionManager object mFusionManager = new FusionManager(this); // Get the ClassificationManager object mClassificationManager = ClassificationManager.getInstance(this); //TODO train classifiers if necessary if (Constants.IS_TRAINING_MODE) { int[] classifiersToBeTrained = { Constants.ACCEL_MOTION_STATE }; for (int classifier : classifiersToBeTrained) { mClassificationManager.mClassfiers.get(classifier).train(); } } //get the sensor service mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE); //get the accelerometer sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(mSensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); mAudioRecordManager = AudioRecordManager.getInstance(); // Get the WakeLockManager object mWakeLockManager = WakeLockManager.getInstance(this); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Get the LogManager object mLogManager = LogManager.getInstance(this); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mXPSHandler = new XPS(this); mXPSHandler.setRegistrationUser(new WPSAuthentication("dbmc", "uic")); //mXPSHandler.setTiling("", 0, 0, null); /** * Initialize IODetector */ cellTowerChart = new CellTowerChart((TelephonyManager) getSystemService(TELEPHONY_SERVICE), this); magnetChart = new MagnetChart(mSensorManager, this); lightChart = new LightChart(mSensorManager, this); //new AggregatedIODetector().execute("");//Check the detection for the first time //This timer handle starts the aggregated calculation for the detection //Interval 1 seconds. Timer uiTimer = new Timer(); mIODectorHandler = new Handler(); /*uiTimer.scheduleAtFixedRate(new TimerTask() { private int walked = 0; @Override public void run() { mIODectorHandler.post(new Runnable() { @Override public void run() { if(phoneNotStill){//Check if the user is walking walked++; } else{ walked = 0; } if(aggregationFinish && walked > 3){//Check if the user has walked for at least 3 second, and the previous calculation has been finish aggregationFinish = false; walked = 0; new AggregatedIODetector().execute(""); } } }); } }, 0, 1000);*/ /** * Initialize fields other than managers */ lastAccReading = new double[3]; /** * Startup routines */ // catch the force close error Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(MainActivity.this)); /** * Start Google Activity Recognition */ mGoogleActivityDetectionRequester = new GoogleActivityRecognitionClientRequester(this); mGoogleActivityDetectionRemover = new GoogleActivityRecognitionClientRemover(this); startGoogleActivityRecognitionUpdates(null); checkGPSEnabled(); //test record sample //mAudioRecordManager.recordAudioSample("/sdcard/audio.wav"); //Test extract features from audio files //String features=AudioFeatureExtraction.extractFeatures(this, "/sdcard/bus6.wav"); //mClassificationManager.mClassfiers.get(Constants.SENSOR_MICROPHONE).classify(features); }
From source file:com.vonglasow.michael.satstat.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { Context c = getApplicationContext(); File dumpDir = c.getExternalFilesDir(null); File dumpFile = new File(dumpDir, "satstat-" + System.currentTimeMillis() + ".log"); PrintStream s;//from w w w .ja va 2 s . co m try { InputStream buildInStream = getResources().openRawResource(R.raw.build); s = new PrintStream(dumpFile); s.append("SatStat build: "); int i; try { i = buildInStream.read(); while (i != -1) { s.write(i); i = buildInStream.read(); } buildInStream.close(); } catch (IOException e1) { e1.printStackTrace(); } s.append("\n\n"); e.printStackTrace(s); s.flush(); s.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } defaultUEH.uncaughtException(t, e); } }); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); final ActionBar actionBar = getActionBar(); setContentView(R.layout.activity_main); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Find out default screen orientation Configuration config = getResources().getConfiguration(); WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); int rot = wm.getDefaultDisplay().getRotation(); isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180) || config.orientation == Configuration.ORIENTATION_PORTRAIT && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270)); Log.d("MainActivity", "isWideScreen=" + Boolean.toString(isWideScreen)); // compact action bar int dpX = (int) (this.getResources().getDisplayMetrics().widthPixels / this.getResources().getDisplayMetrics().density); /* * This is a crude way to ensure a one-line action bar with tabs * (not a drop-down list) and home (incon) and title only if there * is space, depending on screen width: * divide screen in units of 64 dp * each tab requires 1 unit, home and menu require slightly less, * title takes up approx. 2.5 units in portrait, * home and title are about 2 units wide in landscape */ if (dpX < 192) { // just enough space for drop-down list and menu actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); } else if (dpX < 320) { // not enough space for four tabs, but home will fit next to list actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } else if (dpX < 384) { // just enough space for four tabs actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); } else if ((dpX < 448) || ((config.orientation == Configuration.ORIENTATION_PORTRAIT) && (dpX < 544))) { // space for four tabs and home, but not title actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } else { // ample space for home, title and all four tabs actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(true); } setEmbeddedTabs(actionBar, true); providerLocations = new HashMap<String, Location>(); mAvailableProviderStyles = new ArrayList<String>(Arrays.asList(LOCATION_PROVIDER_STYLES)); providerStyles = new HashMap<String, String>(); providerAppliedStyles = new HashMap<String, String>(); providerInvalidationHandler = new Handler(); providerInvalidators = new HashMap<String, Runnable>(); // 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.setOnPageChangeListener(this); // Add tabs, specifying the tab's text and TabListener for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { actionBar.addTab(actionBar.newTab() //.setText(mSectionsPagerAdapter.getPageTitle(i)) .setIcon(mSectionsPagerAdapter.getPageIcon(i)).setTabListener(this)); } // This is needed by the mapsforge library. AndroidGraphicFactory.createInstance(this.getApplication()); // Get system services for event delivery mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mOrSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mPressureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); mHumiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); mTempSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); mAccSensorRes = getSensorDecimals(mAccSensor, mAccSensorRes); mGyroSensorRes = getSensorDecimals(mGyroSensor, mGyroSensorRes); mMagSensorRes = getSensorDecimals(mMagSensor, mMagSensorRes); mLightSensorRes = getSensorDecimals(mLightSensor, mLightSensorRes); mProximitySensorRes = getSensorDecimals(mProximitySensor, mProximitySensorRes); mPressureSensorRes = getSensorDecimals(mPressureSensor, mPressureSensorRes); mHumiditySensorRes = getSensorDecimals(mHumiditySensor, mHumiditySensorRes); mTempSensorRes = getSensorDecimals(mTempSensor, mTempSensorRes); networkTimehandler = new Handler(); networkTimeRunnable = new Runnable() { @Override public void run() { int newNetworkType = mTelephonyManager.getNetworkType(); if (getNetworkGeneration(newNetworkType) != mLastNetworkGen) onNetworkTypeChanged(newNetworkType); else networkTimehandler.postDelayed(this, NETWORK_REFRESH_DELAY); } }; wifiTimehandler = new Handler(); wifiTimeRunnable = new Runnable() { @Override public void run() { mWifiManager.startScan(); wifiTimehandler.postDelayed(this, WIFI_REFRESH_DELAY); } }; updateLocationProviderStyles(); }