【发布时间】:2018-08-18 06:45:38
【问题描述】:
我看到了一个在 Android 8 中创建通知的 youtube 教程,我唯一不明白的是如何使通知发出声音和振动。
这是教程中的代码,我在频道中添加了该代码。其次,channel.enable振动,.setvibrate和setSound。
频道的帮助类:
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
channel1.setSound(null, null);
channel1.setLockscreenVisibility(NotificationCompat.PRIORITY_HIGH);
channel1.enableVibration(true);
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
channel2.setSound(null, null);
channel2.setLockscreenVisibility(NotificationCompat.PRIORITY_HIGH);
channel2.enableVibration(true);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
主要活动:
public class MainActivity extends AppCompatActivity {
private NotificationManagerCompat notificationManager;
private EditText editTextTitle;
private EditText editTextMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = NotificationManagerCompat.from(this);
editTextTitle = findViewById(R.id.edit_text_title);
editTextMessage = findViewById(R.id.edit_text_message);
}
public void sendOnChannel1(View v) {
String title = editTextTitle.getText().toString();
String message = editTextMessage.getText().toString();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVibrate(new long[] {2000})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.build();
notificationManager.notify(1, notification);
}
public void sendOnChannel2(View v) {
String title = editTextTitle.getText().toString();
String message = editTextMessage.getText().toString();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_2_ID)
.setSmallIcon(R.drawable.ic_two)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[] {2000})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.build();
notificationManager.notify(2, notification);
}
}
在清单中,我添加了
<uses-permission android:name="android.permission.VIBRATE"/>
我可以在按钮单击时创建通知,但没有声音和振动。 有人可以向我解释一下这在 Android 8 中是如何工作的
【问题讨论】:
标签: android android-notifications android-8.0-oreo android-8.1-oreo