Android Auto Developer Overview


Android Auto extends the Android platform into the car. When users connect their Android handheld device to a compatible vehicle, Android Auto provides a car-optimized Android experience on the vehicle's screen. Users interact with compatible apps and services through voice actions and the vehicle's input controls.
The Android Auto SDK lets you easily extend your existing apps to work in the car, without having to worry about vehicle-specific hardware differences. You can use many Android APIs and services you are already familiar with. Android Auto provides an easy to use UI model and supports notifications and voice actions:
Media UI
Android Auto defines interaction models and car-specific UI patterns for apps. The first version of Android Auto supports media apps, such as music, podcast, live radio, and audio news apps.
Notifications
The platform will integrate with existing Android APIs for notifications. Users will get car appropiate notifications from Android apps on the vehicle's screen.
Voice Actions
Android Auto supports a set of voice actions to interact with compatible apps and services. Apps can respond to the voice actions they're interested in, such as playing a particular song or taking a note.
Easy Development Workflow
To extend an existing Android app for Android Auto, you implement a set of interfaces and services defined in the platform. You can reuse existing functionality and many Android APIs you already know.
We’ll release the Android Auto SDK in the coming months, which will let you test your Android Auto experience on a regular Android device.

Design


Android Auto extends users' digital ecosystem into their cars, allowing drivers to stay connected to their virtual worlds while staying focused on the road ahead.
Because driving is the primary activity in the car, any digital experiences should be designed to complement and augment that activity. They should never demand the user's attention.
Designing for cars is fundamentally different than designing for phones or tablets, and requires rethinking how experiences unfold. Because attention is limited and not all tasks are possible in the car, effective apps leverage the entire set of devices that drivers have, leveraging the app experience on those devices, outside of the car, to set the stage for simple experiences while driving.
Android Auto experiences are:
Glanceable and simple. Driving requires users' full attention. In-car software should not. Android Auto was designed to simplify not only the UI, but to optimize interactions and require less thinking, induce lower cognitive load, and ultimately, be safer. Effective apps provide just enough information in the minimum amount of time the user needs to glance at it and return their attention back to the road. Apps should also reduce the number of features to only those that are safe and drive-appropriate.
Predictive, yet predictable. Android Auto leverages rich, contextual awareness to keep the driver informed about important situations during the drive. Rich, timely help is combined with predictable functions. Effective apps make use of the patterns for common tasks and show timely information only when relevant.
Connected. By leveraging the user's personal ecosystem of apps and services, Android Auto promotes a continuous experience from phone to car to other devices. The user's music, destinations, and virtual ecosystem are always available to augment the drive. Experiences that leverage personal context and other devices are naturally part of Android Auto.
Naturally integrated. Android Auto blends the user's apps with the car, creating a truly integrated experience that leverages what is unique about each car. By using the screens, controls, and capabilities of the vehicle, Android Auto feels like an extension of the car.

Architecture


The Android Auto app shows your app's customized UI on the vehicle's screen. To communicate with the Android Auto app, your media app implements a set of media interfaces.

  Figure 1 - Architecture of Android Auto.
The architecture consists of the following components:
Media App - Runs a media service that exposes content through browsing and playback APIs. The service provides content to the Android Auto app. This is your Android app.
Android Auto App - Creates the UI and handles user interactions. This app uses a media client to request content from the media service running in the media app. The client requests data from the media service and monitors service states.
Vehicle Display - Shows app content and supports user interaction via on-screen soft buttons and other components, such as physical buttons or steering wheel controls.
Android media apps must implement binders to these APIs:
  • Browsing - Enables a media client to browse a hierarchy of a user’s media collection, presented as a virtual file system with containers (similar to directories) and items (similar to files).
  • Playback - Enables a media client to control media playback and monitor playback state through callbacks.

User Interface


The Android Auto app uses a car-specific UI model to display content and user interaction opportunities. Android Auto provides you with a standard UI designed to minimize driver distraction. You do not have to test a custom UI for for driver distraction, which is a lengthy and expensive process involving multiple legislations across the globe and different standards for each vehicle OEM.
The UI defines interfaces for browsing, searching, and listening to content from media apps. You can customize the UI colors, action icons, background images, and more.

Launcher

The launcher shows all the compatible media apps installed on the user’s Android device and lets users select one of them from an scrollable list:
  Figure 2. The launcher.

Primary App UI

After the user selects a media app, the display shows the primary app UI. You can customize this UI to show your own icons, app name, and background images. Figure 3 shows an example of a customized UI:
  Figure 3. A customized UI.

User Actions

The primary app UI supports four main actions on the action bar, four auxiliary actions on the overflow bar, and the Returnaction. You can use standard controls and customize the actions and icons, as shown in Figure 4.
  Figure 4. Custom extra actions.

Drawer Transitions

For browse actions, the display shows the drawer transition as shown in Figure 5.
  Figure 5. Generic and customized drawers.
After the transition from the primary app UI to the drawer UI, the drawer appears on the center. The customized drawer UI shows the media containers and media files provided by the media service in your app. You can also customize drawers with icons for list items.

Day and Night Transitions

All the UIs support different color schemes for day and night. The platform provides the state (day or night) and makes adjustments automatically.
  Figure 6. Day and night modes.

Customizing UIs

To customize the UI, you provide the following app-specific resources and actions to the Android Auto media client:
  • Resources - App logo, app name, theme colors, and background images.
  • Actions - Multiple custom actions; for example: Thumbs Up/DownFavorite, and Bookmark. These actions are app-specific.
If provided, the media client automatically uses them in the UI.

Development Process


Note: When released, the Android Auto SDK will provide media service interfaces, an APK for handheld devices that simulates the Android Auto app, and other tools for Android Auto development.
To create a media app for Android Auto, you include an Android service in your app that implements the media service interfaces provided by the Android Auto SDK. These interfaces define functionality for browsing and finding content, playing media, customizing the UI, and performing app-specific actions.
The media service interfaces present the content library as a navigable tree and enable clients to play media, get album art, obtain theme resources for the UI, and invoke app-specific actions.
You don’t have to create a new app for Android Auto: you can extend your existing Android app with implementations of the media service interfaces. Your service exposes your app’s media content, theme resources, and app-specific actions using the methods and data types specified by the media service interfaces. This simplifies the development cycle because:
  • You do not have to maintain a separate project for Android Auto
  • You can reuse existing functionality from your Android app
The Android Auto client presents the customized UI to users and invokes the functionality from your service as needed. This has two additional advantages:
  • Your app does not implement a UI for Android Auto
  • Your app does not manage user interactions directly
This also means that you do not have to worry about vehicle-specific hardware differences such as screen resolutions, software interfaces, knobs and touch controls.

Testing Your App on an Android Device


The Android Auto SDK includes an APK with a media client implementation, which is similar to those available in compatible vehicles. To test your app with this client:
  1. Get an Android device with a similar form factor to a dashboard screen (like a Nexus 7).
  2. Configure the device for Android development.
  3. Install the APK for the media client from the Android Auto SDK on the device.
  4. Install the APK for your app on the device.
  5. Open the media client app from the Android Auto SDK on the device.
  6. Select your app from the list of available services.
The customized UI for your app appears on the client. You can navigate the content library and play media. If your app provides app-specific actions, these actions appear in the UI controls.

Running Your App on Android Auto


Media apps are available on the Google Play Store for compatible Android devices. When users connect their Android device to a compatible vehicle, the Android Auto media client shows a list of all the Android apps installed on the phone that implement the media service interfaces.
When users select one of these apps, the Android Auto media client uses the app’s service to respond to user input and invoke the methods in the media service interfaces to build the UI, navigate the content library, and play media.

Update data in SQLite using Android app


Are you getting problems during updating data on sqlite, here is the simple way to solve this problem:

String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);

Or

   ContentValues args = new ContentValues();
    args.put(columnName, newValue);
    db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);

Or

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

Or

String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;

myDataBase.execSQL(strSQL);

Or

updateContact()
    // Updating single contact
public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());

    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}
More: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Happy Coding!!!

Difference between JSF, Servlet and JSP


BalusC gives best answers in stackoverflow, because  it is short and very informatives , clearly to understand fro beginners.

JSP (JavaServer Pages)

JSP is a Java view technology running on the server machine which allows you to write template text in (the client side languages like HTML, CSS, JavaScript and so on). JSP supports taglibs, which are backed by pieces of Java code that let you control the page flow or output dynamically. A well known taglib is JSTL. JSP also supports Expression Language, which can be used to access backend data (via attributes available in page, request, session and application scopes), mostly in combination with taglibs.
When a JSP is requested for the first time or when the webapp starts up, the servlet container will compile it into a class extending HttpServlet and use it during the webapp's lifetime. You can find the generated source code in the server's work directory. In for example Tomcat, it's the /work directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the webserver over network to the client side, which in turn displays it in the web browser.

Servlets

Servlet is an Java application programming interface (API) running on the server machine, which intercepts requests made by the client and generates/sends a response. A well known example is the HttpServlet which provides methods to hook on HTTP requests using the popular HTTP methods such as GET and POST. You can configure HttpServlets to listen on a certain HTTP URL pattern, which is configurable in web.xml, or more recently with Java EE 6, with @WebServlet annotation.
When a Servlet is first requested or during webapp startup, the servlet container will create an instance of it and keep it in memory during the webapp's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by HttpServletRequest and handle the response by HttpServletResponse. Both objects are available as method arguments inside any of the overridden methods of HttpServlet, such as doGet() and doPost().

JSF (JavaServer Faces)

JSF is a component based MVC framework which is built on top of the Servlet API and provides components in favor of taglibs, which can be used in JSP or any other Java based view technology such as Facelets. Facelets is much more suited to JSF than JSP. It namely provides great templating capabilities such as composite components, while JSP basically only offers the <jsp:include> for templating, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work in JSF) when you want to replace a repeated group of components with a single component. If you can, I recommend to drop JSP and go for Facelets when you want to develop with JSF.
As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for View and a Javabean class as Model. The JSF components are been used to bind the view with the model (such as your ASP.NET web control does) and the FacesServlet uses the JSF component tree to do all the work.

Related questions

Jobs: Android Developer @ HUDL, New York


We're hiring in: Nebraska, Texas, California, New York and the United Kingdom.
Would you like to work on a Top 50 Sports App in Google Play with a 4.4+ rating? Want to help define how mobile applications impact the future of athletics? Yes? Then for you, this is the best Android development job on the planet.
At Hudl, we build software that helps coaches and athletes use video and data to improve every day. We’re looking for an experienced Android-focused mobile developer to join one of our small, cross-functional teams.

You

  • Are experienced developing for Android. You use the devices daily, you’ve written and shipped at least one Android app, you understand the development environment and ecosystem, and you’re passionate about the platform.
  •  Translate complex, real-world problems into simple and elegant software solutions.
  •  Understand the balancing act between crafting a robust, lasting solution and banging something out right now.
  • Care about UI and Interaction. You're excited by the new Google Material Design. You’re willing to push the limits, not relying solely on default controls. You answer “Can this be done?” with: “We’ll figure out a way.”
  • Have a passion for code and product. You care about the craft of writing software and fight for the details that separate an average product from a great one.
  • Are excited to have your work used by passionate customers who rely on it to do their job during the key moments in games.
  • Hate the idea of being a cog in the machine—you are self-motivated. You want to own your work and have a say in the direction of the product.

We

  • Believe culture matters more than anything else.
  • Are young nerds, designers, marketers, and former jocks who love sports and tech.
  • Have a profitable, kick-ass product that is changing coaches’ and athletes’ lives.
  • Need you to help us build awesome software for coaches and athletes.
  • Are as passionate about winning as the coaches we serve.
  • Promise you’ll love coming to work every day.

Working with Us, You Can:

  • Enjoy an unlimited vacation policy.
  • Sleep soundly with our paid health insurance and retirement plans.
  • Get hooked up with free tickets to NFL & Div. I sporting events.
  • Work remotely from NY, TX, CA, MA or at our HQ in Lincoln, NE (relocation assistance offered).
  • Stuff yourself at free daily company-sponsored lunches.
  • Snack on free food and soda.

Load an ImageView by URL in Android


Image referenced by URL in an ImageView, getting image from url and set on imageview, then here is the some idea, which may helpful .

Here is the some snap codes:

// show The Image on button load click event
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
}

public void onClick(View v) {
    startActivity(new Intent(this, IndexActivity.class));
    finish();

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}
write permission on  AndroidManifest.xml to access the internet.

<uses-permission android:name="android.permission.INTERNET" />

 and convert whole ImageView to Bitmap from this code:

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

other examples:

http://www.learn2crack.com/2014/06/android-load-image-from-internet.html

http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

http://theopentutorials.com/tutorials/android/imageview/android-how-to-load-image-from-url-in-imageview/

http://belencruz.com/2012/11/load-imageview-from-url-in-android/

Happy Coding!!!

video tutorials in Android

Are you searching video tutorials in android with and without free in android, here is the some links for that.



 why not you search on internet then ask. Go to first
I recommend you best android video tutorials provided websites are:
Official android videos
Lynda.com
mybringback.com
marakana.com
Thenewboston.com
xtensivearts.com

tutorials-android.com

Happy coding !!!

How to add a footer in ListView in android


Create a footer view layout consisting of text that you want to set as footer and then try

View footerView = ((LayoutInflater) ActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
ListView.addFooterView(footerView);

or may be use this also:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="7dip"
android:paddingBottom="7dip"
android:orientation="horizontal"
android:gravity="center">

<LinearLayout
android:id="@+id/footer_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center">

<TextView
android:text="@string/footer_text_1"
android:id="@+id/footer_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textStyle="bold"
android:layout_marginRight="5dip" />
</LinearLayout>
</LinearLayout>

and on activity
public class MyListActivty extends ListActivity {
private Context context = null;
private ListView list = null;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list
= (ListView)findViewById(android.R.id.list);

//code to set adapter to populate list
View footerView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
list
.addFooterView(footerView);
}
}


Happy Coding!!!


How to access child views from a ListView in android

Are you get lots problems during access child view from a listview in android, then here is the some solution that may helpful for you.



Android ListView: get data index of visible itemand combine with part of Feet's answer above, can give you something like:

int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);

this solution copy from stackoverflow and i solved my solution from this:

Happy Coding!!!

Close or hide the Android Soft Keyboard from code


Are you trying to  make close or hide the Soft Keyboard in your app using code. here is the solution .

Force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your edit field.

EditText myEditText = (EditText) findViewById(R.id.myEditText);  
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm
.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);


This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).

Happy Codting

Validate email in JavaScript?


This is one of those useful things that people will be Googling for validate email address on Javascript, this tutorial mostly used when you are developing app on Cross platform, like sencha, phonegap.

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);

}

Here, Using regular expressions is probably the best way. Here's an example (live demo):


Happy Coding!!!

Java Tutorials: Calculate fibonacci series in Java


Calculating fibonacci series in Java

public class Example1 {

public static void main(String [] args) {
 fibonacciLoop(5);
}

 public static void fibonacciLoop(int n){
      if (n == 0) {
           System.out.println("0");
       } else if (n == 1) {
           System.out.println("0, 1, ");
       } else {
           System.out.print("0, 1,  ");
           int a = 0;
           int b = 1;
           for (int i = 1; i < n; i++) {
               int nextNumber = a + b;
               System.out.print(nextNumber + ", ");
               a = b;
               b = nextNumber;
           }
       }
    }

Output:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,


ebook: Migrating to Android for iOS Developers


Migrating to Android for iOS Developers gives you - as an experienced iOS app developer - the ability to learn native Android apps development from scratch. Through case studies and examples, this book starts with a simple but meaningful Hello Android project. Then, this book continues by providing guidelines and tutorial projects showing you how to translate iOS apps to Android right from the beginning.

What you’ll learn

• How to maximize your existing iOS mobile knowledge to learn Android programming skills
• How to use the Android integrated development environment with the Eclipse ADT plugin
• How to translate your existing iOS code to Android with the following common mobile topics:
° Common mobile screen navigation patterns
° User interface components and UI animations
° Storing data
° Networking and using remote services
° Using system apps
° Maps and location awareness
° Mobile search frameworks
° Mobile analytics


  • SBN13: 978-1-484200-11-7
  • 532 Pages
  • User Level: Beginner to Intermediate
  • Publication Date: July 20, 2014 

  • What are the differences between git pull and git fetch?

    When you are getting confuse in git pull and git fetch, here is the some solutions, may be helpful.

    In the simplest terms, git pull does a git fetch followed by a git merge.
    You can do a git fetch at any time to update your remote-tracking branches under refs/remotes/<remote>/. This operation never changes any of your own local branches under refs/heads, and is safe to do without changing your working copy. I have even heard of people running git fetch periodically in a cron job in the background (although I wouldn't recommend doing this).


    A git pull is what you would do to bring a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.

    or

    • When you use pull, Git tries to automatically do your work for you. It is context sensitive, so Git will merge any pulled commits into the branch you are currently working in. pull automatically merges the commits without letting you review them first. If you don’t closely manage your branches you may run into frequent conflicts.
    • When you fetch, Git gathers any commits from the target branch that do not exist in your current branch and stores them in your local repository. However, it does not merge them with your current branch. This is particularly useful if you need to keep your repository up to date, but are working on something that might break if you update your files. To integrate the commits into your master branch, you use merge.

    How to make app using phonegap in eclipse

    If you succesfully installed android SDK bundles, then create simple android project then follows the instruction:

    Add the PhoneGap library

    You now have a simple Android application. Before you can write a PhoneGap application, you need to add the PhoneGap library. There are two files: a JavaScript file that contains the PhoneGap API called by our application, and a native JAR file containing the native implementation for the PhoneGap API.
    1. Expand the AndroidPhoneGap project tree view, as shown in Figure 10:
      Figure 10. Android project with PhoneGap library
      Android project with PhoneGap library
    2. Create the directory \assets\www. Also create the directory \libs if it doesn't already exist.
    3. Unzip the PhoneGap download and locate the Android subdirectory.
    4. Copy the three PhoneGap library files for Android to the following Eclipse project folders:
      • Copy phonegap-1.0.0.jar to \libs\phonegap-1.0.0.jar
      • Copy phonegap-1.0.0.js to \assets\www\phonegap-1.0.0.js
      • Copy xml/plugins.xml to \res\xml\plugins.xml
    Even though the PhoneGap JAR file is copied into the project, you also need to add it to the project's build path.
    1. Select Project > Properties > Java Build Path > Libraries > Add JARs….
    2. Add phonegap-1.0.0.jar by navigating to it in the project, as shown in Figure 11:
    Figure 11. Adding PhoneGap JAR
    Adding PhoneGap JAR
    The final step in preparing the example Android application to use PhoneGap is to modify App.java. Because a PhoneGap application is written in HTML and JavaScript, you need to change App.java to load your HTML file using loadUrl(), as shown in Listing 2. You can edit App.java by double-clicking on App.java in the tree view shown in Figure 10.
    Listing 2. App.java
    Package com.ibm.swgs;
    import android.os.Bundle;
    import com.phonegap.*;
    public class App extends DroidGap //Activity
    {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);
    super.loadUrl("file:///android_asset/www/index.html");
    }
    }

    Write the PhoneGap application

    You're now ready to start writing the PhoneGap application. For Android, files under the asset directory are referenced using file:///android_asset. As specified in loadUrl() in Listing 2, you need to create an index.html file under assets/www.
    After creating index.hml, enter the contents of Listing 3 below.
    Listing 3. index.html
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>PhoneGap</title>
    <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
    </head>
    <body onload='document.addEventListener("deviceready", deviceInfo, false);'>
    <script>
    function deviceInfo() {
    document.write("<h1>This is Phonegap 1.0.0 running on "+device.platform+"
    "+device.version+"!</h1>");
    }
    </script>
    </body>
    </html>
    A brief explanation of index.html is in order. Before calling any PhoneGap APIs, we must wait for the deviceready event, which indicates that the native portion of PhoneGap has been initialized and is ready. In Listing 3, the onload callback registers for deviceready. When it fires, we write out the device's OS and version.
    Since PhoneGap uses native features that are protected by permissions, you need to modify AndroidManifest.xml to include these uses-permission tags. You also need to specify the support-screens tag, the android:configChanges property, and the com.phonegap.DroidGap activity tag, as shown in Listing 4:
    Listing 4. AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ibm.swgs"
    android:versionCode="1"
    android:versionName="1.0">
    <supports-screens
    android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:resizeable="true"
    android:anyDensity="true"
    />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".App"
    android:label="@string/app_name"
    android:configChanges="orientation|keyboardHidden">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    <activity android:name="com.phonegap.DroidGap" android:label="@string/app_name"
    android:configChanges="orientation|keyboardHidden">
    <intent-filter>
    </intent-filter>
    </activity>
    </application>
    </manifest>

    Run the application in the Android emulator

    The PhoneGap application is now ready to run. Select Run > Run As > Android Application, and you should see something similar to Figure 12
    Figure 12. Android emulator
    Screenshot of Android emulator and message 'This is PhoneGap 1.0.0 running on Android 2.2!'
    Eclipse automatically builds the application, launches the emulator, and installs and runs it on the emulator.
    The emulator can take several minutes to start up. To speed development, keep the emulator running until you are done with your development session. Eclipse will automatically use a running emulator instead of launching a new one.

    Get products and technologies

    Source:IBM

    Common android developer interview question and anwers

    Here is common interview asked during interview .

    What is Android?
    #  It is an open-sourced operating system that is used primarily on mobile devices, such as cell phones and tablets.
    It is a Linux kernel-based system that’s been equipped with rich components that allows developers to create and run apps that can perform both basic and advanced functions.

    Explain in brief about the important file and folder when you create new android application.

    # When you create android application the following folders are created in the package explorer in eclipse which are as follows:

    src: Contains the .java source files for your project. You write the code for your application in this file. This file is available under the package name for your project.

    gen —This folder contains the R.java file. It is compiler-generated file that references all the resources found in your project. You should not modify this file.

    Android 4.0 library: This folder contains android.jar file, which contains all the class libraries needed for an Android application.

    assets: This folder contains all the information about HTML file, text files, databases, etc.

    bin: It contains the .apk file (Android Package) that is generated by the ADT during the build process. An .apk file is the application binary file. It contains everything needed to run an Android application.

    res: This folder contains all the resource file that is used byandroid application. It contains subfolders as: drawable, menu, layout, and values etc.

    What is an Activity?
    # A single screen in an application, with supporting Java code.

    What is an Intent?
    # A class (Intent) which describes what a caller desires to do. The caller will send this intent to Android’s intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent (class).

    What is the Android Architecture?
    #  Android Architecture is made up of 4 key components:
    - Linux Kernel
    - Libraries
    - Android Framework
    - Android Applications


    How do you handle multiple resolution screens in android?

    # The following five properties help you to achieve multiple resolution screens in android:

        Screen size – Screen sizes are divided into four generalized sizes: small, normal, large, and extra-large.
        Screen density – Screen densities are also divided into four generalized densities: low, medium, high, and extra-high.
        Orientation – When user rotates the device the orientation of the device also gets changed.
        Resolution – The total number of physical pixels on a screen.
        Density – independent pixel (dp) – Provides you a density-independent way to define your layouts.

    What is a resource?
    # A user defined JSON, XML, bitmap, or other file, injected into the application build process, which can later be loaded from code


     What is an Explicit Intent?
    #
    - Explicit intent specifies the particular activity that should respond to the intent.
    - They are used for application internal messages.

     What is an Implicit Intent?
    #
    - In case of Implicit Intent, an intent is just declared.
    - It is for the platform to find an activity that can respond to it.
    - Since the target component is not declared, it is used for activating components of other applications.


    What is the role of Orientation?

    # Orientation is used to determine the presentation of LinearLayout. It may be presented in rows or columns.


    What is adb?
    #  Adb is short for Android Debug Bridge. It allows developers the power to execute remote shell commands. Its basic function is to allow and control communication towards and from the emulator port.


    What is Dalvik Virtual Machine?
    #
    - It is Android's virtual machine.
    - It is an interpreter-only virtual machine which executes files in Dalvik Executable (.dex) format. This format is optimized for efficient storage and memory-mappable execution.

    What are the different states wherein a process is based?
    #  There are 4 possible states:
    - foreground activity
    - visible activity
    - background activity
    - empty process

    What is the APK format?
    # The APK file is compressed AndroidManifest.xml file with extension .apk. It also includes the application code (.dex files), resource files, and other files which are compressed into a single .apk file.

    What is the AndroidManifest.xml?
    # This file is essential in every application. It is declared in the root directory and contains information about the application that the Android system must know before the codes can be executed.

    What is a Fragment?
    # A fragment is a part or portion of an activity. It is modular in a sense that you can move around or combine with other fragments in a single activity. Fragments are also reusable.

    Describe Briefly the Android Application Architecture
    # Android Application Architecture has the following components:

        Services like Network Operation
        Intent – To perform inter-communication between activities or services
        Resource Externalization – such as strings and graphics
        Notification signaling users – light, sound, icon, notification, dialog etc.
        Content Providers – They share data between applications

    How make weblink(hyperlink) in textview in android

    Weblink or Hyperlink in textview, simple way to make it:

    Textview tv_link= (Textview)findViewById(R.id.tvLink);
    tv_link.setText("prandroid@gmail.com");
    Linkify.addLinks(tv_link, Linkify.ALL);

    or may be use this also:

    TextView tvLinkTest= (TextView) findViewById(R.id.tl);
    tvLinkTest.setMovementMethod(LinkMovementMethod.getInstance());

    next alternative method is:

    <TextView
    android:text="www.hello.com"
    android:id="@+id/TextView01"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:autoLink="web">
    </TextView>

    Happy Coding!!!

    Display Second Largest number in java

    Displaying second largest number in string array in java.

    Here is the full source code, how to display second largest number in integer array ,
    public class One {
    public static void main(String[] args) {

            int arr[] = {5,8,0,7,12};
         
            System.out.println("SortedSet = second largest number is--->"+displaySecond(arr));
           
    }

    private static int displaySecond(int[] arr1) {
    if (arr1.length==0 || arr1.length==1) {
            return -1;
            }else {
            SortedSet<Integer> set = new TreeSet<Integer>();
            for (int i: arr1) {
                set.add(i);
            }
            // Remove the maximum value; print the largest remaining item
            set.remove(set.last());
            return set.last();
    }
    }
    }

    Output looks like:

    SortedSet = second--->8

    Happy Coding!!!


    Press back and Exit app in androird


    If you getting trouble when pressing back don't exit app, then this article will help you. Here first time your will display toast message, please press again for exit app.

    here is the full source code:

    public class MainActivity extends Activity {
    private static long back_pressed;
    private Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    }

    @Override
    public void onBackPressed() {

    if (back_pressed + 2000 > System.currentTimeMillis()){
    // need to cancel the toast here
    toast.cancel();
    // code for exit
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    }else{
    toast = Toast.makeText(getBaseContext(), "Please click BACK again to exit", Toast.LENGTH_SHORT);
    toast.show();
    }
    back_pressed = System.currentTimeMillis();
    }

    Output looks like:



    Happ Coding!!
    }

    Refresh activity on back button in android


    Normally, when user click the back button in android, the next view is not refreshed. I had this problem when I was doing the settings. if user changed the some settings and hit back button, the new settings won’t be applied to the “back” list view since all the cells are reused.
    you can do some scroll to refresh the list view but that is definitely not something we wanna user to do.
    first solution is to override the onResume method in the back view, but it is not guaranteed to work in listView.
    However the following code should do the work:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isNightModeToggled) {
            Intent a = new Intent(this,MainActivity.class);
            a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(a);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    Happy Coding!!!!

    Programmatically Displaying the Settings of device


    Sometimes, you want to set wifi, bluetooth and others setting then from programmatically do things here in your code

    you can use the startActivity()
    method together with an Intent object. The following shows some examples:

        //---display the main Settings page---
        startActivity(
            new Intent(Settings.ACTION_SETTINGS));
           
        //---display the Location access settings page---
        startActivity(new Intent(
            Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                   
        //---display the Wireless & networks settings page---
        startActivity(new Intent(
            Settings.ACTION_AIRPLANE_MODE_SETTINGS));
           
        //---display the Bluetooth settings page---
        startActivity(new Intent(
            Settings.ACTION_BLUETOOTH_SETTINGS));
           
    Output Looks Like:

            In general, you use the predefined constant Settings.ACTION__SETTINGS.
    The full list can be found here: http://developer.android.com/reference/android/provider/Settings.html

    Happy Coding!!!