idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
38,800
private MBeanAttributeConfig makeConfigMBeanAttribute ( ObjectName mBeanName , MBeanAttributeInfo attributeInfo ) { Object attr ; try { attr = mBeanServer . getAttribute ( mBeanName , attributeInfo . getName ( ) ) ; MBeanAttributeConfig config = new MBeanAttributeConfig ( ) ; config . addField ( "name" , attributeInfo . getName ( ) ) ; if ( attr == null ) { return null ; } else if ( attr instanceof CompositeData ) { addComposites ( config , ( CompositeData ) attr ) ; } else { config . addField ( "type" , translateDataType ( attributeInfo . getType ( ) ) ) ; } return config ; } catch ( RuntimeMBeanException e ) { System . err . println ( e . getMessage ( ) ) ; } catch ( AttributeNotFoundException e ) { System . err . println ( e . getMessage ( ) ) ; } catch ( InstanceNotFoundException e ) { System . err . println ( e . getMessage ( ) ) ; } catch ( MBeanException e ) { System . err . println ( e . getMessage ( ) ) ; } catch ( ReflectionException e ) { System . err . println ( e . getMessage ( ) ) ; } return null ; }
Creates an object to represent a single attribute of an MBean . An attribute can be a simple attribute or made up composites .
38,801
private void addComposites ( MBeanAttributeConfig config , CompositeData compositeData ) { CompositeType compositeType = compositeData . getCompositeType ( ) ; for ( String key : compositeType . keySet ( ) ) { config . addChild ( makeComposite ( compositeType , key ) ) ; } }
Adds the composite data of an MBean s attribute to an MBeanAttributeConfig
38,802
private MBeanCompositeConfig makeComposite ( CompositeType compositeType , String name ) { MBeanCompositeConfig config = new MBeanCompositeConfig ( ) ; config . addField ( "name" , name ) ; String rawType = compositeType . getType ( name ) . toString ( ) ; config . addField ( "type" , translateDataType ( rawType ) ) ; return config ; }
Makes a configuration for JMXetric that represents the composite tag
38,803
public GMetric getConfig ( ) throws IOException , XPathExpressionException { ganglia = getXmlNode ( "/jmxetric-config/ganglia" , inputSource ) ; GMetric gmetric = makeGMetricFromXml ( ) ; return gmetric ; }
Creates a GMetric attribute on the JMXetricAgent from the XML config
38,804
GMetric makeGMetricFromXml ( ) throws IOException { String hostname = getHostName ( ) ; int port = getPort ( ) ; UDPAddressingMode addressingMode = getAddressingMode ( ) ; boolean v31x = getV31 ( ) ; String spoof = getSpoof ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( "GMetric host=" ) . append ( hostname ) ; buf . append ( " port=" ) . append ( port ) ; buf . append ( " mode=" ) . append ( addressingMode ) ; buf . append ( " v31x=" ) . append ( v31x ) ; buf . append ( " spoof=" ) . append ( spoof ) ; log . fine ( buf . toString ( ) ) ; System . out . println ( buf . toString ( ) ) ; return new GMetric ( hostname , port , addressingMode , DEFAULT_TTL , v31x , null , spoof ) ; }
Makes a GMetric object that can be use to define configuration for an agent .
38,805
private int getPort ( ) { String port = getGangliaConfig ( args . getPort ( ) , ganglia , "port" , DEFAULT_PORT ) ; return Integer . parseInt ( port ) ; }
Gets the port that JMXetric will announce to this is usually the port gmond is running on
38,806
private UDPAddressingMode getAddressingMode ( ) { String mode = getGangliaConfig ( args . getMode ( ) , ganglia , "mode" , DEFAULT_MODE ) ; if ( mode . toLowerCase ( ) . equals ( "unicast" ) ) { return UDPAddressingMode . UNICAST ; } else { return UDPAddressingMode . MULTICAST ; } }
UDPAddressingMode to use for reporting
38,807
private boolean getV31 ( ) { String stringv31x = getGangliaConfig ( args . getWireformat ( ) , ganglia , "wireformat31x" , "false" ) ; return Boolean . parseBoolean ( stringv31x ) ; }
Whether the reporting be done on the new wire format 31 .
38,808
private String getGangliaConfig ( String cmdLine , Node ganglia , String attributeName , String defaultValue ) { if ( cmdLine == null ) { return selectParameterFromNode ( ganglia , attributeName , defaultValue ) ; } else { return cmdLine ; } }
Gets a configuration parameter for Ganglia . First checks if it was given on the command line arguments . If it is not available it looks for the value in the XML node .
38,809
String getConfigString ( ) throws XPathExpressionException { ganglia = getXmlNode ( "/jmxetric-config/ganglia" , inputSource ) ; String hostname = getHostName ( ) ; int port = getPort ( ) ; UDPAddressingMode addressingMode = getAddressingMode ( ) ; boolean v31x = getV31 ( ) ; String spoof = getSpoof ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( "GMetric host=" ) . append ( hostname ) ; buf . append ( " port=" ) . append ( port ) ; buf . append ( " mode=" ) . append ( addressingMode ) ; buf . append ( " v31x=" ) . append ( v31x ) ; buf . append ( " spoof=" ) . append ( spoof ) ; return buf . toString ( ) ; }
Method used by tests to print out the read in configuration .
38,810
public static void main ( String [ ] args ) throws Exception { while ( true ) { Thread . sleep ( 1000 * 60 * 5 ) ; System . out . println ( "Test wakeup" ) ; } }
A log running trivial main method for test purposes premain method
38,811
public static void premain ( String agentArgs , Instrumentation inst ) { System . out . println ( STARTUP_NOTICE ) ; JMXetricAgent a = null ; try { a = new JMXetricAgent ( ) ; XMLConfigurationService . configure ( a , agentArgs ) ; a . start ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } }
The JVM agent entry point
38,812
public void run ( ) { try { for ( String mbean : mbeanMap . keySet ( ) ) { MBeanHolder h = mbeanMap . get ( mbean ) ; h . publish ( ) ; } } catch ( Exception ex ) { log . warning ( "Exception thrown sampling Mbeans" ) ; log . throwing ( this . getClass ( ) . getName ( ) , "Exception thrown sampling Mbeans:" , ex ) ; } }
Called by the JMXAgent periodically to sample the mbeans
38,813
public static void configure ( JMXetricAgent agent , String agentArgs ) throws Exception { CommandLineArgs args = new CommandLineArgs ( agentArgs ) ; InputSource inputSource = new InputSource ( args . getConfig ( ) ) ; configureGanglia ( agent , inputSource , args ) ; configureJMXetric ( agent , inputSource , args ) ; }
Configures the JMXetricAgent based on the supplied agentArgs Command line arguments overwrites XML arguments . Any arguments that is required but no supplied will be defaulted .
38,814
String readString ( ) throws IOException { StringBuilder sb = new StringBuilder ( 50 ) ; char ch = reader . next ( ) ; if ( ch != '\"' ) { throw new JsonParseException ( "Expected \" but actual is: " + ch , reader . readed ) ; } for ( ; ; ) { ch = reader . next ( ) ; if ( ch == '\\' ) { char ech = reader . next ( ) ; switch ( ech ) { case '\"' : sb . append ( '\"' ) ; break ; case '\\' : sb . append ( '\\' ) ; break ; case '/' : sb . append ( '/' ) ; break ; case 'b' : sb . append ( '\b' ) ; break ; case 'f' : sb . append ( '\f' ) ; break ; case 'n' : sb . append ( '\n' ) ; break ; case 'r' : sb . append ( '\r' ) ; break ; case 't' : sb . append ( '\t' ) ; break ; case 'u' : int u = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { char uch = reader . next ( ) ; if ( uch >= '0' && uch <= '9' ) { u = ( u << 4 ) + ( uch - '0' ) ; } else if ( uch >= 'a' && uch <= 'f' ) { u = ( u << 4 ) + ( uch - 'a' ) + 10 ; } else if ( uch >= 'A' && uch <= 'F' ) { u = ( u << 4 ) + ( uch - 'A' ) + 10 ; } else { throw new JsonParseException ( "Unexpected char: " + uch , reader . readed ) ; } } sb . append ( ( char ) u ) ; break ; default : throw new JsonParseException ( "Unexpected char: " + ch , reader . readed ) ; } } else if ( ch == '\"' ) { break ; } else if ( ch == '\r' || ch == '\n' ) { throw new JsonParseException ( "Unexpected char: " + ch , reader . readed ) ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ; }
read string like a encoded \ u0098 \ str
38,815
double string2Fraction ( CharSequence cs , int readed ) { if ( cs . length ( ) > 16 ) { throw new JsonParseException ( "Number string is too long." , readed ) ; } double d = 0.0 ; for ( int i = 0 ; i < cs . length ( ) ; i ++ ) { int n = cs . charAt ( i ) - '0' ; d = d + ( n == 0 ? 0 : n / Math . pow ( 10 , i + 1 ) ) ; } return d ; }
parse 0123 as 0 . 0123
38,816
public < T > JsonBuilder registerTypeAdapter ( Class < T > clazz , TypeAdapter < T > typeAdapter ) { typeAdapters . registerTypeAdapter ( clazz , typeAdapter ) ; return this ; }
Register a TypeAdapter .
38,817
public JsonReader createReader ( Reader reader ) { return new JsonReader ( reader , jsonObjectFactory , jsonArrayFactory , objectMapper , typeAdapters ) ; }
Create a JsonReader by providing a Reader .
38,818
public JsonReader createReader ( InputStream input ) { try { return createReader ( new InputStreamReader ( input , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Create a JsonReader by providing an InputStream .
38,819
public JsonWriter createWriter ( OutputStream output ) { Writer writer = null ; try { writer = new OutputStreamWriter ( output , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } return new JsonWriter ( writer , typeAdapters ) ; }
Create a JsonWriter that write JSON to specified OutputStream .
38,820
private static String getSetterName ( Method m ) { String name = m . getName ( ) ; if ( name . startsWith ( "set" ) && ( name . length ( ) >= 4 ) && m . getReturnType ( ) . equals ( void . class ) && ( m . getParameterTypes ( ) . length == 1 ) ) { return Character . toLowerCase ( name . charAt ( 3 ) ) + name . substring ( 4 ) ; } return null ; }
Get setter name . setName - > name
38,821
public void remove ( final View view ) { if ( view . getParent ( ) instanceof ViewGroup ) { final ViewGroup parent = ( ViewGroup ) view . getParent ( ) ; if ( durationSet ) { view . animate ( ) . setDuration ( duration ) ; } view . animate ( ) . alpha ( 0f ) . setListener ( new AnimatorListenerAdapter ( ) { public void onAnimationEnd ( Animator animation ) { parent . removeView ( view ) ; view . setAlpha ( 1 ) ; view . animate ( ) . setListener ( null ) ; } } ) ; } }
Fades out the given view and then removes in from its parent . If the view is not currently parented the method simply returns without doing anything .
38,822
public void add ( final View view , final ViewGroup parent , int index ) { if ( view . getParent ( ) == null ) { view . setAlpha ( 0 ) ; parent . addView ( view , index ) ; if ( durationSet ) { view . animate ( ) . setDuration ( duration ) ; } view . animate ( ) . alpha ( 1 ) ; } }
Adds a view to the specified parent at the specified index in the parent s child list and then fades in the view . The view must not currently be parented - if its parent is not null the method returns without doing anything .
38,823
public void show ( final View view ) { if ( view . getVisibility ( ) != View . VISIBLE ) { view . setAlpha ( 0 ) ; view . setVisibility ( View . VISIBLE ) ; if ( durationSet ) { view . animate ( ) . setDuration ( duration ) ; } view . animate ( ) . alpha ( 1 ) ; } }
Sets the visibility of the specified view to View . VISIBLE and then fades it in . If the view is already visible the method will return without doing anything .
38,824
public static long start ( String key ) { if ( key . isEmpty ( ) ) { throw new InvalidKeyForTimeStampException ( ) ; } long timestamp = QuickUtils . date . getCurrentTimeInMiliseconds ( ) ; QuickUtils . prefs . save ( TIMER_PREFIX + key , timestamp ) ; return timestamp ; }
Start counting time
38,825
public static void resetAllTimestamps ( ) { Map < String , ? > allEntries = QuickUtils . prefs . getAll ( ) ; for ( Map . Entry < String , ? > entry : allEntries . entrySet ( ) ) { if ( entry . getKey ( ) . startsWith ( TIMER_PREFIX ) ) { QuickUtils . prefs . remove ( entry . getKey ( ) ) ; } } }
Resets all the timestamps
38,826
public static double round ( double toBeRounded , int digits ) { if ( digits < 0 ) { QuickUtils . log . e ( "must be greater than 0" ) ; return 0 ; } String formater = "" ; for ( int i = 0 ; i < digits ; i ++ ) { formater += "#" ; } DecimalFormat twoDForm = new DecimalFormat ( "#." + formater , new DecimalFormatSymbols ( Locale . US ) ) ; return Double . valueOf ( twoDForm . format ( toBeRounded ) ) ; }
Rounds a double value to a certain number of digits
38,827
public static int getRandomInteger ( int min , int max ) { Random r = new Random ( ) ; return r . nextInt ( max - min + 1 ) + min ; }
Returns a random integer between MIN inclusive and MAX inclusive .
38,828
public static double getRandomDouble ( double min , double max ) { Random r = new Random ( ) ; return min + ( max - min ) * r . nextDouble ( ) ; }
Returns a random double between MIN inclusive and MAX inclusive .
38,829
public static int getRandomNumber ( int min , int max ) { Random r = new Random ( ) ; return r . nextInt ( max - min + 1 ) + min ; }
Returns a random number between MIN inclusive and MAX exclusive .
38,830
public static double truncate ( double value , int places ) { if ( places < 0 ) { throw new IllegalArgumentException ( ) ; } long factor = ( long ) java . lang . Math . pow ( 10 , places ) ; value = value * factor ; long tmp = ( long ) value ; return ( double ) tmp / factor ; }
Truncates a value
38,831
private static String privateBase64Encoder ( String toEncode , int flags ) { byte [ ] data = null ; try { data = toEncode . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException e1 ) { e1 . printStackTrace ( ) ; } if ( flags == - 1 ) { flags = Base64 . DEFAULT ; } return Base64 . encodeToString ( data , flags ) ; }
private Encoder in base64
38,832
private static String privateBase64Decoder ( String decode , int flags ) { if ( flags == - 1 ) { flags = Base64 . DEFAULT ; } byte [ ] data1 = Base64 . decode ( decode , flags ) ; String decodedBase64 = null ; try { decodedBase64 = new String ( data1 , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return decodedBase64 ; }
Private decoder in base64
38,833
public static String calculateMD5 ( String string ) { byte [ ] hash ; try { hash = MessageDigest . getInstance ( "MD5" ) . digest ( string . getBytes ( "UTF-8" ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( "Huh, MD5 should be supported?" , e ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( "Huh, UTF-8 should be supported?" , e ) ; } StringBuilder hex = new StringBuilder ( hash . length * 2 ) ; for ( byte b : hash ) { int i = ( b & 0xFF ) ; if ( i < 0x10 ) hex . append ( '0' ) ; hex . append ( Integer . toHexString ( i ) ) ; } return hex . toString ( ) ; }
Calculate the MD5 of a given String
38,834
public static String calculateSHA1 ( String string ) { MessageDigest md = null ; try { md = MessageDigest . getInstance ( "SHA-1" ) ; } catch ( NoSuchAlgorithmException e ) { QuickUtils . log . e ( "NoSuchAlgorithmException" , e ) ; } try { md . update ( string . getBytes ( "iso-8859-1" ) , 0 , string . length ( ) ) ; } catch ( UnsupportedEncodingException e ) { QuickUtils . log . e ( "UnsupportedEncodingException" , e ) ; } byte [ ] sha1hash = md . digest ( ) ; return convertToHex ( sha1hash ) ; }
Calculate the SHA - 1 of a given String
38,835
public static void navigateToActivityByClassName ( Context context , String className ) throws ClassNotFoundException { Class < ? > c = null ; if ( className != null ) { try { c = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { QuickUtils . log . d ( "ClassNotFound" , e ) ; } } navigateToActivity ( context , c ) ; }
Navigate to an activity programmatically by providing the package + activity name
38,836
public static String getApplicationHashKey ( String packageName ) { String hash = "" ; try { PackageInfo info = QuickUtils . getContext ( ) . getPackageManager ( ) . getPackageInfo ( packageName , PackageManager . GET_SIGNATURES ) ; for ( Signature signature : info . signatures ) { MessageDigest md = MessageDigest . getInstance ( "SHA" ) ; md . update ( signature . toByteArray ( ) ) ; hash = Base64 . encodeToString ( md . digest ( ) , Base64 . DEFAULT ) ; } } catch ( NameNotFoundException e ) { QuickUtils . log . e ( "NameNotFoundException" ) ; } catch ( NoSuchAlgorithmException e ) { QuickUtils . log . e ( "NoSuchAlgorithmException" ) ; } return hash ; }
Your app key hash is required for example for Facebook Login in order to perform security check before authorizing your app .
38,837
public static void toast ( String message ) { Toast toast = Toast . makeText ( QuickUtils . getContext ( ) , message , Toast . LENGTH_SHORT ) ; toast . show ( ) ; }
Quick toast method with short duration
38,838
public static String getDeviceID ( ) { return Settings . Secure . getString ( QuickUtils . getContext ( ) . getContentResolver ( ) , Settings . Secure . ANDROID_ID ) ; }
Get device unique ID
38,839
public static void toggleKeyboard ( ) { InputMethodManager imm = ( ( InputMethodManager ) QuickUtils . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ) ; imm . toggleSoftInput ( 0 , 0 ) ; }
Toggles the SoftKeyboard Input be careful where you call this from as if you want to hide the keyboard and its already hidden it will be shown
38,840
public static void requestHideKeyboard ( View v ) { InputMethodManager imm = ( ( InputMethodManager ) QuickUtils . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ) ; imm . hideSoftInputFromWindow ( v . getWindowToken ( ) , 0 ) ; }
Hides the SoftKeyboard input careful as if you pass a view that didn t open the soft - keyboard it will ignore this call and not close
38,841
public static int convertToDip ( DisplayMetrics displayMetrics , int sizeInPixels ) { return ( int ) TypedValue . applyDimension ( TypedValue . COMPLEX_UNIT_DIP , sizeInPixels , displayMetrics ) ; }
Converts the number in pixels to the number in dips
38,842
public static boolean isServiceRunning ( Class < ? extends Service > service ) { ActivityManager manager = ( ActivityManager ) QuickUtils . getContext ( ) . getSystemService ( Context . ACTIVITY_SERVICE ) ; for ( ActivityManager . RunningServiceInfo runningServiceInfo : manager . getRunningServices ( Integer . MAX_VALUE ) ) { if ( service . getName ( ) . equals ( runningServiceInfo . service . getClassName ( ) ) ) { return true ; } } return false ; }
Is this service running?
38,843
public static boolean isDebuggable ( ) { boolean debuggable = false ; Context ctx = QuickUtils . getContext ( ) ; try { PackageInfo pinfo = ctx . getPackageManager ( ) . getPackageInfo ( ctx . getPackageName ( ) , PackageManager . GET_SIGNATURES ) ; Signature signatures [ ] = pinfo . signatures ; CertificateFactory cf = CertificateFactory . getInstance ( "X.509" ) ; for ( int i = 0 ; i < signatures . length ; i ++ ) { ByteArrayInputStream stream = new ByteArrayInputStream ( signatures [ i ] . toByteArray ( ) ) ; X509Certificate cert = ( X509Certificate ) cf . generateCertificate ( stream ) ; debuggable = cert . getSubjectX500Principal ( ) . equals ( DEBUG_DN ) ; if ( debuggable ) break ; } } catch ( NameNotFoundException | CertificateException ignored ) { } return debuggable ; }
Is this APK signed or is it a Debug build?
38,844
protected boolean handleImageLoaded ( Bitmap bitmap , Message msg ) { String forUrl = ( String ) imageView . getTag ( ) ; if ( imageUrl . equals ( forUrl ) ) { Bitmap image = bitmap != null || errorDrawable == null ? bitmap : ( ( BitmapDrawable ) errorDrawable ) . getBitmap ( ) ; if ( image != null ) { imageView . setImageBitmap ( image ) ; } return true ; } return false ; }
Override this method if you need custom handler logic . Note that this method can actually be called directly for performance reasons in which case the message will be null
38,845
public MapMaker expiration ( long duration , TimeUnit unit ) { if ( expirationNanos != 0 ) { throw new IllegalStateException ( "expiration time of " + expirationNanos + " ns was already set" ) ; } if ( duration <= 0 ) { throw new IllegalArgumentException ( "invalid duration: " + duration ) ; } this . expirationNanos = unit . toNanos ( duration ) ; useCustomMap = true ; return this ; }
Specifies that each entry should be automatically removed from the map once a fixed duration has passed since the entry s creation .
38,846
@ SuppressWarnings ( "unchecked" ) private static < K , V > ValueReference < K , V > computing ( ) { return ( ValueReference < K , V > ) COMPUTING ; }
Singleton placeholder that indicates a value is being computed .
38,847
public static JSONObject getJSONFromUrlViaPOST ( String url , List < NameValuePair > params ) { InputStream is = null ; JSONObject jObj = null ; String json = "" ; try { DefaultHttpClient httpClient = new DefaultHttpClient ( ) ; HttpPost httpPost = new HttpPost ( url ) ; httpPost . setEntity ( new UrlEncodedFormEntity ( params ) ) ; HttpResponse httpResponse = httpClient . execute ( httpPost ) ; HttpEntity httpEntity = httpResponse . getEntity ( ) ; is = httpEntity . getContent ( ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } try { BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , "iso-8859-1" ) , 8 ) ; StringBuilder sb = new StringBuilder ( ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line + "\n" ) ; } is . close ( ) ; json = sb . toString ( ) ; } catch ( Exception e ) { Log . e ( "Buffer Error" , "Error converting result " + e . toString ( ) ) ; } try { jObj = new JSONObject ( json ) ; } catch ( JSONException e ) { Log . e ( "JSON Parser" , "Error parsing data " + e . toString ( ) ) ; } return jObj ; }
Queries the given URL with a list of params via POST
38,848
public static JSONObject getJSONFromUrlViaGET ( String url ) { JSONObject jObj = null ; StringBuilder builder = new StringBuilder ( ) ; HttpClient client = new DefaultHttpClient ( ) ; HttpGet httpGet = new HttpGet ( url ) ; try { HttpResponse response = client . execute ( httpGet ) ; StatusLine statusLine = response . getStatusLine ( ) ; int statusCode = statusLine . getStatusCode ( ) ; if ( statusCode == 200 ) { HttpEntity entity = response . getEntity ( ) ; InputStream content = entity . getContent ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( content ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { builder . append ( line ) ; } jObj = new JSONObject ( builder . toString ( ) ) ; } else { } } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return jObj ; }
Queries the given URL with a GET request
38,849
public static boolean hasInternetConnection ( ) { ConnectivityManager connectivity = ( ConnectivityManager ) QuickUtils . getContext ( ) . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; if ( connectivity == null ) { return false ; } else { NetworkInfo [ ] info = connectivity . getAllNetworkInfo ( ) ; if ( info != null ) { for ( int i = 0 ; i < info . length ; i ++ ) { if ( info [ i ] . getState ( ) == NetworkInfo . State . CONNECTED ) { return true ; } } } } return false ; }
Checks if the app has connectivity to the Internet
38,850
public static boolean changeWirelessState ( boolean state ) { try { WifiManager wifi = ( WifiManager ) QuickUtils . getContext ( ) . getSystemService ( Context . WIFI_SERVICE ) ; wifi . setWifiEnabled ( state ) ; return true ; } catch ( Exception e ) { return false ; } }
Set wireless connectivity On also this method will need the permissions android . permission . CHANGE_WIFI_STATE and android . permission . ACCESS_WIFI_STATE
38,851
public static String join ( Collection < ? > objectsToJoin , String separator ) { if ( ( objectsToJoin != null ) && ! objectsToJoin . isEmpty ( ) ) { StringBuilder builder = new StringBuilder ( ) ; for ( Object object : objectsToJoin ) { builder . append ( object ) ; builder . append ( separator ) ; } return builder . substring ( 0 , builder . length ( ) - separator . length ( ) ) ; } else { return EMPTY ; } }
Joins all the strings in the list in a single one separated by the separator sequence .
38,852
public static String truncate ( String text , Integer maxCharacters , Boolean truncateWords ) { if ( isNotBlank ( text ) ) { StringBuilder truncatedTextBuilder = new StringBuilder ( ) ; if ( text . length ( ) > maxCharacters ) { if ( truncateWords ) { if ( maxCharacters <= ELLIPSIS . length ( ) ) { truncatedTextBuilder . append ( text . substring ( 0 , maxCharacters ) ) ; } else { truncatedTextBuilder . append ( text . substring ( 0 , maxCharacters - ELLIPSIS . length ( ) ) ) ; truncatedTextBuilder . append ( ELLIPSIS ) ; } } else { List < String > words = Lists . newArrayList ( text . split ( SPACE ) ) ; Iterator < String > it = words . iterator ( ) ; int usedChars = 0 ; Boolean exit = false ; while ( it . hasNext ( ) && ! exit ) { String word = it . next ( ) ; int increment = usedChars == 0 ? word . length ( ) : word . length ( ) + 1 ; if ( ( usedChars + increment ) <= maxCharacters ) { truncatedTextBuilder . append ( usedChars == 0 ? word : SPACE + word ) ; usedChars += increment ; } else { exit = true ; } } } } else { truncatedTextBuilder . append ( text ) ; } return truncatedTextBuilder . toString ( ) ; } return text ; }
Truncate the text adding ... if the truncateWords parameter is true . The ellipsis will be taken into account when counting the amount of characters .
38,853
public static String truncate ( String text , Integer maxCharacters ) { return truncate ( text , maxCharacters , true ) ; }
Truncate the text adding ... . The ellipsis will be taken into account when counting the amount of characters .
38,854
public static Set < String > extractPlaceHolders ( String string ) { Matcher matcher = Pattern . compile ( PLACEHOLDER_PATTERN ) . matcher ( string ) ; Set < String > placeHolders = Sets . newHashSet ( ) ; while ( matcher . find ( ) ) { placeHolders . add ( matcher . group ( 1 ) ) ; } return placeHolders ; }
Extract all the placeholder s names of the string
38,855
public static String toAlphanumeric ( String value ) { return Pattern . compile ( ALPHANUMERIC_PATTERN ) . matcher ( value ) . replaceAll ( "" ) ; }
Transform the received value removing all the not alphanumeric or spaces characters
38,856
public static String getFirstToken ( String string , String token ) { if ( ( string != null ) && string . contains ( token ) ) { return string . split ( token ) [ 0 ] ; } return string ; }
Returns the first token of the string if that string can be split by the token else return the unmodified input string
38,857
public static String wordWrapToTwoLines ( String text , int minLength ) { String wordWrapText = text != null ? text . trim ( ) : null ; if ( ( wordWrapText != null ) && ( wordWrapText . length ( ) > minLength ) ) { int middle = wordWrapText . length ( ) / 2 ; int leftSpaceIndex = wordWrapText . substring ( 0 , middle ) . lastIndexOf ( SPACE ) ; int rightSpaceIndex = wordWrapText . indexOf ( SPACE , middle ) ; int wordWrapIndex = rightSpaceIndex ; if ( ( leftSpaceIndex >= 0 ) && ( ( rightSpaceIndex < 0 ) || ( ( middle - leftSpaceIndex ) < ( rightSpaceIndex - middle ) ) ) ) { wordWrapIndex = leftSpaceIndex ; } if ( wordWrapIndex >= 0 ) { wordWrapText = wordWrapText . substring ( 0 , wordWrapIndex ) + "\n" + wordWrapText . substring ( wordWrapIndex + 1 ) ; } } return wordWrapText ; }
This method word wrap a text to two lines if the text has multiple words and its length is greater than the specified minLength . To do the word wrap the white space closest to the middle of the string is replaced by a \ n character
38,858
protected void onDraw ( Canvas canvas ) { if ( adaptedImage != null ) canvas . drawBitmap ( adaptedImage , 0 , 0 , paint ) ; }
Draws the view if the adapted image is not null
38,859
public void handleScroll ( float distY ) { if ( getHeight ( ) > 0 && originalImage != null ) { if ( scrollY <= originalImage . getHeight ( ) - getHeight ( ) ) { adaptedImage = Bitmap . createBitmap ( originalImage , 0 , ( int ) - distY , screenWidth , getHeight ( ) ) ; invalidate ( ) ; } } }
Handle an external scroll and render the image by switching it by a distance
38,860
public static void load ( String imageUrl , ImageView imageView ) { load ( imageUrl , imageView , new ImageLoaderHandler ( imageView , imageUrl ) , null , null ) ; }
Triggers the image loader for the given image and view . The image loading will be performed concurrently to the UI main thread using a fixed size thread pool . The loaded image will be posted back to the given ImageView upon completion .
38,861
public void run ( ) { Bitmap bitmap = imageCache . getBitmap ( imageUrl ) ; if ( bitmap == null ) { bitmap = downloadImage ( ) ; } notifyImageLoaded ( imageUrl , bitmap ) ; }
The job method run on a worker thread . It will first query the image cache and on a miss download the image from the Web .
38,862
protected Bitmap downloadImage ( ) { int timesTried = 1 ; while ( timesTried <= numRetries ) { try { byte [ ] imageData = retrieveImageData ( ) ; if ( imageData != null ) { imageCache . put ( imageUrl , imageData ) ; } else { break ; } return BitmapFactory . decodeByteArray ( imageData , 0 , imageData . length ) ; } catch ( Throwable e ) { QuickUtils . log . w ( "download for " + imageUrl + " failed (attempt " + timesTried + ")" ) ; e . printStackTrace ( ) ; SystemClock . sleep ( DEFAULT_RETRY_HANDLER_SLEEP_TIME ) ; timesTried ++ ; } } return null ; }
after each and every download
38,863
public static String deviceResolution ( ) { DisplayMetrics metrics = QuickUtils . getContext ( ) . getResources ( ) . getDisplayMetrics ( ) ; return String . valueOf ( metrics . widthPixels ) + "x" + metrics . heightPixels ; }
Current device resolution
38,864
public static String join ( Collection < ? > collection , String delimiter ) { if ( collection == null || collection . isEmpty ( ) ) { return EMPTY_STRING ; } else if ( delimiter == null ) { delimiter = EMPTY_STRING ; } StringBuilder builder = new StringBuilder ( ) ; Iterator < ? > it = collection . iterator ( ) ; while ( it . hasNext ( ) ) { builder . append ( it . next ( ) ) . append ( delimiter ) ; } int length = builder . length ( ) ; builder . delete ( length - delimiter . length ( ) , length ) ; return builder . toString ( ) ; }
Joins a Collection of typed objects using their toString method separated by delimiter
38,865
public static List < String > getWords ( int count , boolean startLorem ) { LinkedList < String > wordList = new LinkedList < String > ( ) ; if ( startLorem ) { if ( count > COMMON_WORDS . length ) { wordList . addAll ( Arrays . asList ( COMMON_WORDS ) ) ; } else { for ( int i = 0 ; i < count ; i ++ ) { wordList . add ( COMMON_WORDS [ i ] ) ; } } } for ( int i = wordList . size ( ) ; i < count ; i ++ ) { wordList . add ( QuickUtils . math . getRandomPosition ( DICTIONARY ) ) ; } return wordList ; }
Returns a list of words .
38,866
public static String implode ( String [ ] inputArr , String delimiter ) { String implodedStr = "" ; implodedStr += inputArr [ 0 ] ; for ( int i = 1 ; i < inputArr . length ; i ++ ) { implodedStr += delimiter ; implodedStr += inputArr [ i ] ; } return implodedStr ; }
Implodes an array into a string Similar to PHP implode function
38,867
public static String capitalize ( String input ) { char [ ] stringArray = input . toCharArray ( ) ; stringArray [ 0 ] = Character . toUpperCase ( stringArray [ 0 ] ) ; return new String ( stringArray ) ; }
Capitalize first word in a string
38,868
public static int e ( String message , Throwable throwable ) { return logger ( QuickUtils . ERROR , message , throwable ) ; }
Sends an ERROR log message
38,869
public static int i ( String message , Throwable throwable ) { return logger ( QuickUtils . INFO , message , throwable ) ; }
Sends an INFO log message .
38,870
public static int v ( String message , Throwable throwable ) { return logger ( QuickUtils . VERBOSE , message , throwable ) ; }
Sends a VERBBOSE log message .
38,871
public static int w ( String message , Throwable throwable ) { return logger ( QuickUtils . WARN , message , throwable ) ; }
Sends a WARNING log message .
38,872
public static int d ( String message , Throwable throwable ) { return logger ( QuickUtils . DEBUG , message , throwable ) ; }
Sends a DEBUG log message and log the exception .
38,873
private static int logger ( int level , String message , Throwable throwable ) { if ( QuickUtils . shouldShowLogs ( ) ) { switch ( level ) { case QuickUtils . DEBUG : return android . util . Log . d ( QuickUtils . TAG , message , throwable ) ; case QuickUtils . VERBOSE : return android . util . Log . v ( QuickUtils . TAG , message , throwable ) ; case QuickUtils . INFO : return android . util . Log . i ( QuickUtils . TAG , message , throwable ) ; case QuickUtils . WARN : return android . util . Log . w ( QuickUtils . TAG , message , throwable ) ; case QuickUtils . ERROR : return android . util . Log . e ( QuickUtils . TAG , message , throwable ) ; default : break ; } } return - 1 ; }
Private Logger function to handle Log calls
38,874
public static LocationModel getLocationByCoordinates ( Double latitude , Double longitude ) { try { Geocoder geocoder ; List < Address > addresses ; geocoder = new Geocoder ( QuickUtils . getContext ( ) ) ; addresses = geocoder . getFromLocation ( latitude , longitude , 1 ) ; LocationModel locationModel = new LocationModel ( ) ; locationModel . latitude = latitude ; locationModel . longitude = longitude ; try { locationModel . address = addresses . get ( 0 ) . getAddressLine ( 0 ) ; } catch ( Exception ex ) { QuickUtils . log . e ( "empty address" ) ; } try { locationModel . city = addresses . get ( 0 ) . getAddressLine ( 1 ) ; } catch ( Exception ex ) { QuickUtils . log . e ( "empty city" ) ; } try { locationModel . country = addresses . get ( 0 ) . getAddressLine ( 2 ) ; } catch ( Exception ex ) { QuickUtils . log . e ( "empty country" ) ; } return locationModel ; } catch ( IOException e ) { QuickUtils . log . e ( "empty location" ) ; return new LocationModel ( ) ; } }
Gets the location by Coordinates
38,875
public void setDominantMeasurement ( int dominantMeasurement ) { if ( dominantMeasurement != MEASUREMENT_HEIGHT && dominantMeasurement != MEASUREMENT_WIDTH ) { throw new IllegalArgumentException ( "Invalid measurement type." ) ; } this . dominantMeasurement = dominantMeasurement ; requestLayout ( ) ; }
Set the dominant measurement for the aspect ratio .
38,876
public static long getTimeSinceMidnight ( ) { Calendar c = Calendar . getInstance ( ) ; long now = c . getTimeInMillis ( ) ; c . set ( Calendar . HOUR_OF_DAY , 0 ) ; c . set ( Calendar . MINUTE , 0 ) ; c . set ( Calendar . SECOND , 0 ) ; c . set ( Calendar . MILLISECOND , 0 ) ; return now - c . getTimeInMillis ( ) ; }
Miliseconds since midnight
38,877
public static java . util . Date getDayAsDate ( int day ) { Calendar cal = Calendar . getInstance ( ) ; cal . add ( Calendar . DATE , day ) ; return cal . getTime ( ) ; }
Gets the desired day as a Date
38,878
public static String getNumberWithSuffix ( int number ) { int j = number % 10 ; if ( j == 1 && number != 11 ) { return number + "st" ; } if ( j == 2 && number != 12 ) { return number + "nd" ; } if ( j == 3 && number != 13 ) { return number + "rd" ; } return number + "th" ; }
Get number with a suffix
38,879
public static String convertMonth ( int month , boolean useShort ) { String monthStr ; switch ( month ) { default : monthStr = "January" ; break ; case Calendar . FEBRUARY : monthStr = "February" ; break ; case Calendar . MARCH : monthStr = "March" ; break ; case Calendar . APRIL : monthStr = "April" ; break ; case Calendar . MAY : monthStr = "May" ; break ; case Calendar . JUNE : monthStr = "June" ; break ; case Calendar . JULY : monthStr = "July" ; break ; case Calendar . AUGUST : monthStr = "August" ; break ; case Calendar . SEPTEMBER : monthStr = "September" ; break ; case Calendar . OCTOBER : monthStr = "October" ; break ; case Calendar . NOVEMBER : monthStr = "November" ; break ; case Calendar . DECEMBER : monthStr = "December" ; break ; } if ( useShort ) monthStr = monthStr . substring ( 0 , 3 ) ; return monthStr ; }
Converts a month by number to full text
38,880
public static void getBitmapByImageURL ( String imageURL , final OnEventListener callback ) { new DownloadImageTask < Bitmap > ( imageURL , new OnEventListener < Bitmap > ( ) { public void onSuccess ( Bitmap bitmap ) { callback . onSuccess ( bitmap ) ; } public void onFailure ( Exception e ) { callback . onFailure ( e ) ; } } ) . execute ( ) ; }
Get a bitmap by a given URL
38,881
public static void storeImage ( Bitmap image , File pictureFile ) { if ( pictureFile == null ) { QuickUtils . log . d ( "Error creating media file, check storage permissions: " ) ; return ; } try { FileOutputStream fos = new FileOutputStream ( pictureFile ) ; image . compress ( Bitmap . CompressFormat . PNG , 90 , fos ) ; fos . close ( ) ; } catch ( FileNotFoundException e ) { QuickUtils . log . d ( "File not found: " + e . getMessage ( ) ) ; } catch ( IOException e ) { QuickUtils . log . d ( "Error accessing file: " + e . getMessage ( ) ) ; } }
Stores an image on the storage
38,882
@ SuppressWarnings ( "deprecation" ) @ SuppressLint ( "NewApi" ) public static int getScreenHeight ( Activity context ) { Display display = context . getWindowManager ( ) . getDefaultDisplay ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR2 ) { Point size = new Point ( ) ; display . getSize ( size ) ; return size . y ; } return display . getHeight ( ) ; }
Get the screen height .
38,883
@ SuppressWarnings ( "deprecation" ) @ SuppressLint ( "NewApi" ) public static int getScreenWidth ( Activity context ) { Display display = context . getWindowManager ( ) . getDefaultDisplay ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR2 ) { Point size = new Point ( ) ; display . getSize ( size ) ; return size . x ; } return display . getWidth ( ) ; }
Get the screen width .
38,884
private void sanitizeDiskCache ( ) { File [ ] cachedFiles = new File ( diskCacheDirectory ) . listFiles ( ) ; if ( cachedFiles == null ) { return ; } for ( File f : cachedFiles ) { long lastModified = f . lastModified ( ) ; Date now = new Date ( ) ; long ageInMinutes = ( ( now . getTime ( ) - lastModified ) / ( 1000 * 60 ) ) ; if ( ageInMinutes >= expirationInMinutes ) { Log . d ( name , "DISK cache expiration for file " + f . toString ( ) ) ; f . delete ( ) ; } } }
Sanitize disk cache . Remove files which are older than expirationInMinutes .
38,885
public boolean enableDiskCache ( Context context , int storageDevice ) { Context appContext = context . getApplicationContext ( ) ; String rootDir = null ; if ( storageDevice == DISK_CACHE_SDCARD && Environment . MEDIA_MOUNTED . equals ( Environment . getExternalStorageState ( ) ) ) { rootDir = Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) + "/Android/data/" + appContext . getPackageName ( ) + "/cache" ; } else { File internalCacheDir = appContext . getCacheDir ( ) ; if ( internalCacheDir == null ) { return ( isDiskCacheEnabled = false ) ; } rootDir = internalCacheDir . getAbsolutePath ( ) ; } setRootDir ( rootDir ) ; File outFile = new File ( diskCacheDirectory ) ; if ( outFile . mkdirs ( ) ) { File nomedia = new File ( diskCacheDirectory , ".nomedia" ) ; try { nomedia . createNewFile ( ) ; } catch ( IOException e ) { Log . e ( LOG_TAG , "Failed creating .nomedia file" ) ; } } isDiskCacheEnabled = outFile . exists ( ) ; if ( ! isDiskCacheEnabled ) { Log . w ( LOG_TAG , "Failed creating disk cache directory " + diskCacheDirectory ) ; } else { sanitizeDiskCache ( ) ; } return isDiskCacheEnabled ; }
Enable caching to the phone s internal storage or SD card .
38,886
@ SuppressWarnings ( "unchecked" ) public synchronized ValT get ( Object elementKey ) { KeyT key = ( KeyT ) elementKey ; ValT value = cache . get ( key ) ; if ( value != null ) { Log . d ( name , "MEM cache hit for " + key . toString ( ) ) ; return value ; } File file = getFileForKey ( key ) ; if ( file . exists ( ) ) { long lastModified = file . lastModified ( ) ; Date now = new Date ( ) ; long ageInMinutes = ( ( now . getTime ( ) - lastModified ) / ( 1000 * 60 ) ) ; if ( ageInMinutes >= expirationInMinutes ) { Log . d ( name , "DISK cache expiration for file " + file . toString ( ) ) ; file . delete ( ) ; return null ; } Log . d ( name , "DISK cache hit for " + key . toString ( ) ) ; try { value = readValueFromDisk ( file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } if ( value == null ) { return null ; } cache . put ( key , value ) ; return value ; } return null ; }
Reads a value from the cache by probing the in - memory cache and if enabled and the in - memory probe was a miss the disk cache .
38,887
@ SuppressWarnings ( "unchecked" ) public synchronized boolean containsKey ( Object key ) { return cache . containsKey ( key ) || ( isDiskCacheEnabled && getFileForKey ( ( KeyT ) key ) . exists ( ) ) ; }
Checks if a value is present in the cache . If the disk cached is enabled this will also check whether the value has been persisted to disk .
38,888
public static < T > T read ( String key , Class < T > classOfT ) throws Exception { String json = cache . getString ( key ) . getString ( ) ; T value = new Gson ( ) . fromJson ( json , classOfT ) ; if ( value == null ) { throw new NullPointerException ( ) ; } return value ; }
Get an object from Reservoir with the given key . This a blocking IO operation .
38,889
public static View blink ( View view , int duration , int offset ) { android . view . animation . Animation anim = new AlphaAnimation ( 0.0f , 1.0f ) ; anim . setDuration ( duration ) ; anim . setStartOffset ( offset ) ; anim . setRepeatMode ( android . view . animation . Animation . REVERSE ) ; anim . setRepeatCount ( android . view . animation . Animation . INFINITE ) ; view . startAnimation ( anim ) ; return view ; }
Make a View Blink for a desired duration
38,890
public void onDraw ( Canvas canvas ) { if ( animationOn ) { if ( angleRecalculate ( new Date ( ) . getTime ( ) ) ) { this . setRotation ( angle1 ) ; } } else { this . setRotation ( angle1 ) ; } super . onDraw ( canvas ) ; if ( animationOn ) { this . invalidate ( ) ; } }
onDraw override . If animation is on view is invalidated after each redraw to perform recalculation on every loop of UI redraw
38,891
public void setPhysical ( float inertiaMoment , float alpha , float mB ) { this . inertiaMoment = inertiaMoment >= 0 ? inertiaMoment : this . INERTIA_MOMENT_DEFAULT ; this . alpha = alpha >= 0 ? alpha : ALPHA_DEFAULT ; this . mB = mB >= 0 ? mB : MB_DEFAULT ; }
Use this to set physical properties . Negative values will be replaced by default values
38,892
public void rotationUpdate ( final float angleNew , final boolean animate ) { if ( animate ) { if ( Math . abs ( angle0 - angleNew ) > ANGLE_DELTA_THRESHOLD ) { angle0 = angleNew ; this . invalidate ( ) ; } animationOn = true ; } else { angle1 = angleNew ; angle2 = angleNew ; angle0 = angleNew ; angleLastDrawn = angleNew ; this . invalidate ( ) ; animationOn = false ; } }
Use this to set new magnetic field angle at which image should rotate
38,893
protected boolean angleRecalculate ( final long timeNew ) { float deltaT1 = ( timeNew - time1 ) / 1000f ; if ( deltaT1 > TIME_DELTA_THRESHOLD ) { deltaT1 = TIME_DELTA_THRESHOLD ; time1 = timeNew + Math . round ( TIME_DELTA_THRESHOLD * 1000 ) ; } float deltaT2 = ( time1 - time2 ) / 1000f ; if ( deltaT2 > TIME_DELTA_THRESHOLD ) { deltaT2 = TIME_DELTA_THRESHOLD ; } float koefI = inertiaMoment / deltaT1 / deltaT2 ; float koefAlpha = alpha / deltaT1 ; float koefk = mB * ( float ) ( Math . sin ( Math . toRadians ( angle0 ) ) * Math . cos ( Math . toRadians ( angle1 ) ) - ( Math . sin ( Math . toRadians ( angle1 ) ) * Math . cos ( Math . toRadians ( angle0 ) ) ) ) ; float angleNew = ( koefI * ( angle1 * 2f - angle2 ) + koefAlpha * angle1 + koefk ) / ( koefI + koefAlpha ) ; angle2 = angle1 ; angle1 = angleNew ; time2 = time1 ; time1 = timeNew ; if ( Math . abs ( angleLastDrawn - angle1 ) < ANGLE_DELTA_THRESHOLD ) { return false ; } else { angleLastDrawn = angle1 ; return true ; } }
Recalculate angles using equation of dipole circular motion
38,894
public static void sendEmail ( String email , String subject , String emailBody ) { Intent emailIntent = new Intent ( Intent . ACTION_SEND ) ; emailIntent . setType ( "message/rfc822" ) ; emailIntent . putExtra ( Intent . EXTRA_EMAIL , new String [ ] { email } ) ; emailIntent . putExtra ( Intent . EXTRA_SUBJECT , subject ) ; emailIntent . putExtra ( Intent . EXTRA_TEXT , emailBody ) ; emailIntent . setFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; try { QuickUtils . getContext ( ) . startActivity ( emailIntent ) ; } catch ( android . content . ActivityNotFoundException ex ) { QuickUtils . system . toast ( "There are no email clients installed." ) ; } }
Share via Email
38,895
private static void shareMethod ( String message , String activityInfoName ) { Intent shareIntent = new Intent ( Intent . ACTION_SEND ) ; shareIntent . setType ( "text/plain" ) ; shareIntent . putExtra ( Intent . EXTRA_TEXT , message ) ; PackageManager pm = QuickUtils . getContext ( ) . getPackageManager ( ) ; List < ResolveInfo > activityList = pm . queryIntentActivities ( shareIntent , 0 ) ; for ( final ResolveInfo app : activityList ) { if ( ( app . activityInfo . name ) . contains ( activityInfoName ) ) { final ActivityInfo activity = app . activityInfo ; final ComponentName name = new ComponentName ( activity . applicationInfo . packageName , activity . name ) ; shareIntent . addCategory ( Intent . CATEGORY_LAUNCHER ) ; shareIntent . setFlags ( Intent . FLAG_ACTIVITY_NEW_TASK | Intent . FLAG_ACTIVITY_RESET_TASK_IF_NEEDED ) ; shareIntent . setComponent ( name ) ; QuickUtils . getContext ( ) . startActivity ( shareIntent ) ; break ; } } }
Private method that handles facebook and twitter sharing
38,896
public static void genericSharing ( String subject , String message ) { Intent intent = new Intent ( Intent . ACTION_SEND ) ; intent . setType ( "text/plain" ) ; intent . putExtra ( Intent . EXTRA_TEXT , message ) ; intent . putExtra ( Intent . EXTRA_SUBJECT , subject ) ; intent . setFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; QuickUtils . getContext ( ) . startActivity ( intent ) ; }
Generic method for sharing that Deliver some data to someone else . Who the data is being delivered to is not specified ; it is up to the receiver of this action to ask the user where the data should be sent .
38,897
public static boolean isSDCardAvailable ( ) { boolean mExternalStorageAvailable = false ; String state = Environment . getExternalStorageState ( ) ; if ( Environment . MEDIA_MOUNTED . equals ( state ) ) { mExternalStorageAvailable = true ; } else if ( Environment . MEDIA_MOUNTED_READ_ONLY . equals ( state ) ) { mExternalStorageAvailable = true ; } else { mExternalStorageAvailable = false ; } return mExternalStorageAvailable ; }
Check if the SD Card is Available
38,898
public static boolean isSDCardWritable ( ) { boolean mExternalStorageWriteable = false ; String state = Environment . getExternalStorageState ( ) ; if ( Environment . MEDIA_MOUNTED . equals ( state ) ) { mExternalStorageWriteable = true ; } else if ( Environment . MEDIA_MOUNTED_READ_ONLY . equals ( state ) ) { mExternalStorageWriteable = false ; } else { mExternalStorageWriteable = false ; } return mExternalStorageWriteable ; }
Check if the SD Card is writable
38,899
public static boolean checkIfFileExists ( String filePath ) { File file = new File ( filePath ) ; return ( file . exists ( ) ? true : false ) ; }
Check if file exists on SDCard or not