SlideShare a Scribd company logo
1 of 48
THAT’S MY APP
       ~
RUNNING IN YOUR
 BACKGROUND
       ~
 DRAINING YOUR
   BATTERY
WHO AM I?
    Michael Galpin
 Mobile Architect, eBay
Author, Android in Practice

       @michaelg
AGENDA


Motivation

Strategies

Death

Resurrection

Advanced
TRUE MULTI-TASKING

          Multiple applications,
          executing
          simultaneously

            Consuming memory

            CPU cycles (battery)

            Using I/O

          But not like Desktop
DATA SYNC

     Apps don’t live in a
     vacuum

       Users use other
       apps / website

       Other users interact

     Keep data sync

     Improve user experience
LOOK MA, NO HANDS


Start your app without
the user launching it

Extend app execution
after app is closed (long
running tasks)

Interact with other apps
STRATEGIES
SERVICES 101

<manifest>
    <application android:icon="@drawable/icon"
         android:label="@string/app_name">
        <service android:process=":stocks_background"
             android:name=".PortfolioManagerService"
             android:icon="@drawable/icon"
             android:label="@string/service_name"/>
<!-- ... -->
</manifest>
SERVICES 101
public class PortfolioManagerService extends Service {

    @Override
    public void onCreate() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags,
        int startId) {
    }

    @Override
    public IBinder onBind(Intent intent) {
    }

}
POLLING
@Override
public void onCreate() {
    super.onCreate();
    final long fiveMinutes = 5*60*1000;
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable(){
        public void run(){
            updateStockData();
            handler.postDelayed(this, fiveMinutes);
        }
    }, fiveMinutes);
}
NOTIFICATIONS
private void createHighPriceNotification(Stock stock) {
    // Get the system service
    NotificationManager mgr = (NotificationManager)
        getSystemService(Context.NOTIFICATION_SERVICE);
    // Create the ticker
    int dollarBill = R.drawable.dollar_icon;
    String shortMsg = "High price alert: " + stock.getSymbol();
    long time = System.currentTimeMillis();
    Notification n = new Notification(dollarBill, shortMsg, time);
    // Create expanded info and what happens when tapped
    String title = stock.getName();
    String msg = "Current price $" + stock.getCurrentPrice() +
        " is high";
    Intent i = new Intent(this, NotificationDetails.class);
    i.putExtra("stock", stock);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
    n.setLatestEventInfo(this, title, msg, pi);
    // Sound!
    n.defaults |= Notification.DEFAULT_SOUND;
    // Vibrate!!
    long[] steps = {0, 500, 100, 200, 100, 200};
    n.vibrate = steps;
    // Flashing LED lights !!!
    n.ledARGB = 0x80009500;
    n.ledOnMS = 250;
    n.ledOffMS = 500;
    n.flags |= Notification.FLAG_SHOW_LIGHTS;
    // Post the Notification
    mgr.notify(HIGH_PRICE_NOTIFICATION, n);
}
START ME UP!
<receiver android:name="PortfolioStartupReceiver"
    android:process=":stocks_background">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
</receiver>



    public class PortfolioStartupReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Intent stockService =
                new Intent(context, PortfolioManagerService.class);
            context.startService(stockService);
        }

    }
TANGENT




<receiver android:name="InstallReceiver"
    android:process=":stocks_background">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER"/>
        </intent-filter>
</receiver>
DATA MANAGEMENT

        Service and app use the
        same data

        Use the Service for any
        access

        Service can cache data

        Pre-emptive retrieval
ACTIVITY -> SERVICE
                COMMUNICATION
public class Stock implements Parcelable{
    // fields, getter, setters
    private Stock(Parcel parcel){
         this.readFromParcel(parcel);
    }
    public static final Parcelable.Creator<Stock> CREATOR =
       new Parcelable.Creator<Stock>() {
         public Stock createFromParcel(Parcel source) {
             return new Stock(source);
                                                                          Stock.aidl
         }
         public Stock[] newArray(int size) {                        package com.flexware.stocks;
             return new Stock[size];
         }                                                          parcelable Stock;
    };
    public int describeContents() {
         return 0; // nothing special here!                         IStockService.aidl
    }
    public void writeToParcel(Parcel parcel, int flags) {     package com.flexware.stocks.service;
         parcel.writeString(symbol);
         parcel.writeDouble(maxPrice);                        import com.flexware.stocks.Stock;
         parcel.writeDouble(minPrice);
         ...                                                  interface IStockService{
    }
                                                                  Stock addToPortfolio(in Stock stock);
    public void readFromParcel(Parcel parcel){
         symbol = parcel.readString();                            List<Stock> getPortfolio();
         maxPrice = parcel.readDouble();                      }
         minPrice = parcel.readDouble();
         ...
    }
}
ACTIVITY -> SERVICE
              COMMUNICATION
 Generated
public interface IStockService extends IInterface{
    /** Local-side IPC implementation stub class. */
    public static abstract class Stub extends Binder implements IStockService{
    }
}



public class PortfolioManagerService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return new IStockService.Stub() {
            public Stock addToPortfolio(Stock stock) throws RemoteException {
                ...
            }

             public List<Stock> getPortfolio() throws RemoteException {
                 ...
             }
        };
    }
}
ACTIVITY -> SERVICE
  COMMUNICATION
public class ViewStocks extends ListActivity {
    private IStockService stockService;
    private ServiceConnection connection = new ServiceConnection(){
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            stockService = IStockService.Stub.asInterface(service);
            stocks = stockService.getPortfolio();
            refreshUi();
        }
        public void onServiceDisconnected(ComponentName className) {
            stockService = null;
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        bindService(new Intent(IStockService.class.getName()), connection,
                Context.BIND_AUTO_CREATE);
    }
SOMETIMES AIDL IS
      OVERKILL

Service binding only
needed for if you need
data from Service

  Activity -> Service

  Service -> Service

Otherwise consider
IntentService
DON’T BUILD THIS
   YOURSELF!

                        Task
                        Task
                        Task
  AIDL ?   Service      Task
                        Task
                        Task




                     IO (Network, Disk)
DON’T BUILD THIS
   YOURSELF!

                               Task


                  Intent
                               Task
                               Task
Intent   AIDL ?   Service      Task
                               Task
                               Task




                            IO (Network, Disk)
USING AN
                           INTENTSERVICE
public static class StockActivity extends Activity{         public class AddStockService extends IntentService {
	   private Stock stock;
	   @Override                                               	   private static final String NAME = "AddStockService";
	   public void onCreate(Bundle savedInstance){             	   public static final String EXTRA_STOCK = "Stock";
	   	    Button button = (Button) findViewById(R.id.btn);   	
	   	    button.setOnClickListener(new OnClickListener(){   	   public AddStockService(){
                                                            	   	   super(NAME);
	   	   	     @Override                                     	   }
	   	   	     public void onClick(View v) {                 	
	   	   	     	   Intent request =                          	   @Override
	   	   	     	   	    new Intent(StockActivity.this,       	   protected void onHandleIntent(Intent request) {
                             AddStockService.class);        	   	   Stock stock =
	   	   	     	   request.putExtra(EXTRA_STOCK, stock);                 request.getParcelableExtra(EXTRA_STOCK);
	   	   	     	   startService(request);                    	   	   StocksDb db = new StocksDb(this);
	   	   	     }                                             	   	   db.addStock(stock);
	   	   	                                                   	   }
	   	   });                                                 }
	   }
}
DEATH OF A SERVICE
PSYCHOPATHIC USERS

Settings ->
Applications ->
Running
Services ->
KILL!

3rd Party “Task
Managers”

FUD (Thanks
Apple)
MANAGE SERVICES
PROCESS
PRIORITIZATION
    Foreground

      Visible


      Service

    Background
      Empty
PROCESS
PRIORITIZATION
    Foreground

      Visible


      Service

    Background
      Empty
PROCESS
PRIORITIZATION
    Foreground

      Visible


      Service

    Background
      Empty
PROCESS
PRIORITIZATION
    Foreground

      Visible


      Service

    Background
      Empty
PROCESS
PRIORITIZATION
    Foreground

      Visible


      Service

    Background
      Empty
PROCESS
PRIORITIZATION
    Foreground

      Visible


      Service

    Background
      Empty
RESURRECTION
CONCEPT: USE THE OS
HELLO
       ALARMMANAGER!

public class PortfolioStartupReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        AlarmManager mgr =
            (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, AlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0,
                i, PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, 2);
        long fifteenMinutesInMillis = 15*60*1000;
        mgr.setRepeating(AlarmManager.RTC_WAKEUP,
                now.getTimeInMillis(), fifteenMinutesInMillis, sender);
    }
}
SLEEP IS FOR THE WEAK!
public class AlarmReceiver extends BroadcastReceiver {
    private static PowerManager.WakeLock wakeLock = null;
    private static final String LOCK_TAG = "com.flexware.stocks";
    public static synchronized void acquireLock(Context ctx){
        if (wakeLock == null){
            PowerManager mgr = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
            wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_TAG);
            wakeLock.setReferenceCounted(true);
        }
        wakeLock.acquire();
    }
    public static synchronized void releaseLock(){
        if (wakeLock != null){
            wakeLock.release();
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        acquireLock(context);
        Intent stockService =
            new Intent(context, PortfolioManagerService.class);
        context.startService(stockService);
    }

}
SHARING A WAKELOCK
public class PortfolioManagerService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        updateStockData();
        return Service.START_STICKY;
    }
    private void updateStockData(){
       try{
           ...
        } finally {
            AlarmReceiver.releaseLock();
            stopSelf();
        }
    }
}
STRATEGY: THE SHORT-
   LIVED SERVICE
           Start at device boot

           Use AlarmManager

             Start early and often

           Stop Service when work
           is done

             Fly under the radar

             Use IntentService?
ADVANCED
DIY PUSH

Persistent TCP
connection

Long-lived service

  Frequent alarms

  Keep-alives, re-
  connect

Always in-sync
CLOUD TO DEVICE
MESSAGING (C2DM)

         Requires Android 2.2

           At runtime, not
           compile-time

         Send data directly to
         device

         Requires server
         component
C2DM
<receiver android:name=".PushReceiver"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name=
            "com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.flexware.stocks" />
    </intent-filter>
    <intent-filter>
        <action android:name=
            "com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="com.flexware.stocks" />
    </intent-filter>
</receiver>
...
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<permission android:name="com.flexware.stocks.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.flexware.stocks.permission.C2D_MESSAGE"/>
<uses-permission android:name=
    "com.google.android.c2dm.permission.RECEIVE"/>
C2DM
public class PushReceiver extends BroadcastReceiver {
	   @Override
	   public void onReceive(Context context, Intent intent) {
	   	   AlarmReceiver.acquireLock(context);
	       if (intent.getAction().equals(
	       	 	     "com.google.android.c2dm.intent.REGISTRATION")) {
	           onRegistration(context, intent);
	       } else if (intent.getAction().equals(
	       	 	     "com.google.android.c2dm.intent.RECEIVE")) {
	           onMessage(context, intent);
	         }
	     }
	   private void onRegistration(Context context, Intent intent) {
	   	   String regId = intent.getStringExtra("registration_id");
	   	   if (regId != null) {
	   	   	   Intent i = new Intent(context, SendC2dmRegistrationService.class);
	   	   	   i.putExtra("regId", regId);
	   	   	   context.startService(i);
	   	   }
	   }

	   private void onMessage(Context context, Intent intent){
	   	   Intent stockService =
	   	   	   new Intent(context, PortfolioManagerService.class);
	   	   // copy any data sent from your server
	   	   stockService.putExtras(intent);
	   	   context.startService(stockService);
	   }
}
C2DM REGISTRATION
                              Device
Broadcast registration            C2DM
                                                2

Intent                            Service




                          1                 3
C2DM service sends
request to Google             MyService


                                                    C2DM Servers

Receive registration
                              4
response (Intent)

Send registration ID to
                              My Servers

your servers
C2DM RUNTIME EVENTS
                           Device
                                            2
Send data to Google         C2DM
                            Service




  Good ‘ol HTTP            3



Pushed from C2DM           MyService




server to device service                        C2DM Servers



over persistent conn

Broadcasts Intent to
your Service               My Servers

                                        1
STRATEGY: REMOTE
     RESURRECTION
Use C2DM

Send minimal Intents

  Start (short
  lived)Service
  (IntentService?)

    Retrieve/sync data

    Notifications

Activity only use cache
RESOURCES


Android in Practice

  http://www.manning.com/collins

  http://code.google.com/p/android-in-practice/

CommonsWare http://commonsware.com/
AndTutorials/

More Related Content

What's hot

#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTDavid Chandler
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Vaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowVaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowJoonas Lehtinen
 
Average- An android project
Average- An android projectAverage- An android project
Average- An android projectIpsit Dash
 
Easy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkEasy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkZeroTurnaround
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Kirill Rozov
 
Iddd domain service
Iddd domain serviceIddd domain service
Iddd domain serviceEric Huang
 

What's hot (20)

Introduction toandroid
Introduction toandroidIntroduction toandroid
Introduction toandroid
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Swing database(mysql)
Swing database(mysql)Swing database(mysql)
Swing database(mysql)
 
Vaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowVaadin 7 Today and Tomorrow
Vaadin 7 Today and Tomorrow
 
Phactory
PhactoryPhactory
Phactory
 
Average- An android project
Average- An android projectAverage- An android project
Average- An android project
 
Mysql
MysqlMysql
Mysql
 
Lab2-DB-Mongodb
Lab2-DB-MongodbLab2-DB-Mongodb
Lab2-DB-Mongodb
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
Android wear (coding)
Android wear (coding)Android wear (coding)
Android wear (coding)
 
Easy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkEasy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip Ozturk
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2
 
Iddd domain service
Iddd domain serviceIddd domain service
Iddd domain service
 

Viewers also liked

Jisc RSC Wales ISS 260213
Jisc RSC Wales ISS 260213Jisc RSC Wales ISS 260213
Jisc RSC Wales ISS 260213Lis Parcell
 
ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...
ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...
ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...Hendrik Drachsler
 
Web Service on SSD
Web Service on SSDWeb Service on SSD
Web Service on SSDKazuho Oku
 
Egitimler
EgitimlerEgitimler
Egitimleranttab
 
Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...
Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...
Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...Martin Rehm
 
Unified in Learning –Separated by Space
Unified in Learning –Separated by SpaceUnified in Learning –Separated by Space
Unified in Learning –Separated by SpaceMartin Rehm
 
2.1 Web Programming - InternetBasics
2.1 Web Programming - InternetBasics2.1 Web Programming - InternetBasics
2.1 Web Programming - InternetBasicsIntan Jameel
 
2010 National Latin Exam Information
2010 National Latin Exam Information2010 National Latin Exam Information
2010 National Latin Exam InformationNSellers1
 
Типичные ошибки продвижения проекта в Интернете — Максим Спиридонов
Типичные ошибки продвижения проекта в Интернете — Максим СпиридоновТипичные ошибки продвижения проекта в Интернете — Максим Спиридонов
Типичные ошибки продвижения проекта в Интернете — Максим СпиридоновMaria Podolyak
 
تفريغ دورة فريق العمل الفعال
تفريغ دورة فريق العمل الفعالتفريغ دورة فريق العمل الفعال
تفريغ دورة فريق العمل الفعالHani Al-Menaii
 
Two Options - One Virtual World
Two Options - One Virtual WorldTwo Options - One Virtual World
Two Options - One Virtual WorldMartin Rehm
 
Hay vida antes del Community Manager
Hay vida antes del Community ManagerHay vida antes del Community Manager
Hay vida antes del Community ManagerDavinia Suárez
 
Socialist Software Development - RubyConf 2010
Socialist Software Development - RubyConf 2010Socialist Software Development - RubyConf 2010
Socialist Software Development - RubyConf 2010CJ Kihlbom
 
The Future of Big Data in Education
The Future of Big Data in EducationThe Future of Big Data in Education
The Future of Big Data in EducationHendrik Drachsler
 

Viewers also liked (20)

Jisc RSC Wales ISS 260213
Jisc RSC Wales ISS 260213Jisc RSC Wales ISS 260213
Jisc RSC Wales ISS 260213
 
ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...
ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...
ReMashed – Recommendation Approaches for Mash-Up Personal Learning Environmen...
 
Web Service on SSD
Web Service on SSDWeb Service on SSD
Web Service on SSD
 
Egitimler
EgitimlerEgitimler
Egitimler
 
Scaling
ScalingScaling
Scaling
 
Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...
Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...
Case Study on a Global Learning Program (OnlineEduca 2008 Conference Proceedi...
 
Unified in Learning –Separated by Space
Unified in Learning –Separated by SpaceUnified in Learning –Separated by Space
Unified in Learning –Separated by Space
 
2.1 Web Programming - InternetBasics
2.1 Web Programming - InternetBasics2.1 Web Programming - InternetBasics
2.1 Web Programming - InternetBasics
 
Mwomen
MwomenMwomen
Mwomen
 
2010 National Latin Exam Information
2010 National Latin Exam Information2010 National Latin Exam Information
2010 National Latin Exam Information
 
Типичные ошибки продвижения проекта в Интернете — Максим Спиридонов
Типичные ошибки продвижения проекта в Интернете — Максим СпиридоновТипичные ошибки продвижения проекта в Интернете — Максим Спиридонов
Типичные ошибки продвижения проекта в Интернете — Максим Спиридонов
 
تفريغ دورة فريق العمل الفعال
تفريغ دورة فريق العمل الفعالتفريغ دورة فريق العمل الفعال
تفريغ دورة فريق العمل الفعال
 
Two Options - One Virtual World
Two Options - One Virtual WorldTwo Options - One Virtual World
Two Options - One Virtual World
 
Hay vida antes del Community Manager
Hay vida antes del Community ManagerHay vida antes del Community Manager
Hay vida antes del Community Manager
 
Pero florecera
Pero floreceraPero florecera
Pero florecera
 
Origen, filosofía
Origen, filosofíaOrigen, filosofía
Origen, filosofía
 
Lezione 2011
Lezione 2011Lezione 2011
Lezione 2011
 
M02 un04 p02
M02 un04 p02M02 un04 p02
M02 un04 p02
 
Socialist Software Development - RubyConf 2010
Socialist Software Development - RubyConf 2010Socialist Software Development - RubyConf 2010
Socialist Software Development - RubyConf 2010
 
The Future of Big Data in Education
The Future of Big Data in EducationThe Future of Big Data in Education
The Future of Big Data in Education
 

Similar to That’s My App - Running in Your Background - Draining Your Battery

Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developersPavel Lahoda
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon Berlin
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseYonatan Levin
 
IPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseIPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseYonatan Levin
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragmentChiwon Song
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012Amazon Web Services
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your appsJuan C Catalan
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityWashington Botelho
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - AndroidWingston
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 

Similar to That’s My App - Running in Your Background - Draining Your Battery (20)

Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
 
IPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseIPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curse
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your apps
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Android - Api & Debugging in Android
Android - Api & Debugging in AndroidAndroid - Api & Debugging in Android
Android - Api & Debugging in Android
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - Android
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Day 5
Day 5Day 5
Day 5
 

More from Michael Galpin

Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in schoolMichael Galpin
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Scala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesScala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesMichael Galpin
 
Persistent Data Structures And Managed References
Persistent Data Structures And Managed ReferencesPersistent Data Structures And Managed References
Persistent Data Structures And Managed ReferencesMichael Galpin
 
Mobile Development 101
Mobile Development 101Mobile Development 101
Mobile Development 101Michael Galpin
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTMichael Galpin
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 

More from Michael Galpin (11)

Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in school
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Scala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesScala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump Technologies
 
Mobile Web 5.0
Mobile Web 5.0Mobile Web 5.0
Mobile Web 5.0
 
Persistent Data Structures And Managed References
Persistent Data Structures And Managed ReferencesPersistent Data Structures And Managed References
Persistent Data Structures And Managed References
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
 
Mobile Development 101
Mobile Development 101Mobile Development 101
Mobile Development 101
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWT
 
Eclipse @eBay 2009
Eclipse @eBay 2009Eclipse @eBay 2009
Eclipse @eBay 2009
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Eclipse@eBay
Eclipse@eBayEclipse@eBay
Eclipse@eBay
 

Recently uploaded

Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...ssuserf63bd7
 
1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdf1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdfShaun Heinrichs
 
Effective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold JewelryEffective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold JewelryWhittensFineJewelry1
 
Cyber Security Training in Office Environment
Cyber Security Training in Office EnvironmentCyber Security Training in Office Environment
Cyber Security Training in Office Environmentelijahj01012
 
Introducing the Analogic framework for business planning applications
Introducing the Analogic framework for business planning applicationsIntroducing the Analogic framework for business planning applications
Introducing the Analogic framework for business planning applicationsKnowledgeSeed
 
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxGo for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxRakhi Bazaar
 
trending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdf
trending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdftrending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdf
trending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdfMintel Group
 
digital marketing , introduction of digital marketing
digital marketing , introduction of digital marketingdigital marketing , introduction of digital marketing
digital marketing , introduction of digital marketingrajputmeenakshi733
 
Healthcare Feb. & Mar. Healthcare Newsletter
Healthcare Feb. & Mar. Healthcare NewsletterHealthcare Feb. & Mar. Healthcare Newsletter
Healthcare Feb. & Mar. Healthcare NewsletterJamesConcepcion7
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03DallasHaselhorst
 
business environment micro environment macro environment.pptx
business environment micro environment macro environment.pptxbusiness environment micro environment macro environment.pptx
business environment micro environment macro environment.pptxShruti Mittal
 
Darshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdfDarshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdfShashank Mehta
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...Hector Del Castillo, CPM, CPMM
 
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxThe-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxmbikashkanyari
 
WSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdfWSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdfJamesConcepcion7
 
WSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfWSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfJamesConcepcion7
 
Planetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifePlanetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifeBhavana Pujan Kendra
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFChandresh Chudasama
 

Recently uploaded (20)

Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
Intermediate Accounting, Volume 2, 13th Canadian Edition by Donald E. Kieso t...
 
1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdf1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdf
 
Effective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold JewelryEffective Strategies for Maximizing Your Profit When Selling Gold Jewelry
Effective Strategies for Maximizing Your Profit When Selling Gold Jewelry
 
Cyber Security Training in Office Environment
Cyber Security Training in Office EnvironmentCyber Security Training in Office Environment
Cyber Security Training in Office Environment
 
Introducing the Analogic framework for business planning applications
Introducing the Analogic framework for business planning applicationsIntroducing the Analogic framework for business planning applications
Introducing the Analogic framework for business planning applications
 
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptxGo for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
Go for Rakhi Bazaar and Pick the Latest Bhaiya Bhabhi Rakhi.pptx
 
trending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdf
trending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdftrending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdf
trending-flavors-and-ingredients-in-salty-snacks-us-2024_Redacted-V2.pdf
 
digital marketing , introduction of digital marketing
digital marketing , introduction of digital marketingdigital marketing , introduction of digital marketing
digital marketing , introduction of digital marketing
 
Healthcare Feb. & Mar. Healthcare Newsletter
Healthcare Feb. & Mar. Healthcare NewsletterHealthcare Feb. & Mar. Healthcare Newsletter
Healthcare Feb. & Mar. Healthcare Newsletter
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03
 
business environment micro environment macro environment.pptx
business environment micro environment macro environment.pptxbusiness environment micro environment macro environment.pptx
business environment micro environment macro environment.pptx
 
Darshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdfDarshan Hiranandani [News About Next CEO].pdf
Darshan Hiranandani [News About Next CEO].pdf
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
How Generative AI Is Transforming Your Business | Byond Growth Insights | Apr...
 
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxThe-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
 
WSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdfWSMM Technology February.March Newsletter_vF.pdf
WSMM Technology February.March Newsletter_vF.pdf
 
WSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdfWSMM Media and Entertainment Feb_March_Final.pdf
WSMM Media and Entertainment Feb_March_Final.pdf
 
Planetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in LifePlanetary and Vedic Yagyas Bring Positive Impacts in Life
Planetary and Vedic Yagyas Bring Positive Impacts in Life
 
WAM Corporate Presentation April 12 2024.pdf
WAM Corporate Presentation April 12 2024.pdfWAM Corporate Presentation April 12 2024.pdf
WAM Corporate Presentation April 12 2024.pdf
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDF
 

That’s My App - Running in Your Background - Draining Your Battery

  • 1. THAT’S MY APP ~ RUNNING IN YOUR BACKGROUND ~ DRAINING YOUR BATTERY
  • 2. WHO AM I? Michael Galpin Mobile Architect, eBay Author, Android in Practice @michaelg
  • 3.
  • 5.
  • 6. TRUE MULTI-TASKING Multiple applications, executing simultaneously Consuming memory CPU cycles (battery) Using I/O But not like Desktop
  • 7. DATA SYNC Apps don’t live in a vacuum Users use other apps / website Other users interact Keep data sync Improve user experience
  • 8. LOOK MA, NO HANDS Start your app without the user launching it Extend app execution after app is closed (long running tasks) Interact with other apps
  • 10. SERVICES 101 <manifest> <application android:icon="@drawable/icon" android:label="@string/app_name"> <service android:process=":stocks_background" android:name=".PortfolioManagerService" android:icon="@drawable/icon" android:label="@string/service_name"/> <!-- ... --> </manifest>
  • 11. SERVICES 101 public class PortfolioManagerService extends Service { @Override public void onCreate() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { } @Override public IBinder onBind(Intent intent) { } }
  • 12. POLLING @Override public void onCreate() { super.onCreate(); final long fiveMinutes = 5*60*1000; final Handler handler = new Handler(); handler.postDelayed(new Runnable(){ public void run(){ updateStockData(); handler.postDelayed(this, fiveMinutes); } }, fiveMinutes); }
  • 13. NOTIFICATIONS private void createHighPriceNotification(Stock stock) { // Get the system service NotificationManager mgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Create the ticker int dollarBill = R.drawable.dollar_icon; String shortMsg = "High price alert: " + stock.getSymbol(); long time = System.currentTimeMillis(); Notification n = new Notification(dollarBill, shortMsg, time); // Create expanded info and what happens when tapped String title = stock.getName(); String msg = "Current price $" + stock.getCurrentPrice() + " is high"; Intent i = new Intent(this, NotificationDetails.class); i.putExtra("stock", stock); PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0); n.setLatestEventInfo(this, title, msg, pi); // Sound! n.defaults |= Notification.DEFAULT_SOUND; // Vibrate!! long[] steps = {0, 500, 100, 200, 100, 200}; n.vibrate = steps; // Flashing LED lights !!! n.ledARGB = 0x80009500; n.ledOnMS = 250; n.ledOffMS = 500; n.flags |= Notification.FLAG_SHOW_LIGHTS; // Post the Notification mgr.notify(HIGH_PRICE_NOTIFICATION, n); }
  • 14. START ME UP! <receiver android:name="PortfolioStartupReceiver" android:process=":stocks_background"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> public class PortfolioStartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent stockService = new Intent(context, PortfolioManagerService.class); context.startService(stockService); } }
  • 15. TANGENT <receiver android:name="InstallReceiver" android:process=":stocks_background"> <intent-filter> <action android:name="com.android.vending.INSTALL_REFERRER"/> </intent-filter> </receiver>
  • 16. DATA MANAGEMENT Service and app use the same data Use the Service for any access Service can cache data Pre-emptive retrieval
  • 17. ACTIVITY -> SERVICE COMMUNICATION public class Stock implements Parcelable{ // fields, getter, setters private Stock(Parcel parcel){ this.readFromParcel(parcel); } public static final Parcelable.Creator<Stock> CREATOR = new Parcelable.Creator<Stock>() { public Stock createFromParcel(Parcel source) { return new Stock(source); Stock.aidl } public Stock[] newArray(int size) { package com.flexware.stocks; return new Stock[size]; } parcelable Stock; }; public int describeContents() { return 0; // nothing special here! IStockService.aidl } public void writeToParcel(Parcel parcel, int flags) { package com.flexware.stocks.service; parcel.writeString(symbol); parcel.writeDouble(maxPrice); import com.flexware.stocks.Stock; parcel.writeDouble(minPrice); ... interface IStockService{ } Stock addToPortfolio(in Stock stock); public void readFromParcel(Parcel parcel){ symbol = parcel.readString(); List<Stock> getPortfolio(); maxPrice = parcel.readDouble(); } minPrice = parcel.readDouble(); ... } }
  • 18. ACTIVITY -> SERVICE COMMUNICATION Generated public interface IStockService extends IInterface{ /** Local-side IPC implementation stub class. */ public static abstract class Stub extends Binder implements IStockService{ } } public class PortfolioManagerService extends Service { @Override public IBinder onBind(Intent intent) { return new IStockService.Stub() { public Stock addToPortfolio(Stock stock) throws RemoteException { ... } public List<Stock> getPortfolio() throws RemoteException { ... } }; } }
  • 19. ACTIVITY -> SERVICE COMMUNICATION public class ViewStocks extends ListActivity { private IStockService stockService; private ServiceConnection connection = new ServiceConnection(){ public void onServiceConnected(ComponentName className, IBinder service) { stockService = IStockService.Stub.asInterface(service); stocks = stockService.getPortfolio(); refreshUi(); } public void onServiceDisconnected(ComponentName className) { stockService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { ... bindService(new Intent(IStockService.class.getName()), connection, Context.BIND_AUTO_CREATE); }
  • 20.
  • 21. SOMETIMES AIDL IS OVERKILL Service binding only needed for if you need data from Service Activity -> Service Service -> Service Otherwise consider IntentService
  • 22. DON’T BUILD THIS YOURSELF! Task Task Task AIDL ? Service Task Task Task IO (Network, Disk)
  • 23. DON’T BUILD THIS YOURSELF! Task Intent Task Task Intent AIDL ? Service Task Task Task IO (Network, Disk)
  • 24. USING AN INTENTSERVICE public static class StockActivity extends Activity{ public class AddStockService extends IntentService { private Stock stock; @Override private static final String NAME = "AddStockService"; public void onCreate(Bundle savedInstance){ public static final String EXTRA_STOCK = "Stock"; Button button = (Button) findViewById(R.id.btn); button.setOnClickListener(new OnClickListener(){ public AddStockService(){ super(NAME); @Override } public void onClick(View v) { Intent request = @Override new Intent(StockActivity.this, protected void onHandleIntent(Intent request) { AddStockService.class); Stock stock = request.putExtra(EXTRA_STOCK, stock); request.getParcelableExtra(EXTRA_STOCK); startService(request); StocksDb db = new StocksDb(this); } db.addStock(stock); } }); } } }
  • 25. DEATH OF A SERVICE
  • 26. PSYCHOPATHIC USERS Settings -> Applications -> Running Services -> KILL! 3rd Party “Task Managers” FUD (Thanks Apple)
  • 28. PROCESS PRIORITIZATION Foreground Visible Service Background Empty
  • 29. PROCESS PRIORITIZATION Foreground Visible Service Background Empty
  • 30. PROCESS PRIORITIZATION Foreground Visible Service Background Empty
  • 31. PROCESS PRIORITIZATION Foreground Visible Service Background Empty
  • 32. PROCESS PRIORITIZATION Foreground Visible Service Background Empty
  • 33. PROCESS PRIORITIZATION Foreground Visible Service Background Empty
  • 36. HELLO ALARMMANAGER! public class PortfolioStartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, AlarmReceiver.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); Calendar now = Calendar.getInstance(); now.add(Calendar.MINUTE, 2); long fifteenMinutesInMillis = 15*60*1000; mgr.setRepeating(AlarmManager.RTC_WAKEUP, now.getTimeInMillis(), fifteenMinutesInMillis, sender); } }
  • 37. SLEEP IS FOR THE WEAK! public class AlarmReceiver extends BroadcastReceiver { private static PowerManager.WakeLock wakeLock = null; private static final String LOCK_TAG = "com.flexware.stocks"; public static synchronized void acquireLock(Context ctx){ if (wakeLock == null){ PowerManager mgr = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_TAG); wakeLock.setReferenceCounted(true); } wakeLock.acquire(); } public static synchronized void releaseLock(){ if (wakeLock != null){ wakeLock.release(); } } @Override public void onReceive(Context context, Intent intent) { acquireLock(context); Intent stockService = new Intent(context, PortfolioManagerService.class); context.startService(stockService); } }
  • 38. SHARING A WAKELOCK public class PortfolioManagerService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { updateStockData(); return Service.START_STICKY; } private void updateStockData(){ try{ ... } finally { AlarmReceiver.releaseLock(); stopSelf(); } } }
  • 39. STRATEGY: THE SHORT- LIVED SERVICE Start at device boot Use AlarmManager Start early and often Stop Service when work is done Fly under the radar Use IntentService?
  • 41. DIY PUSH Persistent TCP connection Long-lived service Frequent alarms Keep-alives, re- connect Always in-sync
  • 42. CLOUD TO DEVICE MESSAGING (C2DM) Requires Android 2.2 At runtime, not compile-time Send data directly to device Requires server component
  • 43. C2DM <receiver android:name=".PushReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name= "com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.flexware.stocks" /> </intent-filter> <intent-filter> <action android:name= "com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.flexware.stocks" /> </intent-filter> </receiver> ... <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET"/> <permission android:name="com.flexware.stocks.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.flexware.stocks.permission.C2D_MESSAGE"/> <uses-permission android:name= "com.google.android.c2dm.permission.RECEIVE"/>
  • 44. C2DM public class PushReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AlarmReceiver.acquireLock(context); if (intent.getAction().equals( "com.google.android.c2dm.intent.REGISTRATION")) { onRegistration(context, intent); } else if (intent.getAction().equals( "com.google.android.c2dm.intent.RECEIVE")) { onMessage(context, intent); } } private void onRegistration(Context context, Intent intent) { String regId = intent.getStringExtra("registration_id"); if (regId != null) { Intent i = new Intent(context, SendC2dmRegistrationService.class); i.putExtra("regId", regId); context.startService(i); } } private void onMessage(Context context, Intent intent){ Intent stockService = new Intent(context, PortfolioManagerService.class); // copy any data sent from your server stockService.putExtras(intent); context.startService(stockService); } }
  • 45. C2DM REGISTRATION Device Broadcast registration C2DM 2 Intent Service 1 3 C2DM service sends request to Google MyService C2DM Servers Receive registration 4 response (Intent) Send registration ID to My Servers your servers
  • 46. C2DM RUNTIME EVENTS Device 2 Send data to Google C2DM Service Good ‘ol HTTP 3 Pushed from C2DM MyService server to device service C2DM Servers over persistent conn Broadcasts Intent to your Service My Servers 1
  • 47. STRATEGY: REMOTE RESURRECTION Use C2DM Send minimal Intents Start (short lived)Service (IntentService?) Retrieve/sync data Notifications Activity only use cache
  • 48. RESOURCES Android in Practice http://www.manning.com/collins http://code.google.com/p/android-in-practice/ CommonsWare http://commonsware.com/ AndTutorials/