如何在Android Oreo或更高版本的设备中着色通知?

时间:2017-12-30 05:36:48

标签: android

我只是想支持我的应用程序到Android O.我只是喜欢彩色通知的概念,类似于此。

我想实现如下图像:

enter image description here

以下是我目前正在做的事情:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button bt;
String channelID="channelID";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt=findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View view) {
                Notification notification=new Notification.Builder(MainActivity.this)
                        .setContentTitle("This is an title")
                        .setContentText("This is an long text")
                        .setChannelId(channelID)
                        .setOngoing(true)
                        .setColor(getResources().getColor(R.color.blue))
                        .setColorized(true)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .build();
                NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                NotificationChannel channel= null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    channel = new NotificationChannel(channelID,"Popup notification channel", NotificationManager.IMPORTANCE_HIGH);
                    channel.setLightColor(getResources().getColor(R.color.blue));
                    channel.setShowBadge(true);
                    manager.createNotificationChannel(channel);
                }
                manager.notify(0,notification);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:1)

您必须使用NotificationCompat.Builder,然后设置MediaStyle。

NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
    .setStyle(new NotificationCompat.MediaStyle()
              // Attach our MediaSession token
            .setMediaSession(mediaSession.getSessionToken())
            // Show our playback controls in the compat view
           .setShowActionsInCompactView(0, 1, 2))

现在运行并检查android O

答案 1 :(得分:0)

enter image description here

如果您使用的是android x

print(self.obj_a, self.obj_b) # <pC_Obj_A object at 0x029FF610> <pC_Obj_B object at 0x029FF620>
print(f'{<int>self.obj_a._c_self:x} {<int>self.obj_b._c_self:x}') # 2134b9c 2134c08