Notifications 通知

Notifications

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

 

Notification的基本布局:

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

 

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

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

 

 

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

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

 

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

 

 

 

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

 

 

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

 

 

Normal view

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

 

 

 

Big view

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

它与normal view的区别在7上:

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

Big picture style  最大256dp 大图片

 

Big text style 区域文字

 

Inbox style 多行文本

 

 

创建一个Notification

必须包含一下内容:

·                         A small icon, set by setSmallIcon()

·                       A title, set by setContentTitle()

·                       Detail text, set by setContentText()

 

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

你要使用PendingIntent containing an Intent that starts an Activity in your application.

setContentIntent().

 

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

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!");
 
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
 
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
        );
mBuilder.setContentIntent(resultPendingIntent);
 
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
 
 

 

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

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("Event tracker")
    .setContentText("Events received")
NotificationCompat.InboxStyle inboxStyle =
        new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox style big view
inboxStyle.SetBigContentTitle("Event tracker details:");
...
// Moves events into the big view
for (int i=0; i < events.length; i++) {
 
    inboxStyle.addLine(events[i]);
}
// Moves the big view style object into the notification object.
mBuilder.setStyle(inBoxStyle);
...
// Issue the notification here.

 

管理Notifications

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

mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle("New Message")
    .setContentText("You've received new messages.")
    .setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
    mNotifyBuilder.setContentText(currentText)
        .setNumber(++numMessages);
    // Because the ID remains unchanged, the existing notification is
    // updated.
    mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());
...

移除notifications

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

或者

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

或者

       指明id,  cancel() 

或者cancelAll()

 

 

PreservingNavigation when Starting an Activity

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

 

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

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

 

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

 

 

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

 

 

Setting up a regular activityPendingIntent

1.     Define your application's Activity hierarchy in the manifest.

<activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android: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. Create a back stack based on the Intent thatstarts the Activity:

...
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
...
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());

 

Setting upa special activity PendingIntent

1.       In your manifest, add the following attributes to the <activity> element for the Activity

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

2.       Build and issue the notification:

// Instantiate a Builder object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Creates an Intent for the Activity
Intent notifyIntent =
        new Intent(new ComponentName(this, ResultActivity.class));
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
PendingIntent notifyIntent =
        PendingIntent.getActivity(
        this,
        0,
        notifyIntent
        PendingIntent.FLAG_UPDATE_CURRENT
);
 
// Puts the PendingIntent into the notification builder
builder.setContentIntent(notifyIntent);
// Notifications are issued by sending them to the
// NotificationManager system service.
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Builds an anonymous Notification object from the builder, and
// passes it to the NotificationManager
mNotificationManager.notify(id, builder.build());

 

DisplayingProgress in a Notification

展示一个带进度的通知

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

带具体进度的

       ...
mNotifyManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
    .setContentText("Download in progress")
    .setSmallIcon(R.drawable.ic_notification);
// Start a lengthy operation in a background thread
new Thread(
    new Runnable() {
        @Override
        public void run() {
            int incr;
            // Do the "lengthy" operation 20 times
            for (incr = 0; incr <= 100; incr+=5) {
                    // Sets the progress indicator to a max value, the
                    // current completion percentage, and "determinate"
                    // state
                    mBuilder.setProgress(100, incr, false);
                    // Displays the progress bar for the first time.
                    mNotifyManager.notify(0, mBuilder.build());
                        // Sleeps the thread, simulating an operation
                        // that takes time
                        try {
                            // Sleep for 5 seconds
                            Thread.sleep(5*1000);
                        } catch (InterruptedException e) {
                            Log.d(TAG, "sleep failure");
                        }
            }
            // When the loop is finished, updates the notification
            mBuilder.setContentText("Download complete")
            // Removes the progress bar
                    .setProgress(0,0,false);
            mNotifyManager.notify(ID, mBuilder.build());
        }
    }
// Starts the thread by calling the run() method in its Runnable
).start();

 

 

Displaying a continuing activityindicator

只是展示正在下载的进度

to your notification with setProgress(0, 0, true)(the first two arguments are ignored), and issue the notification.

 

When the operation is done, call setProgress() setProgress(0, 0, false) and then update the notification to remove the activity indicator. 

// Sets an activity indicator for an operation of indeterminate length
mBuilder.setProgress(0, 0, false);
// Issues the notification
mNotifyManager.notify(0, mBuilder.build());

 

CustomNotification Layouts

RemoteViews

setContent().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值