Android 设置通知通道,当前不工作

Android 设置通知通道,当前不工作,android,notifications,Android,Notifications,我使用alarmmanager创建了一个用于测试通知的应用程序。它在不使用通知通道的设备上工作 我正在尝试为android 8.0添加一个频道,但我似乎不明白 有人能帮我整理一下,这样我就可以在安卓8.0设备上收到通知了吗+ 活动主 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCre

我使用alarmmanager创建了一个用于测试通知的应用程序。它在不使用通知通道的设备上工作

我正在尝试为android 8.0添加一个频道,但我似乎不明白

有人能帮我整理一下,这样我就可以在安卓8.0设备上收到通知了吗+

活动主

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final Context context = this;

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setReminder(context,ReminderReceiver.class,10);
            Snackbar.make(view, "Hope", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

public void setReminder(Context context, Class<?> cls, int sec)
{
    Intent intent = new Intent(context, cls);
    intent.putExtra("TIME",sec);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, sec, intent,
            PendingIntent.FLAG_ONE_SHOT);/* Find more about flags: https://developer.android.com/reference/android/app/PendingIntent */

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (sec * 1000), pendingIntent );//Add time in milliseconds. if you want to minute or hour mutiply by 60.. For ex: You want to trigger 5 Min then here you need to change 5 * 60 * 1000


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}
public类MainActivity扩展了AppCompatActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
最终上下文=此;
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
setReminder(上下文,ReminderReceiver.class,10);
Snackbar.make(视图“希望”,Snackbar.LENGTH\u LONG)
.setAction(“Action”,null).show();
}
});
}
公共无效设置提醒(上下文、类cls、整数秒)
{
意向=新意向(上下文,cls);
意图。额外(“时间”,秒);
PendingEvent PendingEvent=PendingEvent.getBroadcast(上下文、秒、意图、,
PendingEvent.FLAG_ONE_SHOT);/*查找有关flags的更多信息:https://developer.android.com/reference/android/app/PendingIntent */
AlarmManager am=(AlarmManager)context.getSystemService(context.ALARM\u服务);
am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+(sec*1000),PendingEvent);//以毫秒为单位添加时间。如果您希望以分钟或小时为单位乘以60..例如:您希望触发5分钟,则需要在此处更改5*60*1000
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
}
提醒

public class ReminderReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    int Request_Code = intent.getExtras().getInt("TIME",0);
    showNotification(context, MainActivity.class,
            "New Notification Alert..!", "scheduled for " + Request_Code + " seconds",Request_Code);
}

public void showNotification(Context context, Class<?> cls, String title, String content,int RequestCode)
{
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Intent notificationIntent = new Intent(context, cls);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(cls);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(
            RequestCode,PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"Default");
    Notification notification = builder.setContentTitle(title)
            .setContentText(content).setAutoCancel(true)
            .setSound(alarmSound).setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentIntent(pendingIntent).build();

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String channelId = "id1";
        CharSequence channelName = "id1";
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert notificationManager != null;
        notificationManager.createNotificationChannel(notificationChannel);
    }

    //assert notificationManager != null;
    assert notificationManager != null;
    notificationManager.notify(RequestCode,notification);
}

}
公共类提醒接收程序扩展广播接收程序{
@凌驾
公共void onReceive(上下文、意图){
int Request_Code=intent.getExtras().getInt(“时间”,0);
showNotification(上下文,MainActivity.class,
“新通知警报!”,“预定时间”+请求代码+“秒”,请求代码);
}
公共void showNotification(上下文上下文、类cls、字符串标题、字符串内容、int请求代码)
{
Uri alarmSound=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
意向通知意向=新意向(上下文,cls);
notificationIntent.setFlags(Intent.FLAG\u ACTIVITY\u CLEAR\u TOP);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(上下文);
stackBuilder.addParentStack(cls);
stackBuilder.addNextIntent(通知意图);
PendingEvent PendingEvent=stackBuilder.GetPendingEvent(
请求代码,PendingEvent.FLAG(一个镜头);
NotificationCompat.Builder=新建NotificationCompat.Builder(上下文,“默认”);
通知通知=builder.setContentTitle(标题)
.setContentText(内容).setAutoCancel(真)
.setSound(alarmSound).setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(pendingIntent).build();
NotificationManager NotificationManager=(NotificationManager)
getSystemService(context.NOTIFICATION\u服务);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.O){
字符串channelId=“id1”;
CharSequence channelName=“id1”;
int重要性=NotificationManager.importance\u LOW;
NotificationChannel NotificationChannel=新的NotificationChannel(通道ID、通道名称、重要性);
notificationChannel.enableLights(真);
notificationChannel.setLightColor(颜色为红色);
通知通道。启用振动(真);
notificationChannel.setVibrationPattern(新的长[]{100200300400500400300200400});
assert notificationManager!=null;
notificationManager.createNotificationChannel(notificationChannel);
}
//assert notificationManager!=null;
assert notificationManager!=null;
notificationManager.notify(请求代码,通知);
}
}
显示

<?xml version="1.0" encoding="utf-8"?>


您需要在通知生成器中添加setChannel(notificationChannel),如下所示:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"Default");
Notification notification = builder.setContentTitle(title)
        .setContentText(content).setAutoCancel(true)
        .setSound(alarmSound).setSmallIcon(R.mipmap.ic_launcher_round)
        .setContentIntent(pendingIntent)
        .setChannel(channelId).build();
在创建通知通道后添加此代码

NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"Default");
Notification notification = builder.setContentTitle(title)
        .setContentText(content).setAutoCancel(true)
        .setSound(alarmSound).setSmallIcon(R.mipmap.ic_launcher_round)
        .setContentIntent(pendingIntent)
        .setChannel(channelId).build();