加载中...

16 August 2012

Creating Your Own Spelling Checker Service

Posted by Satoshi Kataoka and Ken Wakasa of the Android text input engineering team

The Spelling Checker framework improves the text-input experience on Android by helping the user quickly identify and correct spelling errors. When an app uses the spelling checker framework, the user can see a red underline beneath misspelled or unrecognized words so that the user can correct mistakes instantly by choosing a suggestion from a dropdown list.

If you are an input method editor (IME) developer, the Spelling Checker framework gives you a great way to provide an even better experience for your users. You can add your own spelling checker service to your IME to provide consistent spelling error corrections from your own custom dictionary. Your spelling checker can recognize and suggest corrections for the vocabularies that are most important to your users, and if your language is not supported by the built-in spelling checker, you can provide a spelling checker for that language.

The Spelling Checker APIs let you create your own spelling checker service with minimal steps. The framework manages the interaction between your spelling checker service and a text input field. In this post we’ll give you an overview of how to implement a spelling checker service. For details, take a look at the Spelling Checker Framework API Guide.

1. Create a spelling checker service class


To create a spelling checker service, the first step is to create a spelling checker service class that extends android.service.textservice.SpellCheckerService.

For a working example of a spelling checker, you may want to take a look at the SampleSpellCheckerService class in the SpellChecker sample app, available from the Samples download package in the Android SDK.

2. Implement the required methods


Next, in your subclass of SpellCheckerService, implement the methods createSession() and onGetSuggestions(), as shown in the following code snippet:
@Override                                                                        
public Session createSession() {                                             
    return new AndroidSpellCheckerSession();                                 
}       

private static class AndroidSpellCheckerSession extends Session {            
    @Override                                                                
    public SuggestionsInfo onGetSuggestions(TextInfo textInfo, int suggestionsLimit) {
        SuggestionsInfo suggestionsInfo;
        ... // look up suggestions for TextInfo
        return suggestionsInfo;
    }      
}

Note that the input argument textInfo of onGetSuggestions(TextInfo, int) contains a single word. The method returns suggestions for that word as a SuggestionsInfo object. The implementation of this method can access your custom dictionary and any utility classes for extracting and ranking suggestions.

For sentence-level checking, you can also implement onGetSuggestionsMultiple(), which accepts an array of TextInfo.

3. Register the spelling checker service in AndroidManifest.xml


In addition to implementing your subclass, you need to declare the spelling checker service in your manifest file. The declaration specifies the application, the service, and a metadata file that defines the Activity to use for controlling settings. Here’s an example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.samplespellcheckerservice">
    <application android:label="@string/app_name">
        <service 
            android:label="@string/app_name"    
            android:name=".SampleSpellCheckerService" 
            android:permission="android.permission.BIND_TEXT_SERVICE">
            <intent-filter>
                <action 
                    android:name="android.service.textservice.SpellCheckerService" />
            </intent-filter>
            <meta-data
                android:name="android.view.textservice.scs"
                android:resource="@xml/spellchecker" />
        </service>
    </application>
</manifest>

Notice that the service must request the permission android.permission.BIND_TEXT_SERVICE to ensure that only the system binds to the service.

4. Create a metadata XML resource file


Last, create a metadata file for your spelling checker to define the Activity to use for controlling spelling checker settings. The metadata file can also define subtypes for the spelling checker. Place the file in the location specified in the
element of the spelling checker declaration in the manifest file.

In the example below, the metadata file spellchecker.xml specifies the settings Activity as SpellCheckerSettingsActivity and includes subtypes to define the locales that the spelling checker can handle.
<spell-checker xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/spellchecker_name"
    android:settingsactivity="com.example.SpellCheckerSettingsActivity" />
    <subtype   
        android:label="@string/subtype_generic" 
        android:subtypeLocale="en" />
</spell-checker>

That’s it! Your spelling checker service is now available to client applications such as your IME.

Bonus points: Add batch processing of multiple sentences


For faster, more accurate spell-checking, Android 4.1 (Jelly Bean) introduces APIs that let clients pass multiple sentences to your spelling checker at once.

To support sentence-level checking for multiple sentences in a single call, just override and implement the method onGetSentenceSuggestionsMultiple(), as shown below.
private static class AndroidSpellCheckerSession extends Session {                 
    @Override                                                                
    public SentenceSuggestionsInfo[] onGetSentenceSuggestionsMultiple(
          TextInfo[] textInfo, int suggestionsLimit) {
        SentenceSuggestionsInfo[] sentenceSuggestionsInfos;
        ... // look up suggestions for each TextInfo
        return sentenceSuggestionsInfos
    }      
}

In this case, textInfo is an array of TextInfo, each of which holds a sentence. The method returns lengths and offsets of suggestions for each sentence as a SentenceSuggestionsInfo object.

Documents and samples


If you’d like to learn more about how to use the spelling checker APIs, take a look at these documents and samples:
  • Spelling Checker Framework API Guide — a developer guide covering the Spelling Checker API for clients and services.
  • SampleSpellCheckerService sample app — helps you get started with your spelling checker service.
    • You can find the app at /samples/android-15/SpellChecker/SampleSpellCheckerService in the Samples download.
  • HelloSpellChecker sample app — a basic app that uses a spelling checker.
    • You can find the app at /samples/android-15/SpellChecker/HelloSpellChecker in the Samples download.
To learn how to download sample apps for the Android SDK, see Samples.

Join the discussion on
+Android Developers

18 July 2012

Getting Your App Ready for Jelly Bean and Nexus 7

[This post is by Nick Butcher, an Android engineer who notices small imperfections, and they annoy him.]

We are pleased to announce that the full SDK for Android 4.1 is now available to developers and can be downloaded through your SDK Manager. You can now develop and publish applications against API level 16 using new Jelly Bean APIs. We are also releasing SDK Tools revision 20.0.1 and NDK revision 8b containing bug fixes only.

For many people, their first taste of Jelly Bean will be on the beautiful Nexus 7. While most applications will run just fine on Nexus 7, who wants their app to be just fine? Here are some tips for optimizing your application to make the most of this device.

Screen

Giving Nexus 7 its name, is the glorious 7” screen. As developers we see this as around 600 * 960 density independent pixels and a density of tvdpi. As Dianne Hackborn has elaborated, this density might be a surprise to you but don’t panic! We actively discourage you from rushing out and creating new assets at this density; Android will scale your existing assets for you. In fact the entire Jelly Bean OS contains only a single tvdpi asset, the remainder are scaled down from hdpi assets.

To be sure the system can successfully scale your hdpi assets for tvdpi, take special care that your 9-patch images are created correctly so that they can be scaled down effectively:
  • Make sure that any stretchable regions are at least 2x2 pixels in size, else they risk disappearing when scaled down.
  • Give one pixel of extra safe space in the graphics before and after stretchable regions else interpolation during scaling may cause the color at the boundaries to change.

The 7” form factor gives you more space to present your content. You can use the sw600dp resource qualifier to provide alternative layouts for this size screen. For example your application may contain a layout for your launch activity:

res/layout/activity_home.xml
To take advantage of the extra space on the 7” screen you might provide an alternative layout:
res/layout-sw600dp/activity_home.xml
The sw600dp qualifier declares that these resources are for devices that have a screen with at least 600dp available on its smallest side.

Furthermore you might even provide a different layout for 10” tablets:
res/layout-sw720dp/activity_home.xml
This technique allows a single application to use defined switching points to respond to a device’s configuration and present an optimized layout of your content.

Similarly if you find that your phone layout works well on a 7” screen but requires slightly larger font or image sizes then you can use a single layout but specify alternative sizes in dimensions files. For example res/values/dimens.xml may contain a font size dimension:
<dimen name="text_size">18sp</dimen>
but you can specify an alternative text size for 7” tablets in res/values-sw600dp/dimens.xml:
<dimen name="text_size">32sp</dimen>
Hardware

Nexus 7 has different hardware features from most phones:
  • No telephony
  • A single front facing camera (apps requiring the android.hardware.camera feature will not be available on Nexus 7)

Be aware of which system features that you declare (or imply) are required to run your application or the Play Store will not make your application available to Nexus 7 users. Always declare hardware features that aren't critical to your app as required="false" then detect at runtime if the feature is present and progressively enhance functionality. For example if your app can use the camera but it isn’t essential to its operation, you would declare it with:

<uses-feature android:name="android.hardware.camera" 
              android:required="false"/>

For more details follow Reto Meier’s Five Steps to Hardware Happiness.

Conclusion

Nexus 7 ships with Jelly Bean and its updated suite of system apps are built to take advantage of new Jelly Bean APIs. These apps are the standard against which your application will be judged — make sure that you’re keeping up!

If your application shows notifications then consider utilizing the new richer notification styles. If you are displaying immersive content then control the appearance of the system UI. If you are still using the options menu then move to the Action Bar pattern.

A lot of work has gone into making Jelly Bean buttery smooth; make sure your app is as well. If you haven’t yet opted in to hardware accelerated rendering then now is the time to implement and test this.

For more information on Android 4.1 visit the Android Developers site or join us Live.

Join the discussion on +Android Developers

10 July 2012

Google I/O and Beyond

[This post is by Reto Meier, Android Developer Relations Tech Lead]

With most of the Android Developer Relations team now fully recovered from Google I/O 2012, I'm happy to announce that all of the videos for the Google I/O 2012 Android Sessions are now available!

I've included in the Google I/O 12 - The Android Sessions playlist (embedded below), as well as (in keeping with our newly redesigned developer site) in playlists for each developer category: Design, develop, and distribute.



Google I/O is always a highlight on the Android Developer Relations team's calendar; it's our best opportunity to talk directly to the Android developer community. Unfortunately I/O only happens once a year, and only a lucky few thousand can join us in person.

That's why we've been exploring more scalable approaches to interacting with developers, and with the launch of Google Developers Live, we have a way for the entire Android Developer community to view and participate in live, interactive developer-focused broadcasts all year round, and all across the world.

This week we resume our weekly interactive development Q&A Office Hours in three time zones (US, EMEA, and APAC).  We know many of you have questions related to specific I/O sessions, so we've invited all the speakers to join us, starting with this Wednesday's Android Developer Office Hours with Chet Haase, Romain Guy, Xavier Ducrohet, and Tor Norbye from the What's New in Jelly Bean and What's new in Android Developer Tools sessions.

On Friday afternoons we broadcast The Friday Review of Apps and The Friday Review of Games, two more relaxed sessions where we review self-nominated apps and games, providing feedback to the developers in the hope of discovering some feature-worthy gems.

Every Android Developer Live broadcast is recorded and available from Google Developers Live, the Android Developers YouTube channel, and directly from developer.android.com. We've also begun to make each of the Office Hours, as well as the Android sessions from Google I/O 2012, available as part of the Android Developers Live audio podcast.

We're really excited to use Google Developers Live to interact more regularly with you, the most important members of the Android ecosystem, and will be looking to expand our lineup to include regular interviews with app developers and Android engineers.

Got great ideas for how we can expand our live program? Let us know on Google+.

28 June 2012

Android SDK Tools, Revision 20

[This post is by Xavier Ducrohet, Tech Lead for the Android developer tools]

Along with the preview of the Android 4.1 (Jelly Bean) platform, we launched Android SDK Tools R20 and ADT 20.0.0. Here are a few things that we would like to highlight.
    Application templates: Android ADT supports a new application templates for creating new application, blank activity, master-detail flow, and custom view. These templates support the Android style guide thus making it faster and easier to build beautiful apps. More templates will be added over time.

    Tracer for GLES: With this new tool you can capture the entire sequence of OpenGL calls made by an app into a trace file on the host and replay the captured trace and display the GL state at any point in time.
    Device Monitor: To help you to easily debug your apps, all the Android debugging tools like DDMS, traceview, hierarchyviewer and Tracer for GLES are now built into one single application.
    Systrace: Improving app performance does not have to be a guesswork any more. Systrace for Jelly Bean and above lets you easily optimize your app. You can capture a slice of system activity plus additional information tagged from the Settings > Developer Options > Monitoring: Enable traces or with specific calls added to your application code.

To learn more on the layout editor, XML editing, build system & SDK Manager improvements, please read the ADT 20.0.0 and SDK Tools R20 release notes.

Join us today, June 28th, at the “What’s new in Android developer tools” session for some fun tool demos and a sneak-peak into what’s coming next.

27 June 2012

Introducing Android 4.1 (Jelly Bean) preview platform, and more

[This post is by Angana Ghosh, Product Manager on the Android team]


At Google I/O today we announced the latest version of the Android platform, Android 4.1 (Jelly Bean). With Jelly Bean, we’ve made the great things about Android even better with improved system performance and enhanced user features.

Improvements include a smoother and more responsive UI across the system, a home screen that automatically adapts to fit your content, a powerful predictive keyboard, richer and more interactive notifications, larger payload sizes for Android Beam sharing and much more. For a lowdown on what’s new, head over to the Jelly Bean platform highlights.

Of course, Jelly Bean wouldn’t be complete without a healthy serving of new APIs for app developers. Here are some of the new APIs that Jelly Bean introduces:
    Expandable notifications: Android 4.1 brings a major update to the Android notifications framework. Apps can now display larger, richer notifications to users that can be expanded and collapsed with a pinch. Users can now take actions directly from the notification shade, and notifications support new types of content, including photos.
    Android Beam: In Android 4.1, Android Beam makes it easier to share images, videos, or other payloads by leveraging Bluetooth for the data transfer.
    Bi-directional text support: Android 4.1 helps you to reach more users through support for for bi-directional text in TextView and EditText elements.
    Gesture mode: New APIs for accessibility services let you handle gestures and manage accessibility focus. Now you can traverse any element on the screen using gestures, accessories, you name it.
    Media codec access: Provides low-level access to platform hardware and software codecs.
    Wi-Fi Direct service discoverability: New API provides pre-associated service discovery letting apps get more information from nearby devices about the services they support, before they attempt to connect.
    Network bandwidth management: New API provides ability to detect metered networks, including tethering to a mobile hotspot.
For a complete overview of new APIs in Jelly Bean, please read the API highlights document. Note that this is a preview of the Jelly Bean platform. While we’re still finalizing the API implementations we wanted to give developers a look at the new API to begin planning app updates. We’ll be releasing a final platform in a few weeks that you should use to build and publish applications for Android 4.1.

For Android devices with the Google Play, we launched the following at Google I/O today:
    Smart app updates: For Android 2.3, Gingerbread devices and up, when there is a new version of an app in Google Play, only the parts of the app that changed are downloaded to users’ devices. On average, a smart app update is a third the size of a full apk update. This means your users save bandwidth and battery and the best part? You don’t have to do a thing. This is automatically enabled for all apps downloaded from Google Play.
    App encryption: From Jelly Bean and forward, paid apps in Google Play are encrypted with a device-specific key before they are delivered and stored on the device. We know you work hard building your apps. We work hard to protect your investment.
    Google Cloud Messaging for Android: This is the next version of C2DM and goes back to Froyo. Getting started is easy and has a whole bunch of new APIs than C2DM has to offer. If you sign-up for GCM, you will be able to see C2DM and GCM stats in the Android developer console. Most importantly, the service is free and there are no quotas. [Learn more.]
Starting from today, over 20 Android sessions at Google I/O will deep-dive in many of these areas. Join us in-person or follow us live.

21 June 2012

Replying to User Reviews on Google Play

[This post is by Trevor Johns from the Android team — Tim Bray]

User reviews on Google Play are great for helping people discover quality apps and give feedback to developers and other potential app users. But what about when developers want to give feedback to their users? Sometimes a user just needs a helping hand, or perhaps a new feature has been added and the developer wants to share the good news.

That’s why we’re adding the ability for Google Play developers to respond to reviews from the Google Play Android Developer Console. Developers can gather additional information, provide guidance, and — perhaps most importantly — let users know when their feature requests have been implemented.

We’ll also notify the user who wrote the review via email that the developer has responded. Users can then contact the developer directly if additional followup is needed or update their review.

We’re releasing this feature today to those with a Top Developer badge (). And based on feedback from users and developers, we will offer it to additional Google Play developers in the future.

Conversations are meant to be two-sided, and facilitating discussion between developers and users will ultimately yield better apps, to the benefit of everyone.

Helping you build beautiful, powerful, successful apps

[This post is by Billy Rutledge, Director of Developer Relations for Android. — Tim Bray]

Just in time for Google I/O next week, the Android Developers site is stepping into a new look that is streamlined, simplified, and refocused. A developer’s tasks fall into three baskets: Designing, developing, and distributing. We're trying to make developer.android.com's organization reflect this reality, shepherding you through the app development life cycle, from start to finish.

Design

Earlier this year, we launched Android Design, an online style guide which lays out the principles, building blocks, and patterns for excellence in Android user interfaces. It seems to be working; every day, we see more and more beautiful apps arriving in Google Play. At I/O, we’ll continue to talk design, kicking off with Android Design for Success, led by Matias Duarte.

Develop

An Android app should be fast, powerful and useful. With Android Training, one of the many parts of the Develop section that we continue to build out, we lay out best practices in a variety of framework topics to help you achieve those goals. If you’re at I/O and you’re interested in Android tools, be sure to start off your show with What’s new in Android Developers’ Tools.

Distribute

The most important piece of the piece of the puzzle is about getting your app in front of millions and millions of Android users on Google Play. That’s why we added a section on distributing your app — a peek into the world of publishing and promoting your app. Chris Yerga on the Play team will be kicking off our how-to sessions on distributing your with Android apps in Google Play.

This is just a small sample of the Android sessions at Google I/O, many of which will be live-streamed so you can follow along even if you can’t make it out to San Francisco. In the meantime, we hope you find the new Android Developer site much more useful as you build great apps.


Join the discussion on
+Android Developers