通知欄發送消息Notification(可以使用自定義的布局)

一個簡單的應用場景:假如用戶打開Activity以后,按Home鍵,此時Activity 進入-> onPause() -> onStop() 不可見。代碼在此時機發送一個Notification到通知欄。當用戶點擊通知欄的Notification后,又重新onRestart() -> onStart() -> onResume() 切換回原Activity。

  1 package com.zzw.testnotification;
  2 
  3 import android.app.Activity;
  4 import android.app.Notification;
  5 import android.app.NotificationManager;
  6 import android.app.PendingIntent;
  7 import android.content.Context;
  8 import android.content.Intent;
  9 import android.os.Bundle;
 10 import android.support.v4.app.NotificationCompat.Builder;
 11 import android.util.Log;
 12 import android.widget.RemoteViews;
 13 
 14 public class MainActivity extends Activity {
 15 
 16     private static final String TAG = "---->";
 17 
 18     private final int NOTIFICATION_ID = 0xa01;
 19     private final int REQUEST_CODE = 0xb01;
 20 
 21     @Override
 22     protected void onCreate(Bundle savedInstanceState) {
 23         super.onCreate(savedInstanceState);
 24         setContentView(R.layout.activity_main);
 25         Log.d(TAG, "onCreate");
 26     }
 27 
 28     @Override
 29     protected void onResume() {
 30         Log.d(TAG, "onResume");
 31         super.onResume();
 32     }
 33 
 34     @Override
 35     protected void onDestroy() {
 36         Log.d(TAG, "onDestroy");
 37         super.onDestroy();
 38     }
 39 
 40     @Override
 41     protected void onPause() {
 42         Log.d(TAG, "onPause");
 43         super.onPause();
 44     }
 45 
 46     @Override
 47     protected void onRestart() {
 48         Log.d(TAG, "onRestart");
 49         super.onRestart();
 50     }
 51 
 52     @Override
 53     protected void onStart() {
 54         Log.d(TAG, "onStart");
 55         super.onStart();
 56     }
 57 
 58     @Override
 59     protected void onStop() {
 60         super.onStop();
 61         Log.d(TAG, "onStop");
 62         sendNotification(this, NOTIFICATION_ID, "這是標題", "這是內容");
 63     }
 64 
 65     
 66     //可當作發送通知欄消息模版使用
 67     private void sendNotification(Context context, int notification_ID, String title, String content) {
 68         NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 69 
 70         //使用默認的通知欄布局
 71         Builder builder = new Builder(context);
 72         // 此處設置的圖標僅用于顯示新提醒時候出現在設備的通知欄
 73         builder.setSmallIcon(R.drawable.ic_launcher);
 74         builder.setContentTitle(title);
 75         builder.setContentText(content);
 76 
 77         Notification notification = builder.build();
 78 
 79         /*    使用自定義的通知欄布局
 80          *  當用戶下來通知欄時候看到的就是RemoteViews中自定義的Notification布局
 81          */
 82         // RemoteViews contentView = new RemoteViews(context.getPackageName(),
 83         // R.layout.notification);
 84         // contentView.setImageViewResource(R.id.imageView, R.drawable.ic_launcher);
 85         // contentView.setTextViewText(R.id.title, "土耳其和IS的秘密");
 86         // contentView.setTextViewText(R.id.text, "土耳其拒絕向俄羅斯道歉,懷疑有IS撐腰");
 87         // notification.contentView = contentView;
 88 
 89         // 發送通知到通知欄時:提示聲音 + 手機震動 + 點亮Android手機呼吸燈。
 90         // 注意!!(提示聲音 + 手機震動)這兩項基本上Android手機均支持。
 91         // 但Android呼吸燈能否點亮則取決于各個手機硬件制造商自家的設置。
 92         notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
 93 
 94         // 點擊notification自動消失
 95         notification.flags = Notification.FLAG_AUTO_CANCEL;
 96 
 97         // 通知的時間
 98         notification.when = System.currentTimeMillis();
 99 
100         // 需要注意的是,作為選項,此處可以設置MainActivity的啟動模式為singleTop,避免重復新建onCreate()。
101         Intent intent = new Intent(context, MainActivity.class);
102 
103         // 當用戶點擊通知欄的Notification時候,切換回MainActivity。
104         PendingIntent pi = PendingIntent.getActivity(context, REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
105         notification.contentIntent = pi;
106 
107         // 發送到手機的通知欄
108         notificationManager.notify(notification_ID, notification);
109     }
110 
111     //可當作清除通知欄消息模版使用
112     private void deleteNotification(int id) {
113         NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
114         notificationManager.cancel(id);
115     }
116 }

需要注意的是,默認Android的Activity為標準模式,即每次都new一個新的Activity出來,不是原先的Activity,在本例中,可以觀察到MainActivity中的onCreate()如果不修改啟動模式,則每次本調用每次TextView顯示的時間不同(遞增),所有為了使用原來的Activity、避免重復new一個新的出來,需要:

在AndroidManifest.xml中修改MainActivity啟動模式為:singleTop

<activityandroid:name=".MainActivity"android:label="@string/app_name"android:launchMode="singleTop" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

notification.xml文件源代碼:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent" >
 5 
 6     <ImageView
 7         android:id="@+id/imageView"
 8         android:layout_width="50dp"
 9         android:layout_height="50dp"
10         android:layout_alignParentLeft="true"
11         android:layout_centerVertical="true"
12         android:src="@drawable/ic_launcher" />
13 
14     <TextView
15         android:id="@+id/title"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:layout_above="@+id/text"
19         android:layout_alignParentRight="true"
20         android:layout_alignTop="@+id/imageView"
21         android:layout_marginLeft="18dp"
22         android:layout_toRightOf="@+id/imageView"
23         android:gravity="center_vertical"
24         android:singleLine="true"
25         android:text="TextView" />
26 
27     <TextView
28         android:id="@+id/text"
29         android:layout_width="wrap_content"
30         android:layout_height="wrap_content"
31         android:layout_alignBottom="@+id/imageView"
32         android:layout_alignLeft="@+id/title"
33         android:gravity="center_vertical"
34         android:singleLine="true"
35         android:text="TextView" />
36 
37 
38 </RelativeLayout>
notification.xml

由于sdk版本的不同,有的需要添加震動的權限:

<uses-permission android:name="android.permission.VIBRATE"/>

?

轉載于:https://www.cnblogs.com/zzw1994/p/4999960.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/374089.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/374089.shtml
英文地址,請注明出處:http://en.pswp.cn/news/374089.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

退出頁面刪除cookie_Cookie 機制

歡迎關注公眾號 學習資料不會少01「HTTP 協議是無狀態的」對于瀏覽器的每一次請求&#xff0c;服務器都會獨立處理&#xff0c;不與之前或之后的請求發生關聯。這個過程如圖 11-1 所示&#xff0c;3次“請求&#xff0f;響應”之間沒有任何關系。即使是同一個瀏覽器發送了3個請…

【程序員感悟系列】 由一點業務說開去

最近的工作不是很忙&#xff0c;我也趁著這個機會多讀了一些技術的書籍。比如剛讀完的《大話設計模式》&#xff0c;以將故事的形式講述了設計模式的方方面面&#xff0c;感覺還是不錯的。現在看的一本是英國人寫的《企業應用架構模式》。對于web的企業級應用&#xff0c;還是挺…

浮點數使用注意

public class DoubleNote{ public static void main(String[] args){ System.out.println((1.0-0.8)); //結果&#xff1a; 0.19999999999999996 //浮點數“”要慎用 System.out.println((1.0-0.8)0.2)); // false } } /* Java 浮點數表示采用IEE765表示法 */

Oracle WebLogic Java云服務–幕后花絮。

在開放世界方面&#xff0c;發生的一件大事可能是出乎意料的消息&#xff0c;那就是Oracle最終支持云計算發展并提供自己的公共云服務 。 除了官方公告之外&#xff0c;Aquarium上&#xff08; 此處和此處 &#xff09;的內容或多或少都沒有多少內容&#xff0c;您找不到很多信…

QT子窗口及停靠實現

Demo的效果 頭文件中的變量聲明 //退出動作QAction* exit;//菜單欄菜單QMenu* filemenu;QMenu* actiona;//在狀態欄的標簽控件QLabel* label;//兩個停靠窗口QDockWidget *dockwidget;QDockWidget *dockwidget_textbox; CPP源文件中的對象定義 //創建初始化按鈕,將要放到第一個窗…

python關鍵字驅動框架搭建_python webdriver混合驅動測試框架(數據驅動+關鍵字驅動)...

混合驅動&#xff1a;把數據驅動、關鍵字驅動結合起來一起使用testdata.txthttp://www.126.comhttp://www.sohu.comteststep.txtopen||chromevisit||${url}sleep||3主程序腳本hybrid.py#encodingutf-8import refrom selenium import webdriverimport timewith open("tests…

iOS-cocoapods使用方法

1.CocoaPods的安裝及使用:http://code4app.com/article/cocoapods-install-usagehttp://objccn.io/issue-6-4/http://www.jianshu.com/p/5fc15906c53a查看當前的源gem sources -lgem sources --remove https://rubygems.org///等有反應之后再敲入以下命令&#xff0c;添加淘寶鏡…

Tomcat 6連接池配置

Tomcat 6&#xff0c;配置了連接池&#xff0c;可是運行總是報HTTP Status 500 - javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class for connect URL null的錯誤&#xff0c;檢查URL沒有錯啊&#xff01…

Java并發教程–可調用,將來

從Java的第一個發行版開始&#xff0c;Java的美麗之處之一就是我們可以輕松編寫多線程程序并將異步處理引入我們的設計中。 Thread類和Runnable接口與Java的內存管理模型結合使用&#xff0c;意味著可以進行簡單的線程編程。 但是&#xff0c;如第3部分所述&#xff0c; Thread…

python基本運算符_06-Python基礎知識學習---基本運算符

算術運算符python支持的算數運算符與數學上計算的符號使用是一致的(x 5 , y 2)&#xff1a;算術運算符描述示例兩個對象相加x y 7-兩個對象相減x - y 3*兩個對象相乘x * y 10/除&#xff0c;返回值保留整數和小數部分x / y 2.5//整除&#xff0c;只保留整數部分x // y …

java wait()和sleep() 的區別

之前在寫代碼的時候&#xff0c;如果需要讓線程等待一會&#xff0c;就直接使用sleep()方法&#xff0c;一直也沒有出過問題。而wait()方法的出場率很高&#xff0c;每次打一個句點的時候&#xff0c;對象的方法彈出來&#xff0c;總是能看到wait()在其中&#xff0c;wait()是一…

異常:com.microsoft.sqlserver.jdbc.SQLServerException: 將截斷字符串或二進制數據。

com.microsoft.sqlserver.jdbc.SQLServerException: 將截斷字符串或二進制數據。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196) at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246) a…

Java中的數據庫架構導航

jOOQ的重要組成部分是數據庫架構導航模塊jooq-meta。 代碼生成器使用它來發現相關的架構對象。 我多次被問到為什么我要自己滾動而不使用其他庫&#xff0c;例如SchemaCrawler或SchemaSpy &#xff0c;確實很遺憾我不能依賴其他穩定的第三方產品。 以下是有關數據庫架構導航的一…

python自動化測試的工具_python自動化測試(3)- 自動化框架及工具

3 基本示例如下示例也來自于官方文檔 basic_demo.py&#xff1a;# coding:utf-8"""基本的自動化測試腳本 basic_demo.py"""__author__ zhengimport unittestclass TestStringMethods(unittest.TestCase):def setUp(self):print init by setUp…

Html轉Word文檔,解決無法保存網絡圖片的問題

最近項目中需要這個功能&#xff0c;網上有很多word轉html的方法&#xff0c;但是html轉word的方法很少&#xff0c;因為html中的圖片轉換到本地比較麻煩&#xff1b; 開始的時候只能轉換不帶圖片的html內容&#xff0c;但是不符合要求&#xff0c;將html頁面中的圖片改成絕對路…

一不小心就掉大啦《數組使用注意》

今天程序提交答案總是不對&#xff0c;調試半天才發現本定義的是char s[4]{1,2,3,4} ; 程序運行過程中輸出才發現多了一個字符 printf("%s\n"); //結果12349 思前想后覺得可能是沒有字符數組結束符 (\0); 特別注意&#xff1a; 定義使用字符型數組時&#xff0c;應…

Java并發教程–阻塞隊列

如第3部分所述&#xff0c;Java 1.5中引入的線程池提供了核心支持&#xff0c;該支持很快成為許多Java開發人員的最愛。 在內部&#xff0c;這些實現巧妙地利用了Java 1.5中引入的另一種并發功能-阻塞隊列。 隊列 首先&#xff0c;簡要回顧一下什么是標準隊列。 在計算機科學…

json和字符串/數組/集合的互相轉換の神操作總結

一:前端字符串轉JSON的4種方式 1&#xff0c;eval方式解析&#xff0c;恐怕這是最早的解析方式了。 function strToJson(str){var json eval(( str ));return json; } 2&#xff0c;new Function形式&#xff0c;比較怪異哦。 function strToJson(str){var json (new Funct…

python 修改array_python 基礎_ 數組的 增刪改查3

數組是運用在多個數據存在一個變量中的&#xff0c;而在調用的時候可以調用所需要的數組。創建數組a [a,b,c,d,f]   #創建一個數組a其中有5個元素分別是abcdf1.查詢。所謂的查詢就是顯示變量a中一個或是一些元素print (a[1])  #打印出a變量中的序列1的元素&#xff0c;我們…

Android實現推送方式解決方案

Android實現推送方式解決方案 本文介紹在Android中實現推送方式的基礎知識及相關解決方案。推送功能在手機開發中應用的場景是越來起來了&#xff0c;不說別的&#xff0c;就我們手機上的新聞客戶端就時不j時的推送過來新的消息&#xff0c;很方便的閱讀最新的新聞信息。這種推…