Thursday, 29 August 2013

Battery status

BatteryStatus 


  • Documentation

========================================================================
DESCRIPTION:

Demonstrates the use of the battery status properties and notifications provided via the iPhone OS SDK.

Testing:

The sample is only useful when run on a device. The simulator always returns unknown battery status.


========================================================================
BUILD REQUIREMENTS:

iOS 4.0 SDK

========================================================================
RUNTIME REQUIREMENTS:

iOS 3.2 or later

========================================================================
PACKAGING LIST:

BatteryStatusAppDelegate
Delegate of the main application that presents the initial window.

RootViewController
Controller for initial window. Receives battery status change notifications. Queries the
battery status and presents it in a UITableView. Enables and disables battery status updates.

========================================================================
CHANGES FROM PREVIOUS VERSIONS:

Version 1.1
Updated for iOS 4.
Version 1.0
First release.



Copyright (c) 2009-2010 Apple Inc. All rights reserved.


  • Design  



     
     
  •  Code  
 


RootViewController.h


@interface RootViewController : UITableViewController
{
@private    
    /* private formatter instance that we'll re-use */
    NSNumberFormatter *numberFormatter; 
}

@property (nonatomic, retain, readonly) NSNumberFormatter *numberFormatter;

@end


------------------------------------------------------------
RootViewController.m


#import "RootViewController.h"

@implementation RootViewController

enum ControlTableSections
{
kMonitoringSection = 0,
kLevelSection,
kBatteryStateSection
};

- (void)dealloc
{
[numberFormatter release];
[super dealloc];
}

- (void)viewDidLoad
{
[super viewDidLoad];
// This title will appear in the navigation bar
self.title = NSLocalizedString(@"Battery Status", @"");
// Register for battery level and state change notifications.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryLevelDidChange:)
name:UIDeviceBatteryLevelDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryStateDidChange:)
name:UIDeviceBatteryStateDidChangeNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}

- (NSNumberFormatter *)numberFormatter
{
    if (numberFormatter == nil)
    {
        numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
        [numberFormatter setMaximumFractionDigits:1];
    }
    return numberFormatter;
}

#pragma mark - Switch action handler

- (void)switchAction:(id)sender
{
    if ([sender isOn])
    {
        [UIDevice currentDevice].batteryMonitoringEnabled = YES;
// The UI will be updated as a result of the first notification.
    }
    else {
        [UIDevice currentDevice].batteryMonitoringEnabled = NO;
[self.tableView reloadData];
    }
}

#pragma mark - Battery notifications

- (void)batteryLevelDidChange:(NSNotification *)notification
{
[self.tableView reloadData];
}


- (void)batteryStateDidChange:(NSNotification *)notification
{
[self.tableView reloadData];
}


#pragma mark - UITableView delegates

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *title = nil;
switch (section)
{
case kBatteryStateSection:
{
title = NSLocalizedString(@"Battery State", @"");
break;
}
}
return title;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rowCount = 1;
if (section == kBatteryStateSection)
{
rowCount = 4;
}
return rowCount;
}

static NSInteger kLevelTag = 2;

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
static NSString *kMonitoringCellIdentifier = @"Monitoring";
static NSString *kLevelCellIdentifier = @"Level";
static NSString *kStateCellIdentifier = @"State";
   
UITableViewCell *cell = nil;
switch (indexPath.section)
{
case kMonitoringSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kMonitoringCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMonitoringCellIdentifier] autorelease];
cell.textLabel.text = NSLocalizedString(@"Monitoring", @"");
UISwitch *switchCtl = [[[UISwitch alloc] initWithFrame:CGRectMake(197, 8, 94, 27)] autorelease];
[switchCtl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
switchCtl.backgroundColor = [UIColor clearColor];

[cell.contentView addSubview:switchCtl];
}
break;
}
case kLevelSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kLevelCellIdentifier];
UILabel *levelLabel = nil;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kLevelCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = NSLocalizedString(@"Level", @"");
levelLabel = [[[UILabel alloc] initWithFrame:CGRectMake(171, 11, 120, 21)] autorelease];
levelLabel.tag = kLevelTag;
levelLabel.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview:levelLabel];
levelLabel.backgroundColor = [UIColor clearColor];
}
else {
levelLabel = (UILabel *) [cell.contentView viewWithTag:kLevelTag];
}

float batteryLevel = [UIDevice currentDevice].batteryLevel;
if (batteryLevel < 0.0)
{
// -1.0 means battery state is UIDeviceBatteryStateUnknown
levelLabel.text = NSLocalizedString(@"Unknown", @"");
}
else {
NSNumber *levelObj = [NSNumber numberWithFloat:batteryLevel];
// Using the numberFormatter property lazily creates that object the
// first time it's used. 
levelLabel.text = [self.numberFormatter stringFromNumber:levelObj];
}
break;
}
case kBatteryStateSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kStateCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kStateCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"StatusClear.png"]] autorelease];
}
switch (indexPath.row)
{
case 0:
{
cell.textLabel.text = NSLocalizedString(@"Unknown", @"");
break;
}
case 1:
{
cell.textLabel.text = NSLocalizedString(@"Unplugged", @"");
break;
}
case 2:
{
cell.textLabel.text = NSLocalizedString(@"Charging", @"");
break;
}
case 3:
{
cell.textLabel.text = NSLocalizedString(@"Full", @"");
break;
}
}
UIImageView *statusImageView = (UIImageView *) cell.accessoryView;
if (indexPath.row + UIDeviceBatteryStateUnknown == [UIDevice currentDevice].batteryState)
{
statusImageView.image = [UIImage imageNamed:@"StatusGreen.png"];
}
else {
statusImageView.image = [UIImage imageNamed:@"StatusClear.png"];
}
break;
}
}
    
// Set attributes common to all cell types.
cell.selectionStyle = UITableViewCellSelectionStyleNone;

return cell;
}


@end



------------------------------------------------------------

BatteryStatusAppDelegate.h

 
@interface BatteryStatusAppDelegate : NSObject <UIApplicationDelegate>
{
    UIWindow *window;
    UINavigationController *navigationController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@end


------------------------------------------------------------
BatteryStatusAppDelegate.m


 
#import "BatteryStatusAppDelegate.h"
#import "RootViewController.h"


@implementation BatteryStatusAppDelegate

@synthesize window;
@synthesize navigationController;

#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
    // Override point for customization after app launch    
[window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
[navigationController release];
[window release];
[super dealloc];
}


@end



------------------------------------------------------------
Copyright (C) 2010 Apple Inc. All Rights Reserved.




 

No comments:

Post a Comment