Browse Month: June 2012

Screen Orientations Methods in unity3d

There are 3 types of orientation in

Rotate only landscape

public void AutoOrientToLandScape() {

if(Vector3.Dot(Input.acceleration.normalized,new Vector3(1,0,0)) > 0.45)  { Screen.orientation=ScreenOrientation.LandscapeRight; }

else if(Vector3.Dot(Input.acceleration.normalized,new Vector3(-1,0,0)) > 0.45)  { Screen.orientation=ScreenOrientation.LandscapeLeft; } }

Rotate only Portrait

public void AutoOrientToPortrait() {

if(Vector3.Dot(Input.acceleration.normalized,new Vector3(1,0,0)) > 0.45)  { Screen.orientation=ScreenOrientation.Portrait; }

else if(Vector3.Dot(Input.acceleration.normalized,new Vector3(-1,0,0)) > 0.45)  { Screen.orientation=ScreenOrientation.PortraitUpsideDown; } }

Auto Orientation

public void AutoOrient() {

Screen.orientation=ScreenOrientation.AutoRotation; }

iPhone Application Lifecycle

I just went through one presentation for iPhone application. So this post to share what I understood.

First of all the main focus is how actually iPhone applications work.

When user touches the icon of the application main() gets called by the system.

main() creates the autoreleasepool and starts the application with UIApplicationMain object. UIApplicationMain creates the instance of the UIApplication which actually starts the application.

UIApplication loads the main nib file and sets the application. Then UIApplication forwards the events to interface elements.

For terminating the application user taps home button, UIApplication tells the delegate that application is terminating. And so UIApplication gets exited , then main gets exited. This way the process ends.

This is the way iPhone applications works.

Happy coding…..!!!!

Play YouTube video using UIWebView on iPhone


Sometimes it gets very difficult to find a way to do simple things. Playing videos on iPhone is a simple thing, using UIWebView. Just need to embed the URL to HTML tags, and then load the HTML in UIWebView.

Here is the code to do so.

Pass you URL of YouTube Video in “urlStr”.

//In .h file
UIWebView *videoView;
// In .m file

videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 385)];

[self embedYouTube :urlStr  frame:CGRectMake(0, 0, 320, 385)];

[self.view addSubview:videoView];

// methos to embed URL in HTML & load it to UIWebView

– (void)embedYouTube:(NSString*)url frame:(CGRect)frame


NSString* embedHTML = @”


<style type=”text/css”>

body {

background-color: transparent;

color: white;



</head><body style=”margin:0″>

<embed id=”yt” src=”%@” type=”application/x-shockwave-flash”

width=”%0.0f” height=”%0.0f”></embed>



NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];

if(videoView == nil) {

videoView = [[UIWebView alloc] initWithFrame:frame];

[self.view addSubview:videoView];


[videoView loadHTMLString:html baseURL:nil];


**Note : The UIWebView for YouTube video doesn’t load when you run it on Simulator, work on device perfectly.


Using Horizontal Custom ListView in Android


<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=””    android:orientation=”vertical”    android:layout_width=”fill_parent”    android:layout_height=”fill_parent”>

<TextView      android:layout_width=”fill_parent”      android:layout_height=”wrap_content”      android:text=”MyHorizontalCustomeListView” />

<Gallery      android:id=”@+id/horizontallistview”      android:layout_width=”fill_parent”      android:layout_height=”wrap_content” />




<?xml version=”1.0″ encoding=”utf-8″?><LinearLayout xmlns:android=””  android:layout_width=”fill_parent”  android:layout_height=”fill_parent”  android:orientation=”vertical” >

<TextView      android:id=”@+id/itemtext”








public class Main extends Activity {

Gallery myHorizontalListView;

MyAdapter myAdapter;


public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);


myHorizontalListView =(Gallery)findViewById(;

myAdapter = new MyAdapter(this);        myHorizontalListView.setAdapter(myAdapter);



public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {

Toast.makeText(Main.this, arg0.getItemAtPosition(position).toString() + ” Clicked”,Toast.LENGTH_LONG).show();




public class MyAdapter extends BaseAdapter {

Context context;

String[] itemsArray = { “SUN”,”MON”, “TUS”, “WED”, “THU”, “FRI”, “SAT”};

MyAdapter(Context c){       context = c;      }


public int getCount() {

return itemsArray.length;     }


public Object getItem(int position) {

return itemsArray[position];     }


public long getItemId(int position) { return position;     }


public View getView(int position, View convertView, ViewGroup parent) {

View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,null);

TextView listTextView = (TextView)rowView.findViewById(;    listTextView.setText(itemsArray[position]);

return rowView; }



Toast With Image

Button toastwitimage;

@Override    public void onCreate(Bundle savedInstanceState) {                           super.onCreate(savedInstanceState);                                                     setContentView(R.layout.main);

toastwitimage=(Button)findViewById(;                      toastwitimage.setOnClickListener(new OnClickListener() {                       @Override

public void onClick(View v) {

Toast toast = Toast.makeText(getApplicationContext(), “Toast with image!”,1000);

toast.setGravity(Gravity.CENTER, 0, 0);

LinearLayout toastView = (LinearLayout) toast.getView(); ImageView imageCodeProject = new ImageView(getApplicationContext()); imageCodeProject.setImageResource(R.drawable.alien); toastView.addView(imageCodeProject, 0);;




Send Mail with Image

How to send the image to the mail in android for these you can refer the following code
Getting image from Web

InputStream is = (InputStream) new URL("Image URL").getContent();
// storing image from stream
Drawable drawable = Drawable.createFromStream(is, "srcName");
// converting drawable object to Bitmap to store in content providers of Media
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
// Store image in Devise database to send image to mail
String path = Images.Media.insertImage(getContentResolver(), bitmap,"title", null);
Uri screenshotUri = Uri.parse(path);
final Intent emailIntent1 = new Intent( android.content.Intent.ACTION_SEND);
emailIntent1.putExtra(android.content.Intent.EXTRA_TEXT,"Enter the Text");
emailIntent1.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(emailIntent1, "Send email using"));

How to check best provider for Google map

private void getLocation() { Location gpslocation = null;        Location networkLocation = null;
if(locationManager==null){          locationManager = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);        }        try {            if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100, 0, locationListener);                gpslocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);                Log.v(“Which provider Enabled:”, “GPS”);            }            if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100, 0, locationListener);                networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);                 Log.v(“Which provider Enabled:”, “Network”);            }        } catch (IllegalArgumentException e) {            Log.e(“error”, e.toString());        }        if(gpslocation==null && networkLocation==null)         {         location1= null;         Log.v(“Provider value:”, “G and N both Null”);         }
if(gpslocation!=null && networkLocation!=null){            if(gpslocation.getTime() < networkLocation.getTime()){                gpslocation = null;                location1= networkLocation;                Log.v(“Provider value:”, “G is less active N return”);            }else{                networkLocation = null;                location1= gpslocation;                Log.v(“Provider value:”, “N is less active G return”);            }        }        if (gpslocation == null) {         location1= networkLocation;         Log.v(“Provider value:”, “G is Null N return”);        }        if (networkLocation == null) {         location1= gpslocation;         Log.v(“Provider value:”, “N is Null G return”);        }        location1= null; }


it gives the location..

Multiple Android Activities in a TabActivity(Single tab can open multiple activity)

The problem that I had was when I started a new activity it covered up the Tabs on my TabActivity. I could put a single Activity into a Tab, but adding a second Activity resulted in losing view of the Tabs. Then I learned about ActivityGroups which have a LocalActivityManager. I realized it was possible to have multiple Activities within an ActivityGroup after all this is what a TabHost does. I then realized if I set the content of each Tab to an ActivityGroup I could start multiple Activities in each Tab. I developed the below ActivityGroup.

import java.util.ArrayList;


import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;

* The purpose of this Activity is to manage the activities in a tab.
* Note: Child Activities can handle Key Presses before they are seen here.
* @author Eric Harlow
public class TabGroupActivity extends ActivityGroup {

private ArrayList mIdList;

public void onCreate(Bundle savedInstanceState) {
if (mIdList == null) mIdList = new ArrayList();

* This is called when a child activity of this one calls its finish method.
* This implementation calls {@link LocalActivityManager#destroyActivity} on the child activity
* and starts the previous activity.
* If the last child activity just called finish(),this activity (the parent),
* calls finish to finish the entire group.
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size()-1;

if (index 1) {
Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));

I got caught up trying to figure out if and how LocalActivityManager handled stepping back up the view hierarchy. After viewing the note on the LocalActivityManager.dispatchCreate(bundle state) which states “Note: This does not change the current running activity, or start whatever activity was previously running when the state was saved. That is up to the client to do, in whatever way it thinks is best.”
I decided to add back tracking to the ActivityGroup. I attempted to make it behave the same as Activities outside an ActivityGroup by only needing to call finish() on an Activity and the previous Activity will be restarted or recreated.
I have also added the ability for the ActivityGroup to manage the back button being pressed. Android OS pre 2.0 handles things differently than the newer interface. A reference to this can be found here under Key Events Executed on Key-Up. I have tested the code on a device with OS 1.6 and the emulator with OS 2.1. Note: Child Activities like a ListActivity may handle the back button just override the appropriate methods for your OS version, and call onBackPressed() for the (parent) ActivityGroup. An example would look like this for OS 2.1.

public void onBackPressed() {
TabGroupActivity parentActivity = (TabGroupActivity)getParent();

The following section explains how I used this ActivityGroup. The first thing I did was subclass this ActivityGroup like this.

import android.content.Intent;
import android.os.Bundle;

public class TabGroup1Activity extends TabGroupActivity {
public void onCreate(Bundle savedInstanceState) {
startChildActivity("OptionsActivity", new Intent(this,OptionsActivity.class));

I added this TabGroup1Activity into my TabActivity like this.

TabHost tabHost = getTabHost();

.setContent(new Intent(this, TabGroup1Activity.class)));

Then any Activity that you want to start in the ActivityGroup can be done in a way similar to this.

Intent frequentMessages = new Intent(getParent(), FrequentMessageActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("FrequentMessageActivity", frequentMessages);

And that is how I added multiple Activities with a back tracking ability to a Tab of a TabActivity. Remember to always add Activities to your AndroidManifest.xml.

  • 1
  • 2