您的位置:首页 > 其它

Notifications 通知

2015-06-16 00:37 351 查看
Notifications

利用这个可以通知用户一些事件

Notification的基本布局:

包括:图标,标题,内容,时间戳

基本布局只能展示少量数据,如果要展示大量数据,可以运用可扩展的布局来显示

Android提供了可扩展的文本和图片两种方式:例如

我们在通知的布局上面可以放置按钮来响应用户操作:

但是我们要尽可能的不要放置太多按钮

通知可以指定优先级:来指示通知的重要性:

当一个应用发来相同类型的通知的时候,我们可以选择是否堆叠:例如QQ的消息

可以为通知指定来通知的声音,震动,发光等提醒方式

Normalview

此view的最高是64dp.即使你指定再大也没有用

Bigview

没指定它的最高高度,这个view的使用条件是最低Android4.1.

它与normalview的区别在7上:

这个7里面的内容具体显示样式可以指定:

Bigpicturestyle最大256dp
大图片

Bigtextstyle区域文字

Inboxstyle多行文本

创建一个Notification

必须包含一下内容:

·
Asmallicon,setbysetSmallIcon()
·Atitle,setbysetContentTitle()
·Detailtext,setbysetContentText()

对一个通知,我们应该至少指定一个动作,如果要实现点击通知跳转到应用的某个activity

你要使用
PendingIntent
containing
an
Intent
that
startsan
Activity
in
yourapplication.

setContentIntent()
.

创建一个简单的notification,点击通知后会跳转到某个activity

NotificationCompat.BuildermBuilder=

newNotificationCompat.Builder(this)

.setSmallIcon(R.drawable.notification_icon)

.setContentTitle("Mynotification")

.setContentText("HelloWorld!");


//CreatesanexplicitintentforanActivityinyourapp

IntentresultIntent=newIntent(this,ResultActivity.class);

//Thestackbuilderobjectwillcontainanartificialbackstackforthe

//startedActivity.

//ThisensuresthatnavigatingbackwardfromtheActivityleadsoutof

//yourapplicationtotheHomescreen.

TaskStackBuilderstackBuilder=TaskStackBuilder.create(this);

//AddsthebackstackfortheIntent(butnottheIntentitself)

stackBuilder.addParentStack(ResultActivity.class);

//AddstheIntentthatstartstheActivitytothetopofthestack

stackBuilder.addNextIntent(resultIntent);


PendingIntentresultPendingIntent=

stackBuilder.getPendingIntent(

0,

PendingIntent.FLAG_UPDATE_CURRENT

);

mBuilder.setContentIntent(resultPendingIntent);


NotificationManagermNotificationManager=

(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

//mIdallowsyoutoupdatethenotificationlateron.

mNotificationManager.notify(mId,mBuilder.build());




创建一个bigviewstyle,创建必须保证在最低是android4.1

NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(this)

.setSmallIcon(R.drawable.notification_icon)

.setContentTitle("Eventtracker")

.setContentText("Eventsreceived")

NotificationCompat.InboxStyleinboxStyle=

newNotificationCompat.InboxStyle();

String[]events=newString[6];

//SetsatitlefortheInboxstylebigview

inboxStyle.SetBigContentTitle("Eventtrackerdetails:");

...

//Moveseventsintothebigview

for(inti=0;i<events.length;i++){


inboxStyle.addLine(events[i]);

}

//Movesthebigviewstyleobjectintothenotificationobject.

mBuilder.setStyle(inBoxStyle);

...

//Issuethenotificationhere.


管理Notifications,

如果同一个app发出多个同类型的通知,我们应该将它归类,不应该让其每发个通知都显示在notifiactions上。保证是最新的提示通知

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());

...


移除notifications

可以用手机系统自带的按钮clearall

或者

点击notifications也可让它消失:etAutoCancel()

或者

指明id,
cancel()


或者cancelAll()

PreservingNavigationwhenStartinganActivity

当由通知启动一个activity的时候,这里有两种情况可供选择:

Regularactivity
一般我们的应用都会采用这种模式:


这个是正常的启动了一个activity,它会创建一个新的task,.例如:

当我们收到一个短信的通知时,当我们点击短信,查看这个短信的具体内容后,如果此时我们按返回键,这个时候会退到短信应用的Home界面

Specialactivity
这个不会启动一个新的task。在某种意思上,它是一个继承的notification
。如果我们采用这种模式,这会出现在点击通知,查看具体通知信息后,按返回键,会回退到手机桌面


SettinguparegularactivityPendingIntent

1.Defineyourapplication's
Activity
hierarchy
inthemanifest.

<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>


2.Createabackstackbasedonthe
Intent
thatstarts
the
Activity
:

...

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());


SettingupaspecialactivityPendingIntent

1.
Inyourmanifest,addthefollowingattributestothe
<activity>
element
forthe
Activity


<activity

android:name=".ResultActivity"

...

android:launchMode="singleTask"

android:taskAffinity=""

android:excludeFromRecents="true">

</activity>

...


2.Buildandissuethenotification:

//InstantiateaBuilderobject.

NotificationCompat.Builderbuilder=newNotificationCompat.Builder(this);

//CreatesanIntentfortheActivity

IntentnotifyIntent=

newIntent(newComponentName(this,ResultActivity.class));

//SetstheActivitytostartinanew,emptytask

notifyIntent.setFlags(FLAG_ACTIVITY_NEW_TASK|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());


DisplayingProgressinaNotification

展示一个带进度的通知

在android4.0之后可以直接使用
setProgress()
.。然而4.0以前我们就必须自顶一个notification的布局了,然后在布局里面加个progressbar

带具体进度的

...

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(0,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();


Displayingacontinuingactivityindicator

只是展示正在下载的进度

toyournotificationwith
setProgress(0,
0,true)
(thefirsttwoargumentsareignored),andissuethenotification.

Whentheoperationisdone,call
setProgress()
setProgress(0,0,false)
andthenupdatethenotificationtoremovetheactivityindicator.

//Setsanactivityindicatorforanoperationofindeterminatelength

mBuilder.setProgress(0,0,false);

//Issuesthenotification

mNotifyManager.notify(0,mBuilder.build());


CustomNotificationLayouts

RemoteViews

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