Thursday, February 27, 2014

Seven Switch

iOS7 style drop in replacement for UISwitch
Animation
Default

Donate Bitcoin

If you're using SevenSwitch in an app or for some other reason consider throwing me some coin.
1GuFb1y7xEmKiD6XD3tGEJBriYJ2hXp8zY

Usage

To use it, add SevenSwitch.h and SevenSwitch.m files to your project and add the QuartzCore framework to your project.
Initializing and adding the switch to the screen
SevenSwitch *mySwitch = [[SevenSwitch alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
[self.view addSubview:mySwitch];
When the user manipulates the switch control ("flips" it) a UIControlEventValueChanged event is generated.
[mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
You can set images for the on/off states
mySwitch.offImage = [UIImage imageNamed:@"cross.png"];
mySwitch.onImage = [UIImage imageNamed:@"check.png"];
You can also customize the switches colors
mySwitch.thumbTintColor = [UIColor colorWithRed:0.19f green:0.23f blue:0.33f alpha:1.00f];
mySwitch.activeColor = [UIColor colorWithRed:0.07f green:0.09f blue:0.11f alpha:1.00f];
mySwitch.inactiveColor = [UIColor colorWithRed:0.07f green:0.09f blue:0.11f alpha:1.00f];
mySwitch.onTintColor = [UIColor colorWithRed:0.45f green:0.58f blue:0.67f alpha:1.00f];
mySwitch.borderColor = [UIColor clearColor];
mySwitch.shadowColor = [UIColor blackColor];
You can resize the switch frame to whatever you like to make fatter/skinnier controls
mySwitch.frame = CGRectMake(0, 0, 100, 50);
You can turn off the rounded look by setting the isRounded property to NO
mySwitch.isRounded = NO;

Requirements

SevenSwitch requires iOS 5.0 and above.

Download: https://github.com/bvogelzang/SevenSwitch/archive/master.zip

Sunday, February 23, 2014

JD Status Bar Notification

Show messages on top of the status bar. Customizable colors, font and animation. Supports progress display and can show an activity indicator. iOS 7 ready. iOS6 support. Please open a Github issue, if you think anything is missing or wrong.
Animation
Screenshots

Installation

Cocoapods:

pod 'JDStatusBarNotification'
(For infos on cocoapods, have a look at the cocoapods website)

Manually:

  1. Drag the JDStatusBarNotification/JDStatusBarNotification folder into your project.
  2. Add #include "JDStatusBarNotification.h", where you want to use it

Usage

JDStatusBarNotification is a singleton. You don't need to initialize it anywhere. Just use the following class methods:

Showing a notification

+ (JDStatusBarView*)showWithStatus:(NSString *)status;
+ (JDStatusBarView*)showWithStatus:(NSString *)status
                      dismissAfter:(NSTimeInterval)timeInterval;
The return value will be the notification view. You can just ignore it, but if you need further customization, this is where you can access the view.

Dismissing a notification

+ (void)dismiss;
+ (void)dismissAfter:(NSTimeInterval)delay;

Showing progress

Progress animation
+ (void)showProgress:(CGFloat)progress;  // Range: 0.0 - 1.0

Showing activity

Activity screenshot
+ (void)showActivityIndicator:(BOOL)show
               indicatorStyle:(UIActivityIndicatorViewStyle)style;

Showing a notification with alternative styles

Included styles:

Use them with the following methods:
+ (JDStatusBarView*)showWithStatus:(NSString *)status
                         styleName:(NSString*)styleName;

+ (JDStatusBarView*)showWithStatus:(NSString *)status
                      dismissAfter:(NSTimeInterval)timeInterval
                         styleName:(NSString*)styleName;
To present a notification using a custom style, use the identifier you specified in addStyleNamed:prepare:. See Customization below.

Beware

@goelv informed me, that his app got rejected because of a status bar overlay (for violating 10.1/10.3). So don't overuse it. Although this is the first case I heard of. I even shipped an App myself using this class. It had no problems.

Customization

+ (void)setDefaultStyle:(JDPrepareStyleBlock)prepareBlock;

+ (NSString*)addStyleNamed:(NSString*)identifier
                   prepare:(JDPrepareStyleBlock)prepareBlock;
The prepareBlock gives you a copy of the default style, which can be modified as you like:
[JDStatusBarNotification addStyleNamed:<#identifier#>
                               prepare:^JDStatusBarStyle*(JDStatusBarStyle *style) {

                                   // main properties
                                   style.barColor = <#color#>;
                                   style.textColor = <#color#>;
                                   style.font = <#font#>;

                                   // advanced properties
                                   style.animationType = <#type#>;
                                   style.textShadow = <#shadow#>;
                                   style.textVerticalPositionAdjustment = <#adjustment#>;

                                   // progress bar
                                   style.progressBarColor = <#color#>;
                                   style.progressBarHeight = <#height#>;
                                   style.progressBarPosition = <#position#>;

                                   return style;
                               }];

Animation Types

  • JDStatusBarAnimationTypeNone
  • JDStatusBarAnimationTypeMove
  • JDStatusBarAnimationTypeBounce
  • JDStatusBarAnimationTypeFade

Progress Bar Positions

  • JDStatusBarProgressBarPositionBottom
  • JDStatusBarProgressBarPositionCenter
  • JDStatusBarProgressBarPositionTop
  • JDStatusBarProgressBarPositionBelow
  • JDStatusBarProgressBarPositionNavBar
Download: https://github.com/jaydee3/JDStatusBarNotification/archive/master.zip

Thursday, February 20, 2014

Android Notification LED sample

Note : You should lock(screen) the phone before run this project(via android IDE) , because notification LED will be highlighted only when screen is off

Source SVN:LEDNotification 
Zipped Source:LEDNotification 
 
  public class LEDNotification extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  for (int i = 0; i < 8; i++) {
   notif.cancel(1); // clear previous notification 
   final Notification notification = new Notification();
   if (i == 0){
    notification.ledARGB = Color.MAGENTA;
   }else if (i == 1){
    notification.ledARGB = Color.BLUE;
   }else if (i == 2){
    notification.ledARGB = Color.CYAN;
   }else if (i == 3){
    notification.ledARGB = Color.GRAY;
   }else if (i == 4){
    notification.ledARGB = Color.GREEN;
   }else if (i == 5){
    notification.ledARGB = Color.RED;
   }else if (i == 6){
    notification.ledARGB = Color.WHITE;
   }else if (i == 7){
    notification.ledARGB = Color.YELLOW;
   }
   notification.ledOnMS = 1000;
   notification.flags |= Notification.FLAG_SHOW_LIGHTS;
   notif.notify(1, notification);
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
  }

 }

 

} 
No Special permission required for this project (LED Notification)

Open File Chooser With Camera Option In Webview File Option


File chooser with camera option Open link in webview browser Click on file option webview selected capture image


In this example:

   1.  Opening url in webview and show progress for particular page.

   2.  Show file chooser for Webform file option.

   3.  Show Camera option in file chooser, capture image from camera and store in sdcard and select image for file option.

   4.  For an url click open new activity.

   5.  Open link from webview browser to new browser.

   6.  Open link from webview browser to webview browser.


FILE : ShowWebView.java


Code explanation defined as comments in code.

package com.androidexample.webview;
import java.io.File;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;
public class ShowWebView extends Activity {
    //private Button button;
    private WebView webView;
    final Activity activity = this;
    public Uri imageUri;
     
    private static final int FILECHOOSER_RESULTCODE   = 2888;
    private ValueCallback<Uri> mUploadMessage;
    private Uri mCapturedImageURI = null;
     
    
    public void onCreate(Bundle savedInstanceState) {
         
        super.onCreate(savedInstanceState);
         
        setContentView(R.layout.show_web_view);
         
        //Get webview
        webView = (WebView) findViewById(R.id.webView1);
         
        // Define url that will open in webview
        String webViewUrl = "http://www.androidexample.com/media/webview/details.html";
         
            
         
        // Javascript inabled on webview 
        webView.getSettings().setJavaScriptEnabled(true);
         
        // Other webview options
        webView.getSettings().setLoadWithOverviewMode(true);
         
        //webView.getSettings().setUseWideViewPort(true);
         
        //Other webview settings
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setPluginState(PluginState.ON);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setSupportZoom(true);
         
        //Load url in webview
        webView.loadUrl(webViewUrl);
         
        // Define Webview manage classes
        startWebView();
         
    }
     
    private void startWebView() {
         
         
         
        // Create new webview Client to show progress dialog
        // Called When opening a url or click on link
        // You can create external class extends with WebViewClient
        // Taking WebViewClient as inner class
         
        webView.setWebViewClient(new WebViewClient() {     
            ProgressDialog progressDialog;
          
            //If you will not use this method url links are open in new brower not in webview
            public boolean shouldOverrideUrlLoading(WebView view, String url) {             
                 
                // Check if Url contains ExternalLinks string in url
                // then open url in new browser
                // else all webview links will open in webview browser
                if(url.contains("google")){
                     
                    // Could be cleverer and use a regex
                    //Open links in new browser
                    view.getContext().startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                     
                    // Here we can open new activity
                     
                    return true;
                     
                } else {
                     
                    // Stay within this webview and load url
                    view.loadUrl(url);
                    return true;
                }
                   
            }
             
             
             
            //Show loader on url load
            public void onLoadResource (WebView view, String url) {
             
                // if url contains string androidexample
                // Then show progress  Dialog
                if (progressDialog == null && url.contains("androidexample")
                        ) {
                     
                    // in standard case YourActivity.this
                    progressDialog = new ProgressDialog(ShowWebView.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }
             
            // Called when all page resources loaded
            public void onPageFinished(WebView view, String url) {
                 
                try{
                    // Close progressDialog
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                }catch(Exception exception){
                    exception.printStackTrace();
                }
            }
            
        });
          
           
        // You can create external class extends with WebChromeClient
        // Taking WebViewClient as inner class
        // we will define openFileChooser for select file from camera or sdcard
         
        webView.setWebChromeClient(new WebChromeClient() {
             
            // openFileChooser for Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){ 
                
                // Update message
                mUploadMessage = uploadMsg;
                 
                try{   
                 
                    // Create AndroidExampleFolder at sdcard
                     
                    File imageStorageDir = new File(
                                           Environment.getExternalStoragePublicDirectory(
                                           Environment.DIRECTORY_PICTURES)
                                           , "AndroidExampleFolder");
                                            
                    if (!imageStorageDir.exists()) {
                        // Create AndroidExampleFolder at sdcard
                        imageStorageDir.mkdirs();
                    }
                     
                    // Create camera captured image file path and name
                    File file = new File(
                                    imageStorageDir + File.separator + "IMG_"
                                    + String.valueOf(System.currentTimeMillis())
                                    + ".jpg");
                                     
                    mCapturedImageURI = Uri.fromFile(file);
                     
                    // Camera capture image intent
                    final Intent captureIntent = new Intent(
                                                  android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                                   
                    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                    
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("image/*");
                     
                    // Create file chooser intent
                    Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
                     
                    // Set camera intent to file chooser
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                                           , new Parcelable[] { captureIntent });
                     
                    // On select image call onActivityResult method of activity
                    startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
                     
                  }
                 catch(Exception e){
                     Toast.makeText(getBaseContext(), "Exception:"+e,
                                Toast.LENGTH_LONG).show();
                 }
                 
            }
             
            // openFileChooser for Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg){
                openFileChooser(uploadMsg, "");
            }
             
            //openFileChooser for other Android versions
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                       String acceptType,
                                       String capture) {
                                        
                openFileChooser(uploadMsg, acceptType);
            }
            // The webPage has 2 filechoosers and will send a
            // console message informing what action to perform,
            // taking a photo or updating the file
             
            public boolean onConsoleMessage(ConsoleMessage cm) { 
                   
                onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
                return true;
            }
             
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                //Log.d("androidruntime", "Show console messages, Used for debugging: " + message);
                 
            }
        });   // End setWebChromeClient
          
    }
     
     
     
    // Return here when file selected from camera or from SDcard
     
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, 
                                       Intent intent) {
         
     if(requestCode==FILECHOOSER_RESULTCODE) 
     
        
            if (null == this.mUploadMessage) {
                return;
            }
           Uri result=null;
            
           try{
                if (resultCode != RESULT_OK) {
                     
                    result = null;
                     
                } else {
                     
                    // retrieve from the private variable if the intent is null
                    result = intent == null ? mCapturedImageURI : intent.getData();
                }
            }
            catch(Exception e)
            {
                Toast.makeText(getApplicationContext(), "activity :"+e,
                 Toast.LENGTH_LONG).show();
            }
             
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
      
     }
         
    }
     
    // Open previous opened link from history on webview when back button pressed
     
    @Override
    // Detect when the back button is pressed
    public void onBackPressed() {
     
        if(webView.canGoBack()) {
         
            webView.goBack();
             
        } else {
            // Let the system handle the back button
            super.onBackPressed();
        }
    }
}

FILE : show_web_view.xml


Define webview inside this file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
       
   <WebView 
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>      
</LinearLayout>


FILE : AndroidManifest.xml


Define sdcard and camera permission.

<?xml version="1.0" encoding="utf-8"?>
    package="com.androidexample.webview"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
         
        <activity
            android:label="@string/app_name"
            android:name=".ShowWebView"
            android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Download:
  Download Open File Chooser With Camera Option In Webview File Option