直接上代码了,代码里都有注释
- MainActivity.class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.send_notice:
Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// manager.cancel(1); 效果跟setAutoCancel(true)相同
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("title")
.setContentText("text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentIntent(pendingIntent)
.setAutoCancel(true) //点击图标后通知图标自动消失
.setVibrate(new long[]{0,1000,1000,1000})//设置收到消息后震动,当前表示收到后立刻震动一秒,然后静止一秒,再震动一秒 要在配置文件中配置
.setLights(Color.GREEN,1000,1000)//设置前置LED灯亮的颜色,时常,和闪烁间隔
// .setDefaults(NotificationCompat.DEFAULT_ALL) 通知的默认效果,他会根据当前手机的环境来决定播放什么铃声以及如何震动
.setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的重要程度
.build();
manager.notify(1,notification);
break;
default:
break;
}
}
});
}
- xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.sky.notificationtest.MainActivity">
<Button
android:id="@+id/send_notice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
还有一些杂七杂八的设置我没有贴出来,有需要的可以进我的github里面下载
github地址:https://github.com/skysunlei/NotificationTest