android的Notification折叠

android 的Notification 看起来简单,但是api老是改。用的时候确实很麻烦。这里写一个折叠的Demo。
布局文件:activity_main


<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="elfstton.cheerchip.com.notifitydemo.MainActivity">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Collapsed"
        android:onClick="collapsedNotify" />
RelativeLayout>

点击事件,注意api的判断。

  public void collapsedNotify(View view) {
        Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0);
        Notification.Builder builder=new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(pendingIntent);
        builder.setAutoCancel(true);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));

        //通过RemoteViews创建自定义视图
        RemoteViews  remoteViews=new RemoteViews(getPackageName(),R.layout.mynotification);
        remoteViews.setTextViewText(R.id.textView,"可折叠式");

        Notification notification= null;
        //大于16
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification = builder.build();
        }else{
            //小于16
            notification=builder.getNotification();
        }
        notification.contentView=remoteViews;
        //通过RemoteViews创建自定义的Notification视图
        RemoteViews expandedView=new RemoteViews(getPackageName(),R.layout.notification_expanded);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification.bigContentView=expandedView;
        }

        NotificationManager nm= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(0,notification);

    }

源码下载: https://github.com/AndriodWorld/androidnotification

你可能感兴趣的:(Android,android)