您的位置:首页 > 移动开发 > Android开发

Android设计和开发系列第一篇:Notifications通知(Develop—Training)

2015-02-27 16:01 519 查看

Develop篇

BuildingaNotification

PREVIOUSNEXT

THISLESSONTEACHESYOUTO

CreateaNotificationBuilder

DefinetheNotification'sAction

SettheNotification'sClickBehavior

IssuetheNotification

YOUSHOULDALSOREAD

NotificationsAPIGuide

IntentsandIntentFilters

NotificationsDesignGuide

Thislessonexplainshowtocreateandissueanotification.

Theexamplesinthisclassarebasedonthe
NotificationCompat.Builder
class.
NotificationCompat.Builder
isintheSupportLibrary.Youshoulduse
NotificationCompat
anditssubclasses,particularly
NotificationCompat.Builder
,toprovidethebestnotificationsupportforawiderangeofplatforms.

CreateaNotificationBuilder

Whencreatinganotification,specifytheUIcontentandactionswitha
NotificationCompat.Builder
object.Atbareminimum,a
Builder
objectmustincludethefollowing:

Asmallicon,setby
setSmallIcon()


Atitle,setby
setContentTitle()


Detailtext,setby
setContentText()


Forexample:

NotificationCompat.BuildermBuilder=
newNotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Mynotification")
.setContentText("HelloWorld!");

DefinetheNotification'sAction

Althoughactionsareoptional,youshouldaddatleastoneactiontoyournotification.Anactiontakesusersdirectlyfromthenotificationtoan
Activity
inyourapplication,wheretheycanlookattheeventthatcausedthenotificationordofurtherwork.Insideanotification,theactionitselfisdefinedbya
PendingIntent
containingan
Intent
thatstartsan
Activity
inyourapplication.

Howyouconstructthe
PendingIntent
dependsonwhattypeof
Activity
you'restarting.Whenyoustartan
Activity
fromanotification,youmustpreservetheuser'sexpectednavigationexperience.Inthesnippetbelow,clickingthenotificationopensanewactivitythateffectivelyextendsthebehaviorofthenotification.Inthiscasethereisnoneedtocreateanartificialbackstack(seePreservingNavigationwhenStartinganActivityformoreinformation):

IntentresultIntent=newIntent(this,ResultActivity.class);
...
//Becauseclickingthenotificationopensanew("special")activity,there's
//noneedtocreateanartificialbackstack.
PendingIntentresultPendingIntent=
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);

SettheNotification'sClickBehavior

Toassociatethe
PendingIntent
createdinthepreviousstepwithagesture,calltheappropriatemethodof
NotificationCompat.Builder
.Forexample,tostartanactivitywhentheuserclicksthenotificationtextinthenotificationdrawer,addthe
PendingIntent
bycalling
setContentIntent()
.Forexample:

PendingIntentresultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);

IssuetheNotification

Toissuethenotification:

Getaninstanceof
NotificationManager
.

Usethe
notify()
methodtoissuethenotification.Whenyoucall
notify()
,specifyanotificationID.YoucanusethisIDtoupdatethenotificationlateron.ThisisdescribedinmoredetailinManagingNotifications.

Call
build()
,whichreturnsa
Notification
objectcontainingyourspecifications.

Forexample:

NotificationCompat.BuildermBuilder;
...
//SetsanIDforthenotification
intmNotificationId=001;
//GetsaninstanceoftheNotificationManagerservice
NotificationManagermNotifyMgr=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//Buildsthenotificationandissuesit.
mNotifyMgr.notify(mNotificationId,mBuilder.build());


PreservingNavigationwhenStartinganActivity

PREVIOUSNEXT

THISLESSONTEACHESYOUTO

SetuparegularactivityPendingIntent

SetupaspecialactivityPendingIntent

YOUSHOULDALSOREAD

NotificationsAPIGuide

IntentsandIntentFilters

NotificationsDesignGuide

Partofdesigninganotificationispreservingtheuser'sexpectednavigationexperience.Foradetaileddiscussionofthistopic,seetheNotificationsAPIguide.Therearetwogeneralsituations:

RegularactivityYou'restartingan
Activity
that'spartoftheapplication'snormalworkflow.SpecialactivityTheuseronlyseesthis
Activity
ifit'sstartedfromanotification.Inasense,the
Activity
extendsthenotificationbyprovidinginformationthatwouldbehardtodisplayinthenotificationitself.

SetUpaRegularActivityPendingIntent

Tosetupa
PendingIntent
thatstartsadirectentry
Activity
,followthesesteps:

Defineyourapplication's
Activity
hierarchyinthemanifest.ThefinalXMLshouldlooklikethis:

<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".ResultActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>


Createabackstackbasedonthe
Intent
thatstartsthe
Activity
.Forexample:

intid=1;
...
IntentresultIntent=newIntent(this,ResultActivity.class);
TaskStackBuilderstackBuilder=TaskStackBuilder.create(this);
//Addsthebackstack
stackBuilder.addParentStack(ResultActivity.class);
//AddstheIntenttothetopofthestack
stackBuilder.addNextIntent(resultIntent);
//GetsaPendingIntentcontainingtheentirebackstack
PendingIntentresultPendingIntent=
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
...
NotificationCompat.Builderbuilder=newNotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManagermNotificationManager=
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id,builder.build());

SetUpaSpecialActivityPendingIntent

Aspecial
Activity
doesn'tneedabackstack,soyoudon'thavetodefineits
Activity
hierarchyinthemanifest,andyoudon'thavetocall
addParentStack()
tobuildabackstack.Instead,usethemanifesttosetupthe
Activity
taskoptions,andcreatethe
PendingIntent
bycalling
getActivity()
:

Inyourmanifest,addthefollowingattributestothe
<activity>
elementforthe
Activity
:
android:name="activityclass"
Theactivity'sfully-qualifiedclassname.
android:taskAffinity=""
Combinedwiththe
FLAG_ACTIVITY_NEW_TASK
flagthatyousetincode,thisensuresthatthis
Activity
doesn'tgointotheapplication'sdefaulttask.Anyexistingtasksthathavetheapplication'sdefaultaffinityarenotaffected.
android:excludeFromRecents="true"
ExcludesthenewtaskfromRecents,sothattheusercan'taccidentallynavigatebacktoit.
Thissnippetshowstheelement:

<activity
android:name=".ResultActivity"
...
android:launchMode="singleTask"
android:taskAffinity=""
android:excludeFromRecents="true">
</activity>
...


Buildandissuethenotification:
Createan
Intent
thatstartsthe
Activity
.

Setthe
Activity
tostartinanew,emptytaskbycalling
setFlags()
withtheflags
FLAG_ACTIVITY_NEW_TASK
and
FLAG_ACTIVITY_CLEAR_TASK
.

Setanyotheroptionsyouneedforthe
Intent
.

Createa
PendingIntent
fromthe
Intent
bycalling
getActivity()
.Youcanthenusethis
PendingIntent
astheargumentto
setContentIntent()
.

Thefollowingcodesnippetdemonstratestheprocess:

//InstantiateaBuilderobject.
NotificationCompat.Builderbuilder=newNotificationCompat.Builder(this);
//CreatesanIntentfortheActivity
IntentnotifyIntent=
newIntent(newComponentName(this,ResultActivity.class));
//SetstheActivitytostartinanew,emptytask
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
//CreatesthePendingIntent
PendingIntentnotifyIntent=
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);

//PutsthePendingIntentintothenotificationbuilder
builder.setContentIntent(notifyIntent);
//Notificationsareissuedbysendingthemtothe
//NotificationManagersystemservice.
NotificationManagermNotificationManager=
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//BuildsananonymousNotificationobjectfromthebuilder,and
//passesittotheNotificationManager
mNotificationManager.notify(id,builder.build());


UpdatingNotifications

PREVIOUSNEXT

THISLESSONTEACHESYOUTO

ModifyaNotification

RemoveNotifications

YOUSHOULDALSOREAD

NotificationsAPIGuide

IntentsandIntentFilters

NotificationsDesignGuide

Whenyouneedtoissueanotificationmultipletimesforthesametypeofevent,youshouldavoidmakingacompletelynewnotification.Instead,youshouldconsiderupdatingapreviousnotification,eitherbychangingsomeofitsvaluesorbyaddingtoit,orboth.

Thefollowingsectiondescribeshowtoupdatenotificationsandalsohowtoremovethem.

ModifyaNotification

Tosetupanotificationsoitcanbeupdated,issueitwithanotificationIDbycalling
NotificationManager.notify(ID,notification)
.Toupdatethisnotificationonceyou'veissuedit,updateorcreatea
NotificationCompat.Builder
object,builda
Notification
objectfromit,andissuethe
Notification
withthesameIDyouusedpreviously.

Thefollowingsnippetdemonstratesanotificationthatisupdatedtoreflectthenumberofeventsthathaveoccurred.Itstacksthenotification,showingasummary:

mNotificationManager=
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//SetsanIDforthenotification,soitcanbeupdated
intnotifyID=1;
mNotifyBuilder=newNotificationCompat.Builder(this)
.setContentTitle("NewMessage")
.setContentText("You'vereceivednewmessages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages=0;
//Startofaloopthatprocessesdataandthennotifiestheuser
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
//BecausetheIDremainsunchanged,theexistingnotificationis
//updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...

RemoveNotifications

Notificationsremainvisibleuntiloneofthefollowinghappens:

Theuserdismissesthenotificationeitherindividuallyorbyusing"ClearAll"(ifthenotificationcanbecleared).

Theusertouchesthenotification,andyoucalled
setAutoCancel()
whenyoucreatedthenotification.

Youcall
cancel()
foraspecificnotificationID.Thismethodalsodeletesongoingnotifications.

Youcall
cancelAll()
,whichremovesallofthenotificationsyoupreviouslyissued.

UsingBigViewStyles

PREVIOUSNEXT

THISLESSONTEACHESYOUTO

SetUptheNotificationtoLaunchaNewActivity

ConstructtheBigView

YOUSHOULDALSOREAD

NotificationsAPIGuide

IntentsandIntentFilters

NotificationsDesignGuide

Notificationsinthenotificationdrawerappearintwomainvisualstyles,normalviewandbigview.Thebigviewofanotificationonlyappearswhenthenotificationisexpanded.Thishappenswhenthenotificationisatthetopofthedrawer,ortheuserclicksthenotification.

BigviewswereintroducedinAndroid4.1,andthey'renotsupportedonolderdevices.Thislessondescribeshowtoincorporatebigviewnotificationsintoyourappwhilestillprovidingfullfunctionalityviathenormalview.SeetheNotificationsAPIguideformorediscussionofbigviews.

Hereisanexampleofanormalview:



Figure1.Normalviewnotification.

Hereisanexampleofabigview:



Figure2.Bigviewnotification.

Inthesampleapplicationshowninthislesson,boththenormalviewandthebigviewgiveusersaccesstosamefunctionality:

Theabilitytosnoozeordismissthenotification.

Awaytoviewtheremindertexttheusersetaspartofthetimer.

Thenormalviewprovidesthesefeaturesthroughanewactivitythatlauncheswhentheuserclicksthenotification.Keepthisinmindasyoudesignyournotifications—firstprovidethefunctionalityinthenormalview,sincethisishowmanyuserswillinteractwiththenotification.

SetUptheNotificationtoLaunchaNewActivity

Thesampleapplicationusesan
IntentService
subclass(
PingService
)toconstructandissuethenotification.

Inthissnippet,the
IntentService
method
onHandleIntent()
specifiesthenewactivitythatwillbelaunchediftheuserclicksthenotificationitself.Themethod
setContentIntent()
definesapendingintentthatshouldbefiredwhentheuserclicksthenotification,therebylaunchingtheactivity.

IntentresultIntent=newIntent(this,ResultActivity.class);
resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE,msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);

//Becauseclickingthenotificationlaunchesanew("special")activity,
//there'snoneedtocreateanartificialbackstack.
PendingIntentresultPendingIntent=
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);

//Thissetsthependingintentthatshouldbefiredwhentheuserclicksthe
//notification.Clickingthenotificationlaunchesanewactivity.
builder.setContentIntent(resultPendingIntent);

ConstructtheBigView

Thissnippetshowshowtosetupthebuttonsthatwillappearinthebigview:

//SetsuptheSnoozeandDismissactionbuttonsthatwillappearinthe
//bigviewofthenotification.
IntentdismissIntent=newIntent(this,PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
PendingIntentpiDismiss=PendingIntent.getService(this,0,dismissIntent,0);

IntentsnoozeIntent=newIntent(this,PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
PendingIntentpiSnooze=PendingIntent.getService(this,0,snoozeIntent,0);

Thissnippetshowshowtoconstructthe
Builder
object.Itsetsthestyleforthebigviewtobe"bigtext,"andsetsitscontenttobetheremindermessage.Ituses
addAction()
toaddtheSnoozeandDismissbuttons(andtheirassociatedpendingintents)thatwillappearinthenotification'sbigview:

//ConstructstheBuilderobject.
NotificationCompat.Builderbuilder=
newNotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL)//requiresVIBRATEpermission
/*
*Setsthebigview"bigtext"styleandsuppliesthe
*text(theuser'sremindermessage)thatwillbedisplayed
*inthedetailareaoftheexpandednotification.
*Thesecallsareignoredbythesupportlibraryfor
*pre-4.1devices.
*/
.setStyle(newNotificationCompat.BigTextStyle()
.bigText(msg))
.addAction(R.drawable.ic_stat_dismiss,
getString(R.string.dismiss),piDismiss)
.addAction(R.drawable.ic_stat_snooze,
getString(R.string.snooze),piSnooze);


DisplayingProgressinaNotification

PREVIOUSNEXT

THISLESSONTEACHESYOUTO

DisplayaFixed-durationprogressIndicator

DisplayaContinuingActivityIndicator

YOUSHOULDALSOREAD

NotificationsAPIGuide

IntentsandIntentFilters

NotificationsDesignGuide

Notificationscanincludeananimatedprogressindicatorthatshowsusersthestatusofanongoingoperation.Ifyoucanestimatehowlongtheoperationtakesandhowmuchofitiscompleteatanytime,usethe"determinate"formoftheindicator(aprogressbar).Ifyoucan'testimatethelengthoftheoperation,usethe"indeterminate"formoftheindicator(anactivityindicator).

Progressindicatorsaredisplayedwiththeplatform'simplementationofthe
ProgressBar
class.

Touseaprogressindicator,call
setProgress()
.Thedeterminateandindeterminateformsaredescribedinthefollowingsections.

DisplayaFixed-durationProgressIndicator

Todisplayadeterminateprogressbar,addthebartoyournotificationbycalling
setProgress(max,progress,false)
andthenissuethenotification.Thethirdargumentisabooleanthatindicateswhethertheprogressbarisindeterminate(true)ordeterminate(false).Asyouroperationproceeds,increment
progress
,andupdatethenotification.Attheendoftheoperation,
progress
shouldequal
max
.Acommonwaytocall
setProgress()
istoset
max
to100andthenincrement
progress
asa"percentcomplete"valuefortheoperation.

Youcaneitherleavetheprogressbarshowingwhentheoperationisdone,orremoveit.Ineithercase,remembertoupdatethenotificationtexttoshowthattheoperationiscomplete.Toremovetheprogressbar,call
setProgress(0,0,false)
.Forexample:

intid=1;
...
mNotifyManager=
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder=newNotificationCompat.Builder(this);
mBuilder.setContentTitle("PictureDownload")
.setContentText("Downloadinprogress")
.setSmallIcon(R.drawable.ic_notification);
//Startalengthyoperationinabackgroundthread
newThread(
newRunnable(){
@Override
publicvoidrun(){
intincr;
//Dothe"lengthy"operation20times
for(incr=0;incr<=100;incr+=5){
//Setstheprogressindicatortoamaxvalue,the
//currentcompletionpercentage,and"determinate"
//state
mBuilder.setProgress(100,incr,false);
//Displaystheprogressbarforthefirsttime.
mNotifyManager.notify(id,mBuilder.build());
//Sleepsthethread,simulatinganoperation
//thattakestime
try{
//Sleepfor5seconds
Thread.sleep(5*1000);
}catch(InterruptedExceptione){
Log.d(TAG,"sleepfailure");
}
}
//Whentheloopisfinished,updatesthenotification
mBuilder.setContentText("Downloadcomplete")
//Removestheprogressbar
.setProgress(0,0,false);
mNotifyManager.notify(id,mBuilder.build());
}
}
//Startsthethreadbycallingtherun()methodinitsRunnable
).start();

Theresultingnotificationsareshowninfigure1.Ontheleftsideisasnapshotofthenotificationduringtheoperation;ontherightsideisasnapshotofitaftertheoperationhasfinished.



Figure1.Theprogressbarduringandaftertheoperation.

DisplayaContinuingActivityIndicator

Todisplayacontinuing(indeterminate)activityindicator,addittoyournotificationwith
setProgress(0,0,true)
andissuethenotification.Thefirsttwoargumentsareignored,andthethirdargumentdeclaresthattheindicatorisindeterminate.Theresultisanindicatorthathasthesamestyleasaprogressbar,exceptthatitsanimationisongoing.

Issuethenotificationatthebeginningoftheoperation.Theanimationwillrununtilyoumodifyyournotification.Whentheoperationisdone,call
setProgress(0,0,false)
andthenupdatethenotificationtoremovetheactivityindicator.Alwaysdothis;otherwise,theanimationwillrunevenwhentheoperationiscomplete.Alsoremembertochangethenotificationtexttoindicatethattheoperationiscomplete.

Toseehowcontinuingactivityindicatorswork,refertotheprecedingsnippet.Locatethefollowinglines:

//Setstheprogressindicatortoamaxvalue,thecurrentcompletion
//percentage,and"determinate"state
mBuilder.setProgress(100,incr,false);
//Issuesthenotification
mNotifyManager.notify(id,mBuilder.build());

Replacethelinesyou'vefoundwiththefollowinglines.Noticethatthethirdparameterinthe
setProgress()
callissetto
true
toindicatethattheprogressbarisindeterminate:

//Setsanactivityindicatorforanoperationofindeterminatelength
mBuilder.setProgress(0,0,true);
//Issuesthenotification
mNotifyManager.notify(id,mBuilder.build());

Theresultingindicatorisshowninfigure2:



Figure2.Anongoingactivityindicator.


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: