Using platform indicators

Handling different devices, platforms, and models is often the biggest challenge with cross-platform development. Titanium provides the Ti.Platform namespace to help you make decisions in your code on how to handle runtime execution.

In the following recipes, we will walk through how to create a PlatformHelpers CommonJS module containing convenience methods to solve many of your platform-related queries. The following screenshots demonstrate this recipe while running on both the iPhone and Android platforms.

Using platform indicators

Getting ready

The Ti.Platform namespace is helpful for providing platform and device-specific details, but often you need a high level of detail such as when you have a tablet running your app and if so if it is an iPad Mini.

Adding recipe components to your project

Adding the PlatformHelpers module to your project is easy. Simply copy the platform_helpers.js file into your project as shown in the following screenshot:

Adding recipe components to your project

How to do it...

The following app.js demonstrates the PlatformHelpers module described earlier in this chapter. This sample app presents a window with your device details. Give it a try on all of your Android and iOS devices.

  1. To create our same app, first we declare our app namespace and import our PlatformHelper module.
    //Create our application namespace
    var my = {
      platformHelpers : require('platform_helpers')
    };
    
    (function(){
  2. Next we create the window in which we will present the device information.
    var win = Ti.UI.createWindow({
      backgroundColor:'#fff'
    });
  3. Next we create an empty array to store our device details.
    var deviceData = [];

    An entry is added to deviceData if your device is running on a simulator.

    The isSimulator property is used to show the simulator message, only if the recipe is currently running on a platform simulator or emulator.

    if(my.platformHelpers.isSimulator){
      deviceData.push({
        title:'Running on Simulator', child:false
      });
    }
  4. Next the platform, operating system's name, and manufacturer are added to deviceData.
    deviceData.push({
      title:'Platform: ' + 
      (my.platformHelpers.isAndroid ? 'Android' : 'iOS'), 
      child:false
    });
    
    deviceData.push({
      title:'osname: ' +  my.platformHelpers.osname, 
      child:false
    });
    
    deviceData.push({
      title:'manufacturer: ' +  
      my.platformHelpers.manufacturer, child:false
    });
  5. The following statement adds a flag to deviceData indicating if the current device is a tablet form factor:
    deviceData.push({
      title:(my.platformHelpers.isTablet ? 
      'Is a Tablet' : 'Is not a Tablet'), child:false
    });
  6. Next we add the device model and specify if it supports background tasks in the deviceData array.
    deviceData.push({
      title:'Model: ' + my.platformHelpers.deviceModel, 
      child:false
    });
    
    deviceData.push({
      title:'Backgrounding Support: ' + 
      my.platformHelpers.supportsBackground,
      child:false
    });
  7. Screen dimensions are the most commonly used properties. The following snippet adds the height and width of the screen to the deviceData array:
    deviceData.push({
      title:'Height: ' + my.platformHelpers.deviceHeight +
      ' Width: ' + my.platformHelpers.deviceWidth,
      child:false
    });
  8. If your app is currently running on an iOS device, the following snippet adds the device type and specifies if it is retina enabled, to the deviceData array.
    if(my.platformHelpers.isIOS){
      deviceData.push({
        title:'iOS Device Type: ' + 
        (my.platformHelpers.iPad ? 
        (my.platformHelpers.iPadMiniNonRetina ? 
        'iPad Mini' : 'Is an iPad') : 'iPhone'),
        child:false
      });
    
      deviceData.push({
        title:'Is Retina : ' + my.platformHelpers.isRetina,
        child:false
      });				
    }
  9. The PlatformHelper module provides a great deal of data. To best display this, we will be using a Ti.UI.TableView with the deviceData array that we have built in an earlier code snippet.
    var tableView = Ti.UI.createTableView({top:0, 
    data:deviceData});
    
      win.add(tableView);
      win.open();
    })(); 

How it works...

The device platform lookups will frequently be accessed across your app. To avoid performance issues by repeatedly crossing the JavaScript Bridge, we import the values we will use and assign them to properties in our CommonJS PlatformHelpers module.

exports.osname = Ti.Platform.osname;
exports.manufacturer = Ti.Platform.manufacturer;
exports.deviceModel = Ti.Platform.model;
exports.deviceHeight = Ti.Platform.displayCaps.platformHeight;
exports.deviceWidth = Ti.Platform.displayCaps.platformWidth;
exports.densitylevel = Ti.Platform.displayCaps.density;
exports.deviceDPI = Ti.Platform.displayCaps.dpi;

It is often helpful to have a Boolean indicator for the platform with which you are working. The following snippet shows how to create isAndroid and isIOS properties to accomplish this:

exports.isAndroid = exports.osname === 'android';
exports.isIOS = (exports.osname === 'ipad' || 
exports.osname === 'iphone'),

Simulator check

Depending on your platform, several features may not work in that platform's simulator or emulator. By using the isSimulator property, detect which environment you are in and branch your code accordingly.

exports.isSimulator = (function(){
  return (Ti.Platform.model.toUpperCase() === 'GOOGLE_SDK' || 
  Ti.Platform.model.toUpperCase()  === 'SIMULATOR' || 
  Ti.Platform.model.toUpperCase()  === 'X86_64')
})();

Background capabilities

Mobile apps are often required to perform tasks in the background. This recipe demonstrates how to perform a version-based capability check to determine if the device your application is running on supports backgrounding/multitasking.

exports.supportsBackground = (function(){

Now perform the following steps:

  1. First check if the user is running on Android. If so, return true as most Android ROMs support background processing by default.
      if(exports.osname === 'android'){
        return true;
      }
  2. Next confirm the recipe is running on an iOS device.
      if(exports.osname === 'iphone'){
  3. The version is checked to ensure that the device is running iOS 4 or greater. This confirms the operating system supports background processing.
        var osVersion = Ti.Platform.version.split(".");
        //If no iOS 4, then false
        if(parseInt(osVersion[0],10) < 4){
          return false;
        } 
  4. Finally the recipe confirms the device version is greater than the iPhone 3GS. This confirms the hardware supports background processing.
        var model = exports.deviceModel.toLoweCase()
        .replace("iphone","").trim();
        var phoneVersion = Ti.Platform.version.split(".");
        if(parseInt(phoneVersion[0],10) < 3){
          return false;
        } 		
      }
      //Assume modern device return true
      return true;
    
    })();

    Note

    Depending on the platform, this feature may be turned off by the user. A secondary capacity check is also recommended.

Detecting tablets

Universal app development is a common requirement on both Android and iOS. The following helper provides a Boolean indicator if your app is running on a tablet form factor:

//Determine if running on a tablet
exports.isTablet = (function() {

Check if the device is either an iPad or an Android device with at least one dimension of 700 pixels or greater.

  var tabletCheck = exports.osname === 'ipad' || 
    (exports.osname === 'android' && 
    (!(Math.min(
    exports.deviceHeight,
    exports.deviceWidth
    ) < 700)));
    return tabletCheck;
})();

Note

For Android, this checks if there is a height or width greater than 700 pixels. You may wish to change this based on your targeted devices. For example, if you are targeting some of the larger screen Android phones, you would need to update the default 700 pixels/points to reflect them having a large screen yet still being considered a phone form factor.

A 4-inch iPhone

With the introduction of the iPhone 5, we need to be aware of two different iPhone screen sizes. The following snippet shows how to create a property indicating if your app is running on an iPhone with this new screen size.

exports.newIPhoneSize = (function(){

First verify the recipe is running on an iPhone device.

  if(exports.osname !== 'iphone'){
    return false;
  }

Next check the size to see if there is any dimension greater than 480 points.

  return (Math.max(
    exports.deviceHeight,
    exports.deviceWidth
  ) > 480);
});

Note

Please note, the preceding newIPhoneSize method will only return true, if the app has been completed to support a 4-inch display. Otherwise, it will return false as your app is running in the letterbox mode.

iPad

Titanium allows you to create universal apps on iOS. Using the following property, you can branch your code to show different functionalities to your iPad users:

exports.iPad = exports.osname === 'ipad';

iPad Mini

The iPad Mini was designed with the same resolution as the first and second generation iPads. Although designed to run iPad apps without modification, the smaller screen size often requires UI adjustments for smaller touch targets. The following code demonstrates how to determine if your app is running on an iPad Mini:

exports.iPadMiniNonRetina= (function() {

Now perform the following steps:

  1. First check if the recipe is running on a nonretina iPad.
      if((exports.osname !== 'ipad')||
      (exports.osname === 'ipad' &&
      exports.densitylevel==='high')){
        return false;
      }
  2. Next verify if the nonretina iPad is not an iPad 1 or iPad 2. If not either of these modules, assume the recipe is running on an iPad Mini.
      var modelToCompare = exports.deviceModel.toLowerCase();
      return !(
        (modelToCompare==="ipad1,1")||
        (modelToCompare==="ipad2,1")||
        (modelToCompare==="ipad2,2")||
        (modelToCompare==="ipad2,3")||	
        (modelToCompare==="ipad2,4")		
      );
    })();

Note

Apple currently does not provide a platform indicator for the iPad Mini. This check uses model numbers and might not be future proof.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.107.55