你的位置:首页 > 操作系统

[操作系统]Android 主页面顶部栏的通知Notification 。


 1 package com.lixu.tongzhi;
2 3 import android.app.Activity; 4 import android.app.Notification; 5 import android.app.NotificationManager; 6 import android.os.Bundle; 7 import android.support.v4.app.NotificationCompat; 8 import android.view.View; 9 import android.view.View.OnClickListener;10 import android.widget.Button;11 import android.widget.Toast;12 13 public class MainActivity extends Activity {14 15 private static final int ID = 1987;16 17 @Override18 protected void onCreate(Bundle savedInstanceState) {19 super.onCreate(savedInstanceState);20 setContentView(R.layout.activity_main);21 22 Button btn1 = (Button) findViewById(R.id.fasong);23 Button btn2 = (Button) findViewById(R.id.qingchu);24 25 btn1.setOnClickListener(new OnClickListener() {26 27 @Override28 public void onClick(View v) {29 send();30 31 Toast.makeText(getApplicationContext(), "发送通知成功!", 0).show();32 33 }34 });35 36 btn2.setOnClickListener(new OnClickListener() {37 38 @Override39 public void onClick(View v) {40 41 delete();42 43 Toast.makeText(getApplicationContext(), "清除通知成功!", 0).show();44 45 }46 });47 48 }49 50 private void send() {51 // 获取通知管理器52 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);53 54 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);55 // 设置通知图片56 mBuilder.setSmallIcon(R.drawable.sdfdf);57 // 设置标题58 mBuilder.setContentTitle("小超人来了!");59 // 设置通知内容60 mBuilder.setContentText("我是小超人,主人有什么事情要吩咐。");61 62 Notification notification = mBuilder.build();63 // 设置通知声音或者震动。64 notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;65 // 通知时间66 notification.when = System.currentTimeMillis();67 // 通过特定id来发送这个通知68 manager.notify(ID, notification);69 70 }71 72 private void delete() {73 // 获取通知管理器74 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);75 manager.cancel(ID);76 77 }78 79 }

常用的程序通知,显示到主页面的顶部栏。

 1 <RelativeLayout ="http://schemas.android.com/apk/res/android" 2   ="http://schemas.android.com/tools" 3   android:layout_width="match_parent" 4   android:layout_height="match_parent" > 5  6   <Button 7     android:id="@+id/fasong" 8     android:layout_width="wrap_content" 9     android:layout_height="wrap_content"10     android:layout_alignLeft="@+id/qingchu"11     android:layout_alignParentTop="true"12     android:layout_marginTop="56dp"13     android:text="发送通知" />14 15   <Button16     android:id="@+id/qingchu"17     android:layout_width="wrap_content"18     android:layout_height="wrap_content"19     android:layout_below="@+id/fasong"20     android:layout_centerHorizontal="true"21     android:layout_marginTop="88dp"22     android:text="清除通知" />23 24 </RelativeLayout>

运行效果图: