Add a number to the icon in Android-used for reminders of the number of unread text messages and reminders of the number of applications to be updated

Source: Internet
Author: User
Tags add numbers home screen

 

When developing applications such as short messages and app stores, we will consider adding the number of unread text messages to the icon of the short message, and adding the number of apps that can be upgraded to the app store, in this way, the goal of prompting can be achieved without occupying too much space.

 

This section uses an example of showing the number of contacts in a mobile phone to show how to add a number to an icon, that is, a number overlay .. I have done google map development and know about overlay ..

I. You can learn

 

View contacts based on Uris on your phone

Add Permissions

Retrieve the app icons of any app on your phone

Image processing, such as copying, adds a layer-number to the image.

Use RemoteView to customize Notification

Ii. Start action

 

Create an Android Project named icationicationiconcount. Project with final version included in the attachment

First, modify AndroidManifest. xml and add the permission <uses-permission android: name = "android. permission. READ_CONTACTS"> </uses-permission> because we want to read the contact.

Modify main. xml as follows. Here we define an ImageView. We have the courage to preview the processed icon with numbers.

View plain

<? Xml version = "1.0" encoding = "UTF-8"?>

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"

Android: orientation = "vertical"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

>

<ImageView

Android: id = "@ + id/icon"

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: scaleType = "center"

Android: adjustViewBounds = "true"/>

</LinearLayout>

 

 

First, retrieve the icon of the address book on your phone. If no icon is obtained, use the icon of the application.

View plain

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

MImageView = (ImageView) findViewById (R. id. icon );

// Use the contact icon first. If the contact icon does not exist, use the application icon.

Drawable contactIcon;

Try {

ContactIcon = getPackageManager (). getApplicationIcon ("com. android. contacts ");

} Catch (NameNotFoundException e ){

ContactIcon = null;

}

Bitmap icon;

If (contactIcon instanceof BitmapDrawable ){

Icon = (BitmapDrawable) contactIcon). getBitmap ();

} Else {

Icon = getResIcon (getResources (), R. id. icon );

}

 

View plain

/**

* Obtain an image by id

* @ Param res

* @ Param resId

* @ Return

*/

Private Bitmap getResIcon (Resources res, int resId ){

Drawable icon = res. getDrawable (resId );

If (icon instanceof BitmapDrawable ){

BitmapDrawable bd = (BitmapDrawable) icon;

Return bd. getBitmap ();

} Else {

Return null;

}

}

 

 

Here we use a custom function to retrieve images based on the resource icon id. The Code is as follows:

View plain

/**

* Obtain the number of contacts.

* @ Return refers to the number of contacts in the address book.

*/

Private int getContactCount (){

Cursor c = getContentResolver (). query (ContactsContract. Contacts. CONTENT_URI, new String [] {ContactsContract. Contacts. _ COUNT}, null );

Try {

C. moveToFirst ();

Return c. getInt (0 );

} Catch (Exception e ){

Return 0;

} Finally {

C. close ();

}

}

 

 

After obtaining the icon, you need to process it. to overwrite the number of contacts for the icon, first let's look at the function for getting the number of contacts.

Java code

/**

* Obtain the number of contacts.

* @ Return refers to the number of contacts in the address book.

*/

Private int getContactCount (){

Cursor c = getContentResolver (). query (ContactsContract. Contacts. CONTENT_URI, new String [] {ContactsContract. Contacts. _ COUNT}, null );

Try {

C. moveToFirst ();

Return c. getInt (0 );

} Catch (Exception e ){

Return 0;

} Finally {

C. close ();

}

}

Here we use the Uri method to obtain the contact's cursor and then obtain the number.

With the icon and contact number, you can generate an icon with the number of contacts. Let's look at the generated function.

View plain

/**

* Add the number of contacts in the upper-right corner of the specified image. The quantity is marked in red.

* @ Param icon specifies the image

* @ Return refers to an image with the number of contacts

*/

Private Bitmap generatorContactCountIcon (Bitmap icon ){

// Initialize the canvas

Int iconSize = (int) getResources (). getDimension (android. R. dimen. app_icon_size );

Log. d (TAG, "the icon size is" + iconSize );

Bitmap contactIcon = Bitmap. createBitmap (iconSize, iconSize, Config. ARGB_8888 );

Canvas canvas = new Canvas (contactIcon );

// Copy the image

Paint iconPaint = new Paint ();

IconPaint. setDither (true); // anti-Jitter

IconPaint. setFilterBitmap (true); // It is used to filter Bitmap. In this way, when you select Drawable, it will have anti-aliasing effect.

Rect src = new Rect (0, 0, icon. getWidth (), icon. getHeight ());

Rect dst = new Rect (0, 0, iconSize, iconSize );

Canvas. drawBitmap (icon, src, dst, iconPaint );

// Create an overwrite number of contacts on the Image

Int contacyCount = getContactCount ();

// Enable anti-aliasing and use the text field of the device

Paint countPaint = new Paint (Paint. ANTI_ALIAS_FLAG | Paint. DEV_KERN_TEXT_FLAG );

CountPaint. setColor (Color. RED );

CountPaint. setTextSize (20f );

CountPaint. setTypeface (Typeface. DEFAULT_BOLD );

Canvas. drawText (String. valueOf (contacyCount), iconSize-18, 25, countPaint );

Return contactIcon;

}

 

 

The comments are very detailed and will not be explained. It is nothing more than defining a Canvas, and then drawing icons and numbers on it.

Then we put the processed Bitmap in the ImageView defined in main. xml to see the effect.

View plain

MImageView. setImageBitmap (contactCountIcon );

 

 

 

Let's start the application to see the effect.

 

We can see that red 1 in the upper right corner indicates that there is a contact in my mobile phone.

3. Use status bar notification to display the number of contacts

 

If we listen to the number of unread text messages and display the notifications in the status bar, we can use this method. Here we take the number of contacts as an example.

Because the default icon field of Notification uses the int type of a resource, we use RemoteView to customize Notification. To define RemoteView, a layout is required to define the display Notification style. We create a new notification. xml layout file as follows:

View plain

<? Xml version = "1.0" encoding = "UTF-8"?>

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"

Android: orientation = "horizontal"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

Android: padding = "3dp"

>

<ImageView android: id = "@ + id/image"

Android: layout_width = "wrap_content"

Android: layout_height = "fill_parent"

Android: layout_marginRight = "10dp"

/>

<TextView android: id = "@ + id/text"

Android: layout_width = "wrap_content"

Android: layout_height = "fill_parent"

Android: textColor = "#000"

/>

</LinearLayout>

 

 

An ImageView and a TextView are used to display the icons and text of the prompt.

To use Notification, we must obtain a Service-NotificationManager, which is used in Android to manage our Notification. The code for obtaining NotificationManager is as follows: uninstall the onCreate method.

View plain

Nm = (icationicationmanager) getSystemService (Context. NOTIFICATION_SERVICE );

 

 

Then we will call the method we have defined to display the notification:

View plain

<Pre name = "code" class = "java"> showNotifacation (contactCountIcon );

 

 

 

Next, let's take a look at the specific implementation of the showNotifacation method:

View plain

/**

* Display status bar notifications

* @ Param icon: Notification content icon

*/

Private void showNotifacation (Bitmap icon ){

Notification notification = new Notification (R. drawable. icon, "number of contacts", System. currentTimeMillis ());

// Use RemoteView to customize the Notification View

RemoteViews contentView = new RemoteViews (getPackageName (), R. layout. notification );

ContentView. setImageViewBitmap (R. id. image, icon );

ContentView. setTextViewText (R. id. text, "the red number on the icon indicates the number of contacts in the mobile phone ");

Notification. contentView = contentView;

Intent notificationIntent = new Intent (this, NotificationIconActivity. class );

PendingIntent contentIntent = PendingIntent. getActivity (this, 0, icationicationintent, 0 );

Notification. contentIntent = contentIntent;

Nm. Y (icationication_contact_id, notification );

}

 

 

The comments are very detailed, so I will not explain them one by one.

The last step is to rewrite onDestroy and clear our notifications when Android destroys the Activity.

View plain

@ Override

Protected void onDestroy (){

Super. onDestroy ();

Nm. cancel (icationication_contact_id );

}

 

 

 

Run, you can see the following results

 

 

As you can see, the effect has come out ..

 

Iv. Summary and some extensions

 

The main key to this knot is processing the image. For example, if you add a number here, you can add other things. There are many corresponding functions in the Canvas ..

 

Here we are talking about some methods for displaying and processing images in applications and status notifications. Is there a way to process the icons on the mobile phone's home screen and add numbers to them. For example, if you add the number of unread text messages to the upper right corner of the text message application icon, the answer is yes, but it is a roundabout implementation. The idea is to use AppWidget, which can be implemented and dynamically updated, you can find out how to implement it. Here we only provide an idea, which is similar to the example in this section, but we need to make it an AppWidget...

 

Source code http://www.bkjia.com/uploadfile/2011/1107/20111107092215943.rar

 

Author michael _ li

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.