Posts Tagged ‘Android’
[DevoxxFR2012] Advanced Android Patterns: Mastering Services, Content Providers, and Asynchronous Operations
Lecturer
Mathias Seguy founded Android2EE, specializing in Android training, expertise, and consulting. Holding a PhD in Fundamental Mathematics and an engineering degree from ENSEEIHT, he transitioned from critical J2EE projects—serving as technical expert, manager, project leader, and technical director—to focus on Android. Mathias authored multiple books on Android development, available via Android2ee.com, and contributes articles to Developpez.com.
Abstract
This article delves into Mathias Seguy’s continuation of essential Android development concepts, emphasizing services for background tasks, content providers for data sharing, and patterns for lifecycle synchronization. Building on foundational elements, it analyzes implementation strategies for bound/unbound services, CRUD operations in providers, and thread management with handlers/AsyncTasks. Within Android’s resource-constrained environment, the discussion evaluates techniques for internationalization, resource optimization, and database integration. Through detailed code examples, it assesses implications for application responsiveness, data integrity, and cross-app interoperability, guiding developers toward efficient, maintainable architectures.
Implementing Services for Background Processing
Services enable persistent operations independent of UI, running in the application’s main thread—necessitating offloading to avoid ANRs. Mathias distinguishes unbound (started via startService(), autonomous) from bound (via bindService(), allowing communication).
Lifecycle binding is critical: Align service states with calling components using booleans for running/pausing. Code for an unbound service:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start task
return START_STICKY; // Restart if killed
}
@Override
public void onDestroy() {
// Cleanup
}
}
Bound services use Binder for IPC:
public class MyBoundService extends Service {
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyBoundService getService() {
return MyBoundService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
These ensure tasks like downloads persist, enhancing user experience without freezing interfaces.
Crafting Content Providers for Data Exposure
Content providers standardize data access across apps, using URIs for queries. Mathias outlines creation: Extend ContentProvider, define URIs via UriMatcher.
CRUD implementation:
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(DBHelper.MY_TABLE);
if (matcher.match(uri) == ITEM) {
qb.appendWhere(DBHelper.ID + "=" + uri.getLastPathSegment());
}
return db.query(qb.getTables(), projection, qb.getWhere(), selectionArgs, null, null, sortOrder);
}
Manifest declaration:
<provider
android:name=".MyProvider"
android:authorities="com.example.provider"
android:exported="true"
android:readPermission="com.example.READ"
android:writePermission="com.example.WRITE" />
This facilitates secure sharing, like contacts or media, promoting modular ecosystems.
Asynchronous Patterns and Resource Management
Asynchrony prevents UI blocks: Handlers for UI updates, AsyncTasks for background work. Pattern: Bind threads to activity lifecycles with flags.
onRetainNonConfigurationInstance() passes objects across rotations (pre-Fragments):
@Override
public Object onRetainNonConfigurationInstance() {
return myThread;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myThread = (MyThread) getLastNonConfigurationInstance();
if (myThread == null) {
myThread = new MyThread();
}
}
Resources: Externalize strings in values/strings.xml for localization; use qualifiers like values-fr for French.
These patterns optimize for device variability, ensuring fluid performance.
Database Integration and Permissions
SQLite via SQLiteOpenHelper manages schemas:
public class DBHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + MY_TABLE + " (_id INTEGER PRIMARY KEY, name TEXT);");
}
}
Permissions in manifest control access, balancing security with functionality.
Testing and Project Management Strategies
Unit tests with JUnit; instrumentation via AndroidJUnitRunner. Maven for builds, Hudson/Jenkins for CI.
Implications: These foster reliable apps, mitigating fragmentation. In enterprise mobility, they enable scalable, secure solutions.
Mathias’s methodical breakdown equips developers for real-world challenges.
Links:
Move AVD default location on Windows
Two days ago, I twitted this:
Windows I hate you “PANIC: Could not open AVD config file”
Indeed, I tried to run an AVD (Android Virtual Device) from IntelliJ IDEA, in order to test my Android application. So far, I always ran AVD from KUbuntu, but a specific need I had to run on Windows Seven. The emulator could not start, because it was searching the actual AVD img file in the default folder, eg C:\Documents and Settings\<yourLogin>\.android\avd on Windows XP. Unfortunately, the folder could not be retrieved (a story of French special characters, such as ‘é’, ‘è’, ‘ç’, etc.).
Therefore, the question is: on Windows, how to change AVD default location?
I tried many more or less tricky solutions, but the simplest is the following:
- close IDEA and AVD Manager
- create an environment variable
ANDROID_SDK_HOME(keys Windows + Pause), pointing to your target folder, eg:D:\workarea\honeycomb-sdk - create a
.androidsubfolder, eg:D:\workarea\honeycomb-sdk\.android- if Windows does not allow you to create a folder of which name starts with a dot, then create it through Cygwin’s
mkdir.
- if Windows does not allow you to create a folder of which name starts with a dot, then create it through Cygwin’s
- startup IDEA
Restore GingerBread on a Nexus S “bricked” by CyanoGen
Case
After rooting my Nexus S, I tried to flash the ROM, in order to replace the genuine GingerBread with a CyanoGen ehanced version. This worked pretty well, but for a amazing reason I do not know, I missed the so-called “GApps”: GMail, GMaps, etc., this way a Nexus S (or any other Android-driven mobile device) losing any interest. Then, it was the worst catastrophic epiphenomenon I might fear: the Nexus was “bricked”. Indeed, the splash screen, with the Android robot on a skate, did not stop from looping…
Brick, Block and Pitfall
I tried to restore CyanoGen, wipe the memory, etc., but nothing efficient. At last I decided to restore a genuine Gingerbread version.
Here is the puzzling block that stands on the road: a Nexus S does not contain an actual (I mean physical) SD memory card. The “virtual” SD card must be mounted via ADB. But ADB does not recognize the device, since the Nexus is “bricked”. The only access to the Nexus appears to be FastBoot… which does not recognize the /sdcard folder. And the circle is complete.
As you understand, the key is to be able to mount /sdcard, which is sufficient to copy a ROM, and then apply it as a regular update.
Fix
Here we assume you have a minimal knownledge on how to use ADB and FastBoot:
- Download
recovery-clockwork-3.0.2.4-crespo.img - Download GingerBread original ROM:
da8206299fe6.signed-soju-ota-121341.da820629.zip - Switch on your Nexus in recovery mode (sound up and on/off buttons at the same time)
- Select “
recovery“ - Connect it to your PC
- On the PC:
fastboot boot ~/recovery-clockwork-3.0.2.4-crespo.img - Your phone reboots with a yellow on black console.
- Select “mounts and storage” > “mount usb storage”
- Now your PC detects the phone as a regular mass storage device.
- Copy GingerBread ROM to /sdcard folder.
- Rename it as
update.zip(optionnal, easier for the next step)
- On the PC:
fastboot boot ~/recovery-clockwork-3.0.2.4-crespo.img - On the phone,
- select the option “
apply update“ - select
update.zip
- select the option “
- Restart the phone
- If the phone freezes a long time, shut it down and switch it on again
- Now the regular Nexus splash screen should be OK
When ADB works but FastBoot does not…
I faced a very embarassing situation: trying to root my Nexus S, I had to unlock the device. My Android SDK was succesfully installed, the drivers too. The device was succesfully recognized by ADB… But fastboot devices failed to detect the device. From this point, it was impossible to unlock the device by launching fastboot oem unlock. I tried many basic solutions, but none worked.
At last, I found this post:
http://forum.xda-developers.com/showthread.php?t=875580
When ADB works but not FastBoot, the solution is to… install PdaNet. Amazing ; but efficient.
Many thanks to BigRick10 from XDA forums!
How to emulate Android GingerBread on your PC?
This post describes how to install and play with a emulator of GingerBread (Android 2.3) device on your desktop (or laptop) computer:
- go to this page, download Android SDK related to your system.
- unzip / install it, let’s say in
$android-sdk-home - launch Android SDK Manager (with
$android-sdk-home\SDK Manager.exeunder Windows,$android-sdk-home/androidon other systems) - on the left panel, select
Available Packages, and selectAndroid Repositorypackages you would like to install, and possibly other third party add-ons. - go to Virtual Devices >
- New >
- give a name, for instance “GingerBread” >
- Target “Android 2.3.3…” >
- SD Car Size: 2MiB >
- leave other options >
- Create AVD
- wait a little…
- still in Virtual Devices panel, select the AVD you have just created (called hereGingerBread) > Start
- wait… a lot
- enjoy!
EDIT: I could not resist and I have installed HoneyComb, too 😉