android:Notification實現狀態欄的通知
阿新 • • 發佈:2017-08-07
generate file widget flash track click 短消息 img example
上面代碼中設置的指示燈和震動,因為程序中要訪問系統的指示燈和振動器 所以要在AndroidManifest.xml中聲明使用權限
希望對你有所幫助。
在使用手機時,當有未接來電或者新短消息時,手機會給出響應的提示信息,這些提示信息一般會顯示到手機屏幕的狀態欄上。
Android也提供了用於處理這些信息的類,它們是Notification和NotificationManager。
當中,Notification代表的是具有全局效果的通知,而NotificationManager則是用於發送Notification通知的系統服務。
使用Notification和NotificationManager類發送和顯示通知也比較簡單,大致能夠分為下面四個步驟
(1)調用getSystemService() 方法獲取系統的NotificationManager服務
(2)創建一個Notification對象,並為其設置各種屬性
(3)為Notification對象設置事件信息
(4)通過NotificationManager類的notify()方法發送Notification通知
以下通過一個實例說明和使用Notification在狀態欄上顯示通知
國際慣例
執行結果:
布局文件就不發了 線性垂直布局 兩個button
MainActivity.class
package com.example.notification; import android.os.Bundle; import android.app.Activity; import android.app.Notification; import android.app.Notification.Builder; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener{ private NotificationManager manager; private Button button1; private Button button2; private int Notification_ID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); button1=(Button) findViewById(R.id.button1); button2=(Button) findViewById(R.id.button2); button1.setOnClickListener(this); button2.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.button1:{ showNotification(); break; } case R.id.button2:{ manager.cancel(Notification_ID); break; } } } private void showNotification() { // TODO Auto-generated method stub Notification.Builder builder=new Builder(this); builder.setSmallIcon(R.drawable.ic_launcher);//設置圖標 builder.setTicker("通知來啦");//手機狀態欄的提示 builder.setContentTitle("我是通知標題");//設置標題 builder.setContentText("我是通知內容");//設置通知內容 builder.setWhen(System.currentTimeMillis());//設置通知時間 Intent intent=new Intent(this,MainActivity.class); PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, 0); builder.setContentIntent(pendingIntent);//點擊後的意圖 builder.setDefaults(Notification.DEFAULT_LIGHTS);//設置指示燈 builder.setDefaults(Notification.DEFAULT_SOUND);//設置提示聲音 builder.setDefaults(Notification.DEFAULT_VIBRATE);//設置震動 Notification notification=builder.build();//4.1以上。下面要用getNotification() manager.notify(Notification_ID, notification); } }
上面代碼中設置的指示燈和震動,因為程序中要訪問系統的指示燈和振動器 所以要在AndroidManifest.xml中聲明使用權限
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.FLASHLIGHT" />
希望對你有所幫助。
渣渣學習中....
android:Notification實現狀態欄的通知