Android 에서 Notification 의 용법 집합

우리 가 휴대 전 화 를 사용 할 때 문자 가 왔 는데 우리 가 클릭 하지 않 았 다 면 휴대 전화의 맨 위 상태 표시 줄 에 문자 메시지 의 작은 아이콘 알림 이 있 는 것 아 닙 니까?너 도 이런 기능 을 실현 하고 싶 지 않 니?오늘 의 Notification 은 바로 이 문 제 를 해결 하 는 것 이다.
우 리 는 안 드 로 이 드 시스템 도 계속 업그레이드 되 고 있다 는 것 을 알 고 있 습 니 다.Notification 과 관련 된 용법 도 여러 가지 가 있 습 니 다.어떤 방법 은 안 드 로 이 드 에 의 해 버 려 졌 습 니 다.지금 저 는 세 가지 다른 방법 을 실현 하고 서로 다른 안 드 로 이 드 버 전에 적응 하고 있 습 니 다.지금 나 는 코드 를 발표 할 것 이다.나 는 설명 을 코드 에 쓰 는 것 을 좋아한다.여기 서 나 는 더 이상 말 하지 않 겠 다.먼저 효과 도 를 보 자.

코드 를 보면 주요 코드 는 다음 과 같 습 니 다.

package net.loonggg.notification; 
import android.app.Activity; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.RemoteViews; 
public class MainActivity extends Activity { 
private static final int NOTIFICATION_FLAG = 1; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
} 
public void notificationMethod(View view) { 
//  Android      ,                NotificationManager,      Service。 
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
switch (view.getId()) { 
//      
case R.id.btn1: 
//     PendingIntent, Intent  ,            ,           activity,      PendingIntent,   Notification       Activity 
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 
new Intent(this, MainActivity.class), 0); 
//      Android 2.x         
// Notification notify1 = new Notification(R.drawable.message, 
// "TickerText:" + "      ,     !", System.currentTimeMillis()); 
Notification notify1 = new Notification(); 
notify1.icon = R.drawable.message; 
notify1.tickerText = "TickerText:      ,     !"; 
notify1.when = System.currentTimeMillis(); 
notify1.setLatestEventInfo(this, "Notification Title", 
"This is the notification message", pendingIntent); 
notify1.number = 1; 
notify1.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL           ,      。 
//             。  id  ,  click, statu         
manager.notify(NOTIFICATION_FLAG, notify1); 
break; 
//      API11      
case R.id.btn2: 
PendingIntent pendingIntent2 = PendingIntent.getActivity(this, 0, 
new Intent(this, MainActivity.class), 0); 
//   Notification.Builder     ,  API Level 
// API11      
Notification notify2 = new Notification.Builder(this) 
.setSmallIcon(R.drawable.message) //           ,       24×24,                  ,              ,    setLargeIcon(Bitmap 
// icon) 
.setTicker("TickerText:" + "      ,     !")//    status 
// bar         
.setContentTitle("Notification Title")//      status 
// bar Activity,     NotififyMessage TextView       
.setContentText("This is the notification message")// TextView         
.setContentIntent(pendingIntent2) //   PendingIntent 
.setNumber(1) //  TextView        ,      ,    。  number             ,          (  ID),         。 
.getNotification(); //     build()  API level 
// 16      , API11     getNotificatin()    
notify2.flags |= Notification.FLAG_AUTO_CANCEL; 
manager.notify(NOTIFICATION_FLAG, notify2); 
break; 
//      API16      
case R.id.btn3: 
PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0, 
new Intent(this, MainActivity.class), 0); 
//   Notification.Builder     ,  API Level 
// API16      
Notification notify3 = new Notification.Builder(this) 
.setSmallIcon(R.drawable.message) 
.setTicker("TickerText:" + "      ,     !") 
.setContentTitle("Notification Title") 
.setContentText("This is the notification message") 
.setContentIntent(pendingIntent3).setNumber(1).build(); //     build()  API 
// level16      ,API11    getNotificatin()    
notify3.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL           ,      。 
manager.notify(NOTIFICATION_FLAG, notify3);//   4:            。  id  ,  click, status         
break; 
//       
case R.id.btn4: 
// Notification myNotify = new Notification(R.drawable.message, 
// "     :       ,     !", System.currentTimeMillis()); 
Notification myNotify = new Notification(); 
myNotify.icon = R.drawable.message; 
myNotify.tickerText = "TickerText:      ,     !"; 
myNotify.when = System.currentTimeMillis(); 
myNotify.flags = Notification.FLAG_NO_CLEAR;//         
RemoteViews rv = new RemoteViews(getPackageName(), 
R.layout.my_notification); 
rv.setTextViewText(R.id.text_content, "hello wrold!"); 
myNotify.contentView = rv; 
Intent intent = new Intent(Intent.ACTION_MAIN); 
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, 
intent, 1); 
myNotify.contentIntent = contentIntent; 
manager.notify(NOTIFICATION_FLAG, myNotify); 
break; 
case R.id.btn5: 
//   id NOTIFICATION_FLAG    
manager.cancel(NOTIFICATION_FLAG); 
//         
// manager.cancelAll(); 
break; 
default: 
break; 
} 
} 
}
홈 레이아웃 파일 보기:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
tools:context=".MainActivity" > 
<Button 
android:id="@+id/btn1" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:onClick="notificationMethod" 
android:text="    (    ,    )" /> 
<Button 
android:id="@+id/btn2" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:onClick="notificationMethod" 
android:text="    (API11    )" /> 
<Button 
android:id="@+id/btn3" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:onClick="notificationMethod" 
android:text="    (API16    )" /> 
<Button 
android:id="@+id/btn4" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:onClick="notificationMethod" 
android:text="     " /> 
<Button 
android:id="@+id/btn5" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:onClick="notificationMethod" 
android:text="    " /> 
</LinearLayout>
또 하 나 는 사용자 정의 알림 의 레이아웃 파일 mynotification.xml,코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:background="#ffffff" 
android:orientation="vertical" > 
<TextView 
android:id="@+id/text_content" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:textSize="20sp" /> 
</LinearLayout>
어떻게 하면 자신의 Notification 을 Android QQ 처럼'실행 중인'항목 아래 에 나타 날 수 있 습 니까?
사실 간단 합 니 다.Notification.flags=Notification.FLAG 만 설정 하면 됩 니 다.ONGOING_EVENT;됐 습 니 다.
"실행 중인"항목 아래 에 있 는 Notification 의 레이아웃 을 어떻게 바 꿉 니까?
RemoteViews 를 만 들 고 Notification.contentView 에 부여 하고 PendingIntent 를 Notification.contentIntent 에 부여 하면 됩 니 다.예 를 들 어:

PendingIntent contentIntent = PendingIntent.getActivity(
arg0.getContext(), 
R.string.app_name,
i, 
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews rv = new RemoteViews(Main.this.getPackageName(), R.layout.notification_view);
rv.setImageViewResource(R.id.image, R.drawable.chat);
rv.setTextViewText(R.id.text, "Hello,there,I'm john.");
n.contentView = rv;
n.contentIntent = contentIntent;
nm.notify(R.string.app_name, n);
contentView 를 사용 했다 면 Notification.setLatest EventInfo 를 사용 하지 마 십시오.setLatest EventInfo 가 Notification.contentView 에 부 여 된 코드 가 있 으 면 contentView 의 효 과 는 덮어 쓰 고 setLatest EventInfo 의 효 과 를 보 여 줍 니 다.setLatest EventInfo 가 Notification.contentView 코드 앞 에 있 으 면 Notification.contentView 의 효과 가 표 시 됩 니 다.즉,setLatest EventInfo 나 contentView 의 사용자 정의 효 과 를 원 하 더 라 도 항상 하나의 설정 코드 만 있 도록 하 십시오.마지막 으로 연결 되 었 을 때,이전 설정 contentView 나 setLatest EventInfo 의 코드 는 전혀 필요 하지 않 았 습 니 다.

좋은 웹페이지 즐겨찾기