0703-APP-Notification-statue-bar

0703-APP-Notification-statue-bar

1.展示显示textTicker和仅仅有icon的两种情况:当參数showTicker为true时显示否则不显示

        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(textId);

        // choose the ticker text
        String tickerText = showTicker ? getString(textId) : null;

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(moodId, tickerText,
                System.currentTimeMillis());

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.status_bar_notifications_mood_title),
                       text, makeMoodIntent(moodId));

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNotificationManager.notify(R.layout.status_bar_notifications, notification);
    

2.展示通过view创建notifaction

		// Instead of the normal constructor, we're going to use the one with no
		// args and fill
		// in all of the data ourselves. The normal one uses the default layout
		// for notifications.
		// You probably want that in most cases, but if you want to do something
		// custom, you
		// can set the contentView field to your own RemoteViews object.
		Notification notif = new Notification();

		// This is who should be launched if the user selects our notification.
		notif.contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, NotificationDisplay.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("moodimg", moodId), PendingIntent.FLAG_UPDATE_CURRENT);

		// In this sample, we'll use the same text for the ticker and the
		// expanded notification
		CharSequence text = getText(textId);
		notif.tickerText = text;

		// the icon for the status bar
		notif.icon = moodId;

		// our custom view
		RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.status_bar_balloon);
		contentView.setTextViewText(R.id.text, text);
		contentView.setImageViewResource(R.id.icon, moodId);
		notif.contentView = contentView;

		// we use a string id because is a unique number. we use it later to
		// cancel the
		// notification
		mNotificationManager.notify(R.layout.status_bar_notifications, notif);
	

3.notifacation 设置声音和震动

 private void setDefault(int defaults) {
        
        // This method sets the defaults on the notification before posting it.
        
        // This is who should be launched if the user selects our notification.
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, StatusBarNotifications.class), 0);

        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.status_bar_notifications_happy_message);

        final Notification notification = new Notification(
                R.drawable.stat_happy,       // the icon for the status bar
                text,                        // the text to display in the ticker
                System.currentTimeMillis()); // the timestamp for the notification

        notification.setLatestEventInfo(
                this,                        // the context to use
                getText(R.string.status_bar_notifications_mood_title),
                                             // the title for the notification
                text,                        // the details to display in the notification
                contentIntent);              // the contentIntent (see above)

        notification.defaults = defaults;
        
        mNotificationManager.notify(
                   R.layout.status_bar_notifications, // we use a string id because it is a unique
                                                      // number.  we use it later to cancel the
                   notification);                     // notification
    }    

公共代码(被调用的代码)

  private PendingIntent makeMoodIntent(int moodId) {
        // The PendingIntent to launch our activity if the user selects this
        // notification.  Note the use of FLAG_UPDATE_CURRENT so that if there
        // is already an active matching pending intent, we will update its
        // extras to be the ones passed in here.
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NotificationDisplay.class)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .putExtra("moodimg", moodId),
                PendingIntent.FLAG_UPDATE_CURRENT);
        return contentIntent;
    }

4.常驻通知的样例

/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.app;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

/**
 * This is an example of implementing an application service that can
 * run in the "foreground".  It shows how to code this to work well by using
 * the improved Android 2.0 APIs when available and otherwise falling back
 * to the original APIs.  Yes: you can take this exact code, compile it
 * against the Android 2.0 SDK, and it will against everything down to
 * Android 1.0.
 */
public class ForegroundService extends Service {
    static final String ACTION_FOREGROUND = "com.example.android.apis.FOREGROUND";
    static final String ACTION_BACKGROUND = "com.example.android.apis.BACKGROUND";
    

    private static final Class[] mStartForegroundSignature = new Class[] {
        int.class, Notification.class};
    private static final Class[] mStopForegroundSignature = new Class[] {
        boolean.class};
    
    private NotificationManager mNM;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];
    
    /**
     * This is a wrapper around the new startForeground method, using the older
     * APIs if it is not available.
     */
    void startForegroundCompat(int id, Notification notification) {
        // If we have the new startForeground API, then use it.
        if (mStartForeground != null) {
            mStartForegroundArgs[0] = Integer.valueOf(id);
            mStartForegroundArgs[1] = notification;
            try {
                mStartForeground.invoke(this, mStartForegroundArgs);
            } catch (InvocationTargetException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke startForeground", e);
            } catch (IllegalAccessException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke startForeground", e);
            }
            return;
        }
        
        // Fall back on the old API.
        setForeground(true);
        mNM.notify(id, notification);
    }
    
    /**
     * This is a wrapper around the new stopForeground method, using the older
     * APIs if it is not available.
     */
    void stopForegroundCompat(int id) {
        // If we have the new stopForeground API, then use it.
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
            } catch (InvocationTargetException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke stopForeground", e);
            } catch (IllegalAccessException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke stopForeground", e);
            }
            return;
        }
        
        // Fall back on the old API.  Note to cancel BEFORE changing the
        // foreground state, since we could be killed at that point.
        mNM.cancel(id);
        setForeground(false);
    }
    
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        try {
        	com.example.android.apis.Log.log(getClass().getName());
        	
            mStartForeground = getClass().getMethod("startForeground",
                    mStartForegroundSignature);
            com.example.android.apis.Log.log(mStartForeground.getName());
            mStopForeground = getClass().getMethod("stopForeground",
                    mStopForegroundSignature);
        } catch (NoSuchMethodException e) {
            // Running on an older platform.
            mStartForeground = mStopForeground = null;
        }
    }

    @Override
    public void onDestroy() {
        // Make sure our notification is gone.
        stopForegroundCompat(R.string.foreground_service_started);
    }



    // This is the old onStart method that will be called on the pre-2.0
    // platform.  On 2.0 or later we override onStartCommand() so this
    // method will not be called.
    @Override
    public void onStart(Intent intent, int startId) {
        handleCommand(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }


    void handleCommand(Intent intent) {
        if (ACTION_FOREGROUND.equals(intent.getAction())) {
            // In this sample, we'll use the same text for the ticker and the expanded notification
            CharSequence text = getText(R.string.foreground_service_started);

            // Set the icon, scrolling text and timestamp
            Notification notification = new Notification(R.drawable.stat_sample, text,
                    System.currentTimeMillis());

            // The PendingIntent to launch our activity if the user selects this notification
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, Controller.class), 0);

            // Set the info for the views that show in the notification panel.
            notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                           text, contentIntent);
            
            startForegroundCompat(R.string.foreground_service_started, notification);
            
        } else if (ACTION_BACKGROUND.equals(intent.getAction())) {
            stopForegroundCompat(R.string.foreground_service_started);
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    // ----------------------------------------------------------------------

    /**
     * <p>Example of explicitly starting and stopping the {@link ForegroundService}.
     * 
     * <p>Note that this is implemented as an inner class only keep the sample
     * all together; typically this code would appear in some separate class.
     */
    public static class Controller extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.foreground_service_controller);

            // Watch for button clicks.
            Button button = (Button)findViewById(R.id.start_foreground);
            button.setOnClickListener(mForegroundListener);
            button = (Button)findViewById(R.id.start_background);
            button.setOnClickListener(mBackgroundListener);
            button = (Button)findViewById(R.id.stop);
            button.setOnClickListener(mStopListener);
        }

        private OnClickListener mForegroundListener = new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(ForegroundService.ACTION_FOREGROUND);
                intent.setClass(Controller.this, ForegroundService.class);
                startService(intent);
            }
        };

        private OnClickListener mBackgroundListener = new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(ForegroundService.ACTION_BACKGROUND);
                intent.setClass(Controller.this, ForegroundService.class);
                startService(intent);
            }
        };

        private OnClickListener mStopListener = new OnClickListener() {
            public void onClick(View v) {
                stopService(new Intent(Controller.this,
                        ForegroundService.class));
            }
        };
    }
}

凝视notification.flags能够设置notification能否够点击消除,是否自己主动消除等状态

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/119046.html原文链接:https://javaforall.net

(0)
上一篇 2021年11月23日 下午2:00
下一篇 2021年11月23日 下午2:00


相关推荐

  • MATLAB 2017b 安装教程 (推荐)

    MATLAB 2017b 安装教程 (推荐)MATLAB2017b安装教程matlab2017b安装包及安装教程链接:https://pan.baidu.com/s/1riEvbTQnDSeo7bhix7YLZQ密码:z4em本Markdown编辑器使用[Sta**重点内容**ckEdit][6]修改而来,用它写博客,将会带来全新的体验哦:Matlab安装教程:1、下载文件,得到破解文件。*点…

    2022年5月28日
    57
  • PetaLinux学习笔记 1

    PetaLinux学习笔记 1迟迟没有做底板,所以只能把Linux写到FLASH上了。还好这个FLASH够大。官方所说的有点问题,最后一句改成petalinux-package–boot–fsbl~/FTP_Folder/ax_peta/images/linux/zynq_fsbl.elf–fpga–u-boot–kernel–force再烧进去就可以跑了。手册ug821有说明,先搞清楚它…

    2025年11月1日
    6
  • RabbitMQ入门:总结

    随着上一篇博文的发布,RabbitMQ的基础内容我也学习完了,RabbitMQ入门系列的博客跟着收官了,以后有机会的话再写一些在实战中的应用分享,多谢大家一直以来的支持和认可。RabbitMQ入门系

    2022年2月16日
    52
  • 大端模式和小端模式详解

    大端模式和小端模式详解怎么去理解大端和小端 大端模式和小端是实际的字节顺序和存储的地址顺序对应关系的两种模式 总结如下 大端模式 低地址对应高字节小端模式 低地址对应低字节不管是大端还是小端模式 我们在读取和存储数据的时候一定都是从内存的低地址依次向高地址读取或写入 打个比方 我们定义一个数组 chararray 5 0 1 2 3 4 学习过 C 语言应该都知道 array 是这个数组存

    2026年3月18日
    2
  • 初始化磁盘_c++怎么初始化

    初始化磁盘_c++怎么初始化磁盘在联机后要初始化,同样也有两种方法,一种是调用IOCTL_DISK_CREATE_DISK,还有一种是调用WMI的Initialize方法。1.首先说说简单的WMI的方法:大致思路同博客:C++实现磁盘联机 先获取磁盘的id,然后执行无参数方法Initialize 核心模块代码如下:wchar_tmsftDiskObjectID[256];GetWMIMSFTDiskObjectId(…

    2025年11月26日
    6
  • vue实现移动端音乐APP

    vue实现移动端音乐APP项目基于 vue2 6 使用 vue cli 搭建项目项目部分功能预览目前实现的功能发现音乐首页 侧边栏弹窗 歌单推荐 歌单详情 最新歌曲 歌曲播放 获取排行榜单 歌词同步滚动 手机号登录 手机号注册 后续还会继续完善登录与主页面的链接 验证码验证 我的音乐 视频 云村等功能 技术栈 vue cli 搭建项目 vue 构建用户界面框架 vue router 路由的实现 axios 简化异步操作 ES6 ECMAScript 新一代语法 用到了解构赋值 模块化 还有一些方法

    2026年3月17日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号