Cuando estaba haciendo la pregunta hace unos días, descubrí que la Notificación no estaba bien dominada y era despreciada, así que inventé la Notificación un poco estos días y escribí una demostración, que básicamente cubre todos los puntos de conocimiento. No hables tonterías, simplemente codifica directamente, después de todo. El código es el lenguaje más hermoso.
//Interfaz principal
package wu.skateboard.com.notificationdemo;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button notification_one;
private Button notification_two;
private Button notification_three;
private Button cancel;
private Button update;
private Button progress;
private Button headUp;
private Button lockScreenNotification;
private Button mediaStyle;
private Button customNotification;
private BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initBroadReceiver();
registerBroadReceiver();
}
private void initView()
{
notification_one= (Button) findViewById(R.id.notify_one);
notification_one.setOnClickListener(this);
notification_two= (Button) findViewById(R.id.notify_two);
notification_two.setOnClickListener(this);
notification_three=(Button)findViewById(R.id.notify_three);
notification_three.setOnClickListener(this);
cancel= (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(this);
update= (Button) findViewById(R.id.update);
update.setOnClickListener(this);
progress= (Button) findViewById(R.id.show_progress);
progress.setOnClickListener(this);
headUp= (Button) findViewById(R.id.headup);
headUp.setOnClickListener(this);
lockScreenNotification= (Button) findViewById(R.id.lockscreen);
lockScreenNotification.setOnClickListener(this);
mediaStyle= (Button) findViewById(R.id.meidastyle);
mediaStyle.setOnClickListener(this);
customNotification= (Button) findViewById(R.id.custom);
customNotification.setOnClickListener(this);
}
private void initBroadReceiver()
{
receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(("Previous").equals(intent.getAction()))
{
Toast.makeText(MainActivity.this, "Previous", Toast.LENGTH_SHORT).show();
}
else if(("Pause").equals(intent.getAction()))
{
Toast.makeText(MainActivity.this, "Pause", Toast.LENGTH_SHORT).show();
}
else if(("Next").equals(intent.getAction()))
{
Toast.makeText(MainActivity.this, "Next", Toast.LENGTH_SHORT).show();
}
}
};
}
private void registerBroadReceiver()
{
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("Previous");
intentFilter.addAction("Pause");
intentFilter.addAction("Next");
registerReceiver(receiver,intentFilter);
}
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.notify_one:
notifyNotification(1);
break;
case R.id.notify_two:
notifyNotification(2);
break;
case R.id.notify_three:
notifyExpandNotificaion(3);
break;
case R.id.cancel:
cancelNotificaton();
break;
case R.id.update:
updateNotification(1,"UpdateTitle","UpdateText");
break;
case R.id.show_progress:
startShowProgressNotification();
break;
case R.id.headup:
showHeadUpNotification("HeatUpTitle","HeadUpContent");
break;
case R.id.lockscreen:
showNotificationInLockScreen(NotificationCompat.VISIBILITY_PUBLIC,"LockScreenNotificationTitle","LockScreenNotificationContent");
break;
case R.id.meidastyle:
showMediaStyleNotification("MediaStyleTitle","MediaStyleContent");
break;
case R.id.custom:
showCustomNotification();
break;
}
}
private void notifyExpandNotificaion(int id)
{
NotificationManagerCompat notificationManager= NotificationManagerCompat.from(this);
notificationManager.notify(id,createExpandNotification(new String("Title"+id),new String("Content"+id)));
}
private Notification createExpandNotification(String title,String text)
{
NotificationCompat.InboxStyle style=new android.support.v4.app.NotificationCompat.InboxStyle();
style.setBigContentTitle("ExpandLayoutNotification");
String[] events=new String[]{
"detail1","detail2","detail3","detail4","detail5"};
for(String line:events) {
style.addLine(line);
}
NotificationCompat.Builder notificationBuilder=createNormalNotificationBuilder(title,text);
notificationBuilder.setWhen(System.currentTimeMillis()+1000000)//这个是用来设置通知栏上通知显示的时间的,默认为系统时间,不是广播通知的时间
.setStyle(style);
return notificationBuilder.build();
}
private void notifyNotification(int id)
{
NotificationManagerCompat notificationManager= NotificationManagerCompat.from(this);
notificationManager.notify(id,createNotification(new String("Title"+id),new String("Content"+id)));
}
private Notification createNotification(String title,String text)
{
Intent intent=new Intent(this,NotificationContentActivity.class);
TaskStackBuilder taskStackBuilder=TaskStackBuilder.create(this);
taskStackBuilder.addParentStack(NotificationContentActivity.class);
taskStackBuilder.addNextIntent(intent);
PendingIntent notificationIntent=taskStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder=createNormalNotificationBuilder(title,text);
notificationBuilder.setContentIntent(notificationIntent);
return notificationBuilder.build();
}
private NotificationCompat.Builder createNormalNotificationBuilder(String title,String text)
{
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL);
return notificationBuilder;
}
private void cancelNotificaton()
{
NotificationManagerCompat notificationManager= NotificationManagerCompat.from(this);
notificationManager.cancelAll();
}
private void updateNotification(int id,String title,String text)
{
Notification notification=createNotification(title,text);
NotificationManagerCompat notificationManager= NotificationManagerCompat.from(this);
notificationManager.notify(id,notification);
}
private void startShowProgressNotification()
{
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<=100;i+=10) //每隔2秒进度条层加10
{
showProgrssInNotification(100,i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
showProgrssInNotification(0,0,false);//完成,取消进度条
}
});
thread.start();
}
private void showProgrssInNotification(int id,int max,int step,boolean indeterminate)
{
NotificationCompat.Builder notificationBuilder=createNormalNotificationBuilder("ProgressTitle","ProgressContent");
notificationBuilder.setProgress(max,step,indeterminate);
NotificationManagerCompat notificationManager=NotificationManagerCompat.from(this);
notificationManager.notify(id,notificationBuilder.build());
}
private void showProgrssInNotification(int max,int step,boolean indeterminate)
{
showProgrssInNotification(4,max,step,indeterminate);
}
private void showProgrssInNotification(int max,int step)
{
showProgrssInNotification(4,max,step,true);
}
private void showHeadUpNotification(String title,String text)
{
//想要notification以一个floatingwindow的方式展现出来,首先要是android5.0以上,其次要这个Notification有PRIORITY_HIGH和声音或者震动
NotificationCompat.Builder notificationBuilder=createNormalNotificationBuilder(title,text);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
NotificationManagerCompat notificationManager=NotificationManagerCompat.from(this);
notificationManager.notify(5,notificationBuilder.build());
}
private void showNotificationInLockScreen(int type,String title,String text)
{
//这里的这个Visibility指的是当锁屏是通知的内容你是否能看得见,此时指的还是下拉通知栏菜单后显示的通知,不要以为是直接显示在锁屏屏幕上的。。。
NotificationCompat.Builder notificationBuilder=createNormalNotificationBuilder(title,text);
notificationBuilder.setVisibility(type);
NotificationManagerCompat notificationManager=NotificationManagerCompat.from(this);
notificationManager.notify(6,notificationBuilder.build());
}
private void showMediaStyleNotification(String title,String text)
{
Intent previeousIntent=new Intent("Previous");
PendingIntent previousPendingIntent=PendingIntent.getBroadcast(this,1000,previeousIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent=new Intent("Pause");
PendingIntent pausePendingIntent=PendingIntent.getBroadcast(this,1001,pauseIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent=new Intent("Next");
PendingIntent nextPendingIntent=PendingIntent.getBroadcast(this,1002,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder=createNormalNotificationBuilder(title,text);
notificationBuilder.addAction(R.mipmap.ic_launcher,"Previous",previousPendingIntent).addAction(R.mipmap.ic_launcher,"Pause",pausePendingIntent).addAction(R.mipmap.ic_launcher,"Next",nextPendingIntent)
.setStyle(new NotificationCompat.MediaStyle().setShowActionsInCompactView(new int[]{
0,1,2}))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
NotificationManagerCompat notificationManager=NotificationManagerCompat.from(this);
notificationManager.notify(7,notificationBuilder.build());
}
private void showCustomNotification()
{
//RemoteView说白了就是在显示在另一个进程中的布局
RemoteViews customLayout=new RemoteViews(getPackageName(),R.layout.custom_layout);
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
notificationBuilder.setContent(customLayout).setSmallIcon(R.mipmap.ic_launcher);
NotificationManagerCompat notificationManager=NotificationManagerCompat.from(this);
notificationManager.notify(8,notificationBuilder.build());
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
//
Paquete NotificationContentActivity wu.skateboard.com.notificationdemo;
importar android.os.Bundle;
importar android.support.design.widget.FloatingActionButton;
importar android.support.design.widget.Snackbar;
importar android.support.v7.app.AppCompatActivity;
importar android.support.v7.widget.Toolbar;
importar android.view.View;
La clase pública NotificationContentActivity extiende AppCompatActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_notification_content);
toolbar= (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Title");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
// activity_main
<?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="match_parent"
android:orientation="vertical">
<Button
android:text="Notify1"
android:id="@+id/notify_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="Notify2"
android:id="@+id/notify_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="Notify_Expand"
android:id="@+id/notify_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="UpdateNotification"
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="CancelNotification"
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="ShowProgress"
android:id="@+id/show_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="HeadUp"
android:id="@+id/headup"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="LockScreenNotification"
android:id="@+id/lockscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="MediaStyle"
android:id="@+id/meidastyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="CustomNotification"
android:id="@+id/custom"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
// content_notification_content
<?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="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:background="?attr/colorPrimary"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"/>
<TextView
android:layout_gravity="center"
android:text="NotificationContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>