我正在尝试学习如何在Android上触发通知。该应用程序可以在虚拟设备上运行,但是当我在实际的三星Galaxy S7(Android版本:8.1.0)上尝试使用该应用程序时,每当我按下带有“系统UI已停止”消息的通知按钮时,它都会冻结手机。我的手机无限期无响应,需要重新启动。
public class MainActivity extends AppCompatActivity {
String CHANNEL1_ID = "Channel 1 id";
String CHANNEL1_NAME = "Channel 1";
String channel1_description = "Channel 1 description";
String textTitle = "This is a title.";
String textContent = "Some content.";
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final Context context = this;
createNotificationChannel();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL1_ID);
builder.setSmallIcon(R.drawable.notification_image);
builder.setContentTitle(textTitle);
builder.setContentText(textContent);
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(count, builder.build());
count++;
Log.d("TAG " + count, "onClick: ");
}
});
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = CHANNEL1_NAME;
String description = channel1_description;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL1_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
我要做的就是将以下内容添加到我的模块级别build.gradle中实现“ com.android.support:support-compat:29.0.0”因为我的目标SDK版本是29。