android 通知图标
我的应用程序需要一个带有声音和图标的简单Android通知。 所以这是我用来实现这一目标的代码。 我知道Android中还有许多其他类型的通知,但是这次,我只想向您展示一个非常简单的代码,也可以解决您的问题!
我可能会创建一系列有关Android通知的博客文章,并使其成为我们所有人的备忘单。 无论如何,这是当今代码输出的一些屏幕截图:
![]() |
当您运行此代码时。 |
![]() |
当您点击“显示通知”按钮时, 通知栏将显示忍者图标 你会听到声音 (确保您没有处于静音模式)。 |
![]() |
向下滑动通知栏时。 |
隐藏通知
如何隐藏通知? 有两种方法:
1.首先,您可以单击“取消通知”按钮。
2.或者,第二次向左或向右滑动通知(在第三张图片中滑动通知)。
这些方式是通过编程方式设置的,因此请阅读下面的代码(带有注释)。
让我们编码!
这是我们很棒的代码:MainActivity.java
package com.example.androidnotificationbar;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// listener handler
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnShowNotification:
showNotification();
break;
case R.id.btnCancelNotification:
cancelNotification(0);
break;
}
}
};
// we will set the listeners
findViewById(R.id.btnShowNotification).setOnClickListener(handler);
findViewById(R.id.btnCancelNotification).setOnClickListener(handler);
}
public void showNotification(){
// define sound URI, the sound to be played when there's a notification
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// intent triggered, you can add other intent for other actions
Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
// this is it, we'll build the notification!
// in the addAction method, if you don't want any icon, just set the first param to 0
Notification mNotification = new Notification.Builder(this)
.setContentTitle("New Post!")
.setContentText("Here's an awesome update for you!")
.setSmallIcon(R.drawable.ninja)
.setContentIntent(pIntent)
.setSound(soundUri)
.addAction(R.drawable.ninja, "View", pIntent)
.addAction(0, "Remind", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// If you want to hide the notification after it was selected, do the code below
// myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
public void cancelNotification(int notificationId){
if (Context.NOTIFICATION_SERVICE!=null) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.cancel(notificationId);
}
}
}
我还将忍者图标放在我们的可绘制文件夹中,这就是我们图标的来源。
请分享您接下来想要的Android通知示例!
翻译自: https://www.javacodegeeks.com/2013/08/android-notification-with-sound-and-icon-tutorial.html
android 通知图标