实现步骤
代码实现
创建MainActivity和DetailActivity(点击通知后要跳转的Activity),两个Activity的布局文件就是添加一张全屏的背景图,老规矩,不粘贴。
MainActivity的代码:
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
final int NOTIFYID = 0x123;//通知ID
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建并发送通知
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);//获取通知管理器
Notification.Builder notification =
new Notification.Builder(MainActivity.this);//创建一个通知对象
notification.setAutoCancel(true);//设置通知打开后,自动消失
notification.setSmallIcon(R.drawable.packet);//设置通知图标
notification.setContentTitle("今晚多人运动约吗!!!!!");//设置通知内容标题
notification.setContentText("点击查看玉照!");//设置通知内容
notification.setWhen(System.currentTimeMillis());//设置发送时间
notification.setDefaults(Notification.DEFAULT_SOUND
|Notification.DEFAULT_VIBRATE);//设置声音和震动
Intent intent = new Intent(MainActivity.this,DetailActivty.class);
PendingIntent pi = PendingIntent.getActivity(
MainActivity.this,0,intent,0);
notification.setContentIntent(pi);//设置通知栏点击跳转
notificationManager.notify(NOTIFYID,notification.build());
}
}
这样就实现了在状态栏显示通知的效果: