Sunday, July 29, 2012

Android: Playing with System Settings

Probably if you are developing an Android Application, there will be numerous situations which requires you to modify some of the default settings of the Android system. But how to do that? Therefore...

I have created a simple app that will allow you to modify the System settings.
The above are some of the screen captures of the Android Application.

So here comes the source files...
AndroidManifest.xml (Take note of the user permissions.)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zcs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SimpleSystemSettingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The main layout file - main.xml
<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />


    <CheckBox
        android:id="@+id/chkBoxBrightness"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/chkBox" />

    <SeekBar
        android:id="@+id/seekBarBrightness"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:max="255" />

</LinearLayout>

The main application file - SimpleSystemSettingActivity.java
package com.zcs;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;

public class SimpleSystemSettingActivity extends Activity {
 private SeekBar seekBarBrightness;
 private CheckBox chkBoxBrightness;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Grab the components from the main view
        //and assign them to the respective variables
        seekBarBrightness = 
          (SeekBar)findViewById(R.id.seekBarBrightness);
        chkBoxBrightness = 
          (CheckBox)findViewById(R.id.chkBoxBrightness);
        
        //Adding the value change listeners for the
        //components
        seekBarBrightness.setOnSeekBarChangeListener(
          new seekBarChangedListener());
        chkBoxBrightness.setOnCheckedChangeListener(
          new checkBoxChangeListener());
        
        //Call the function updateSettings()
        updateSettings();
    }
    
    //This function will be used to update/retrieve the
    //values of the Screen Brightness and Screen Brightness
    //mode and assign the values to the respective components
    private void updateSettings()
    {
     try {
      //Grabbing the values of the Screen Brightness and 
      //Screen Brightness mode
   int screenBrightnessMode = Settings.System.getInt(
     getContentResolver(), 
     Settings.System.SCREEN_BRIGHTNESS_MODE);
   int screenBrightness = Settings.System.getInt(
     getContentResolver(), 
     Settings.System.SCREEN_BRIGHTNESS);
   
   seekBarBrightness.setProgress(screenBrightness);
   //If the Screen Brightness Mode is Automatic
   if(screenBrightnessMode == 
     Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)
   {
    //we will hide the seek bar and check the 
    //check box
    chkBoxBrightness.setChecked(true);
    seekBarBrightness.setVisibility(View.INVISIBLE);
   }else{
    //else we will show it and uncheck the
    //check box
    chkBoxBrightness.setChecked(false);
    seekBarBrightness.setVisibility(View.VISIBLE);
   }
  } catch (SettingNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
    
    //Change Listener for the seekbar for brightness
    private class seekBarChangedListener implements 
     SeekBar.OnSeekBarChangeListener {
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
         int currentProgress = progress;
         
         //set the screen brightness into the System
         Settings.System.putInt(getContentResolver(), 
           Settings.System.SCREEN_BRIGHTNESS, 
           currentProgress);
         updateSettings();
        }
        public void onStartTrackingTouch(SeekBar seekBar) {}
        public void onStopTrackingTouch(SeekBar seekBar) {}
    }

    //Change Listener for the check bos for brightness mode
    private class checkBoxChangeListener implements 
     CheckBox.OnCheckedChangeListener
    {
  @Override
  public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
   boolean checkValue = isChecked;
   int intCheckValue = (checkValue)?1:0;
         //set the screen brightness mode into the System
   if(intCheckValue == 
     Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)
   {
          Settings.System.putInt(getContentResolver(), 
            Settings.System.SCREEN_BRIGHTNESS_MODE, 
            Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
   }else{
          Settings.System.putInt(getContentResolver(), 
            Settings.System.SCREEN_BRIGHTNESS_MODE, 
            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);    
   }
         updateSettings();
  }
    }
}

* Click here for the source files of this demo Android Application.
^ Click here for the complete list of System Settings that you can play around.

Saturday, July 21, 2012

AS3: Fading Sound

Music playing, something that is very important to an interactive website, therefore I'm going to show you how to create a pretty simple fade in and fade out effect for your background music today.

Main class file - Main.as
package com.zcs.main 
{ 
 import flash.display.MovieClip;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import com.greensock.TweenLite;
 import flash.media.SoundChannel;
 import flash.media.SoundTransform;
 
 public class Main extends MovieClip 
 {
  private var _btn_mc:MovieClip;
  
  private var bgSound:Sound1;
  
  //Variable to toggle the playing state
  private var isPlaying:Boolean = false;
  
  private var soundChannel:SoundChannel;
  private var soundT:SoundTransform;
  
  public function Main() 
  {
   this.addEventListener(Event.ADDED_TO_STAGE, stageEvent);
  }
  
  private function stageEvent(event:Event):void
  {
   //Setup up the listener for the play stop button.
   _btn_mc = this.getChildByName("btn_mc") as MovieClip;
   _btn_mc.buttonMode = true;
   _btn_mc.addEventListener(MouseEvent.CLICK, clickEvent);
   
   //Create an instance for the Sound Object
   bgSound = new Sound1();
   
   //Create a Sound Transform instance that will be used
   //to modify the volume of the Sound Object 'bgSound'.
   soundT = new SoundTransform();
   soundT.volume = 0;
   
   //In Flash, we need to assign the audio that we want
   //to play to a Sound Channel
   soundChannel = new SoundChannel();
   soundChannel = bgSound.play(0,9999);
   soundChannel.soundTransform = soundT;
   
   //Call the function toggleSound()
   toggleSound();
  }
  
  /*
   If the Sound Object isn't 'playing', we need to slowly
   increase the volume of the sound channel to the max.
   If it's 'playing', slowly decrease the volume to 0.
  */
  private function toggleSound():void
  {
   if(isPlaying)
   {
    _btn_mc.gotoAndStop("stopping");
    TweenLite.to(soundT, 1, {volume:0, onUpdate:updateSoundEvent, 
        onComplete:updateSoundEvent});
   }else{
    _btn_mc.gotoAndStop("playing");
    TweenLite.to(soundT, 1, {volume:1, onUpdate:updateSoundEvent, 
        onComplete:updateSoundEvent});
   }
   isPlaying = !isPlaying;
  }
  
  //When the volume changes, we need to update the sound transform
  //of the sound channel.
  private function updateSoundEvent():void
  {
   soundChannel.soundTransform = soundT;
  }
  
  //Upon clicking the button, run the function toggleSound().
  private function clickEvent(event:Event):void
  {
   toggleSound();
  }
 }
}
* Click here for the demo.
^ Click here for the source files of the demo.

Friday, July 13, 2012

AS3 : Toggle Fullscreen

The other day, friends were asking me how to do full screen popup for flash. So here I am with a simple demo for creating a full screen swf popup. (Note: the full screen popup can only be trigger by a generic mouse click only.)

Time for some coding... The main as file for the swf - Main.as
package com.zcs 
{ 
 import flash.events.Event;
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 import flash.display.StageDisplayState;

 public class Main extends InterfaceSetup implements IInterfaceSetup
 {
  private var _top_mc:MovieClip;
  private var _bottom_mc:MovieClip;
  private var _left_mc:MovieClip;
  private var _right_mc:MovieClip;
  
  private var _cover_mc:MovieClip;
  
  public function Main():void 
  {
   // constructor code
  }
  
  //Override the stage variables
  override public function setupStageEvent(event:Event):void
  {
   super.setupStageEvent(event);
   stageWidthF = 600;
   stageHeightF = 400;
   
   _top_mc = this.getChildByName("top_mc") as MovieClip;
   _bottom_mc = this.getChildByName("bottom_mc") as MovieClip;
   _left_mc = this.getChildByName("left_mc") as MovieClip;
   _right_mc = this.getChildByName("right_mc") as MovieClip;
   
   _cover_mc = this.getChildByName("cover_mc") as MovieClip;
   _cover_mc.buttonMode = true;
   _cover_mc.addEventListener(MouseEvent.CLICK, clickEvent);
   
   resizeEvent();
  }
  
  //Upon Screen Resize....
  override public function resizeEvent(event:Event = null):void
  {
   //Scale and position the MovieClip accordingly
   resizeSubFunc(_top_mc, "50%", "l", "0", "t", 1);
   resizeSubFunc(_bottom_mc, "50%", "l", "0", "b", 1);
   resizeSubFunc(_left_mc, "0", "l", "50%", "t", 1);
   resizeSubFunc(_right_mc, "0", "r", "50%", "t", 1);
   resizeSubFunc(_cover_mc, "0", "l", "0", "t", 1);
  }
  
  private function clickEvent(event:Event):void
  {
   toggleFullScreen();
  }
  
  private function toggleFullScreen():void
  {
   //if normal size, go to fullscreen, else go to normal size
   if(stage.displayState==StageDisplayState.NORMAL){
    stage.displayState=StageDisplayState.FULL_SCREEN;
   }else{
    stage.displayState=StageDisplayState.NORMAL;
   }
  }  
 }
}
This is an simple as file that I have been using for reusing some screen resize functions - InterfaceSetup.as
package com.zcs
{
 import flash.display.MovieClip;
 import flash.events.*;
 import flash.system.*;
 import flash.external.*;
 
 public class InterfaceSetup extends MovieClip implements IInterfaceSetup
 {
  public var stageWidthF;
  public var stageHeightF;
  
  public function InterfaceSetup():void
  {
   this.addEventListener(Event.ADDED_TO_STAGE, setupStageEvent);
  }
  
  //setup the stage after this is added to stage and listen for resize of flash file
  public function setupStageEvent(event:Event):void
  {
   this.removeEventListener(Event.ADDED_TO_STAGE, setupStageEvent);
   stageWidthF = 1024;
   stageHeightF = 768;
   
   stage.addEventListener(Event.RESIZE, resizeEvent);
  }
  
  //resize event
  public function resizeEvent(event:Event = null):void
  {
   
  }
  
  //sub resize function that requires the following variables
  //tempMC = the movieclip lo :P
  //tempPosX, the x position (ex: 0 || 50%)
  //Hdir, from l (left) or r (right)
  //tempPosY, the y position (ex: 0 || 50%)
  //Vdir, from t (top) or b (bottom)
  public function resizeSubFunc(tempMC,tempPosX,Hdir,tempPosY,Vdir,scaleByScreen = 0):void
  {
   var strArray;
   
   if(scaleByScreen == 1){
    tempMC.scaleX = (stage.stageWidth/stageWidthF) * 1;
    tempMC.scaleY = (stage.stageHeight/stageHeightF) * 1;
   }else if(scaleByScreen == -1){
    tempMC.scaleX = (stage.stageHeight/stageHeightF) * 1;
    tempMC.scaleY = (stage.stageWidth/stageWidthF) * 1;
   }
   
   if(Hdir == "l"){
    tempMC.x = -1 * ((stage.stageWidth - stageWidthF) / 2);
    if(String(tempPosX).indexOf("%") != -1)
    {
     strArray = String(tempPosX).split("%");
     tempMC.x += (int(strArray[0])/100) * stage.stageWidth;
    }else{
     tempMC.x += Number(tempPosX);
    }
   }else{
    tempMC.x = stageWidthF + ((stage.stageWidth - stageWidthF) / 2);
    if(String(tempPosX).indexOf("%") != -1)
    {
     strArray = String(tempPosX).split("%");
     tempMC.x -= (int(strArray[0])/100) * stage.stageWidth;
    }else{
     tempMC.x -= Number(tempPosX);
    }
   }
   
   if(Vdir == "t"){
    tempMC.y = -1 * ((stage.stageHeight - stageHeightF) / 2);
    if(String(tempPosY).indexOf("%") != -1)
    {
     strArray = String(tempPosY).split("%");
     tempMC.y += (int(strArray[0])/100) * stage.stageHeight;
    }else{
     tempMC.y += Number(tempPosY);
    }
   }else{
    tempMC.y = stageHeightF + ((stage.stageHeight - stageHeightF) / 2);
    if(String(tempPosY).indexOf("%") != -1)
    {
     strArray = String(tempPosY).split("%");
     tempMC.y -= (int(strArray[0])/100) * stage.stageHeight;
    }else{
     tempMC.y -= Number(tempPosY);
    }
   } 
   tempMC.x = Math.ceil(tempMC.x);
   tempMC.y = Math.ceil(tempMC.y);
  }
 }
}
A simple Interface file - IInterfaceSetup.as
package com.zcs
{
 import flash.events.Event;

 public interface IInterfaceSetup 
 {
  // Interface methods:
  function setupStageEvent(event:Event):void;
  function resizeEvent(event:Event = null):void;
 }
}
Main HTML file - main.html
<html>
 <head>
<style type="text/css">
<!--
html{height:100%}
body {
 margin-left: 0px;
 margin-top: 0px;
 margin-right: 0px;
 margin-bottom: 0px;
 background-color: #000;
}
#flashContent {width:100%;height:100%;}
-->
</style>
    
   <!-- Include support librarys first -->  
  <script type="text/javascript" src="jsScript/swfobject.js"></script>
  <script type="text/javascript" src="jsScript/swfforcesize.js"></script>      
  <script type="text/javascript" src="jsScript/swfaddress.js?tracker=null"></script>    


    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>
    <table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
    <tr><td align="center">
    <div id="flashContent">
         <h1>You need at least Flash Player 10.0 to view this page.</h1>
                <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>
    </div>
  <script type="text/javascript">
   function createSWF(){
    var now=new Date();
    now = Date.UTC(now.getYear(),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds());
    var swfURL = "swf/main.swf?date=" + now;
    var flashvars = {};
    var params = {bgcolor:"#FFFFFF"};
    //Need to set allowfullscreen to "true"
    params.allowfullscreen = "true";
    //By changing scale to "exactFit" will make the swf
    //fill up all the spaces in the browser window
    params.scale = "exactFit";

    var attributes = {};
    attributes.name = "flashContent";
    swfobject.embedSWF(swfURL, "flashContent", "100%", "100%", "10.0.2", null, flashvars, params, attributes);   
   }
   createSWF();
  </script>    
     </td></tr></table>  
</body>
</html>
* Click here for the demo.
(Click on any part of the flash file to show the full screen popup.)
^ Click here for the source files of the demo.

Wednesday, July 4, 2012

AS3: Mesmerizing Stars

Someone has asked me how to create a 'mesmerizing galaxy' in Flash. Well, there's definitely more than one way of doing it and one of them will be tweening the whole animation... which is kind of crazy. Well here's an easier way of doing it. :P

Main.as (The .as file of the fla file)
package com.massStar
{
 import flash.display.MovieClip;
 import flash.events.Event;
 
 public class Main extends MovieClip 
 {
  public function Main() 
  {
   //Upon adding the flash file to the stage
   this.addEventListener(Event.ADDED_TO_STAGE, stageEvent);
  }
  
  //Create a grid of animated stars
  private function stageEvent(event:Event):void
  {
   var tempStar:Star_mc;
   for(var i:int = 0; i <= 400; i += 40)
   {
    for(var j:int = 0; j <= 320; j += 40)
    {
     tempStar = new Star_mc();
     tempStar.x = i;
     tempStar.y = j;
     this.addChild(tempStar);
    }
   }
  }
 } 
}
Star.as (The .as file of the star animation)
package com.massStar
{
 import flash.display.MovieClip;
 import flash.events.Event;
 
 public class Star extends MovieClip 
 {
  public function Star() {
   //Upon adding the animated star on stage...
   this.addEventListener(Event.ADDED_TO_STAGE, stageEvent);
  }
  
  private function stageEvent(event:Event)
  {
   //we will select a random frame and start playing the
   //animation sequence from that random frame
   var tempFrame:int = this.totalFrames;
   this.gotoAndPlay(Math.floor(Math.random() * tempFrame));
  }
 }
}
* Click here for the demo.
^ Click here for the source files of the demo.