標籤:UI 發送 manager tor system contex priority alt source
1.基本用法
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="發送通知" android:onClick="info" />
MainActivity,按鈕事件
public void info(View view){ NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); Notification notification= new NotificationCompat.Builder(this) //通知標題 .setContentTitle("通知") //通知本文 .setContentText("美國又欺負敘利亞了") //通知時間? .setWhen(System.currentTimeMillis()) //小表徵圖 .setSmallIcon(R.mipmap.ic_launcher) //大表徵圖 .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)) .build(); //推播通知,參數1:要保證每個通知的id不同,參數2:Notification對象 manager.notify(1,notification); }
結果
//通知的重要程度,max立即顯示...測試後不管用,,.setPriority(NotificationCompat.PRIORITY_MAX)
點擊通知
建立一個新的活動和布局,Main2Activity
import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.support.v4.app.NotificationCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void info(View view){ Intent intent=new Intent(this,Main2Activity.class); //點擊通知後開啟指定介面,參數1:上下文,參數2:通常固定是0,參數3:意圖,參數4:行為,通常傳0 PendingIntent pi=PendingIntent.getActivity(this,0,intent,0); NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); Notification notification= new NotificationCompat.Builder(this) //通知標題 .setContentTitle("通知") //通知本文 .setContentText("美國又欺負敘利亞了") //通知時間? .setWhen(System.currentTimeMillis()) //小表徵圖 .setSmallIcon(R.mipmap.ic_launcher) //大表徵圖 .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)) //接收一個PendingIntent對象 .setContentIntent(pi) .build(); //推播通知,參數1:要保證每個通知的id不同,參數2:Notification對象 manager.notify(1,notification); }}
()android 通知