- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
几天来,我一直在努力让本地通知显示在 Android 设备上。通知根本不显示,我收到开发人员警告:
package Failed to post notification on channel "channel_id_here" error.
我浏览了许多教程和 StackOverflow 帖子,看看是否遗漏了什么,但我就是找不到。如果我在这里做错了什么或者我是否遗漏了什么,有人可以看看吗?如果能帮我解决这个问题,我将不胜感激。
我的应用程序以 API 29 为目标,我使用了这个 git 中的代码
这是我的应用程序中的相关代码:
AppCompatPreferenceActivity.java
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(@Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
NotificationPublisher.java
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION = "notification";
@Override
public void onReceive(Context ctx, Intent intent) {
NotificationManager notificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
// The notification may come from the received intent (see SettingsActivity for how to build
// it and add it to the intent). If not then we'll build a notification here.
Notification notification;
if (intent.hasExtra(NOTIFICATION)) {
notification = intent.getParcelableExtra(NOTIFICATION);
} else {
notification = buildNotification(ctx);
}
// notificationId is a unique int for each notification.
// TODO Is the current time good enough?
int notificationId = (int) System.currentTimeMillis();
notificationManager.notify(notificationId, notification);
}
private Notification buildNotification(Context ctx) {
Intent intent = new Intent(ctx, com.app.myapp.activity.MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle("Hello I'm a notification!")
.setContentText("Well look at that, it's content")
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
return builder.build();
}
}
NotificationSchedulerApplication.java
public class NotificationSchedulerApplication extends Application {
public static final String CHANNEL_ID = "1998882";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
SettingsActivity.java
public class SettingsActivity extends AppCompatPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String ENABLE_NOTIFICATIONS_PREF_KEY = "notifications_enable";
private static final String NOTIFICATION_TIME_PREF_KEY = "notifications_time";
// This request code is used for all PendingIntents so that PendingIntents previously submitted
// to the AlarmManager can be looked up for cancellation or modification.
private static final int REQUEST_CODE = 0;
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(value.toString());
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof TimePreference) {
TimePreference timePreference = (TimePreference) preference;
preference.setSummary(timePreference.valueToSummary((int) value));
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(value.toString());
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's current value.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(
preference.getContext());
Object value;
if (preference instanceof TimePreference) {
value = sharedPrefs.getInt(preference.getKey(), 0);
} else {
value = sharedPrefs.getString(preference.getKey(), "");
}
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, value);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
// Listen for changes to any preferences.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
// We only want to take action if these particular preferences change.
if (!s.equals(ENABLE_NOTIFICATIONS_PREF_KEY) && !s.equals(NOTIFICATION_TIME_PREF_KEY)) {
return;
}
// If the preference was changed to false then we should cancel any pending notifications.
if (s.equals(ENABLE_NOTIFICATIONS_PREF_KEY) && !sharedPreferences.getBoolean(s, false)) {
cancelIntents();
return;
}
// Get the time at which to schedule notifications.
Calendar startTime = TimePreference.valueToCalendar(
sharedPreferences.getInt(NOTIFICATION_TIME_PREF_KEY, 0));
// If the time has already passed today, start notifications tomorrow.
Calendar now = Calendar.getInstance();
if (now.after(startTime)) {
startTime.add(Calendar.DATE, 1);
}
// Build a notification, add it to the intent we'll schedule, and schedule it.
// Notification notification = buildNotification();
// scheduleNotification(notification, startTime);
// Schedule an intent, and build and publish the notification in the future whenever
// the intent is received.
scheduleNotification(startTime);
}
private PendingIntent getNotificationPublisherIntent(Notification notification) {
Intent intent = new Intent(this, NotificationPublisher.class);
if (notification != null) {
intent.putExtra(NotificationPublisher.NOTIFICATION, notification);
}
return PendingIntent.getBroadcast(
this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private Notification buildNotification() {
Intent intent = new Intent(this, com.app.myapp.activity.MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle("Hello I'm a notification!")
.setContentText("Well look at that, it's content 111")
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
return builder.build();
}
private void scheduleNotification(Notification notification, Calendar startTime) {
scheduleIntent(getNotificationPublisherIntent(notification), startTime);
}
private void scheduleNotification(Calendar startTime) {
scheduleIntent(getNotificationPublisherIntent(null), startTime);
}
private void scheduleIntent(PendingIntent intent, Calendar startTime) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, intent);
}
private void cancelIntents() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(getNotificationPublisherIntent(null));
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {@inheritDoc}
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
// Bind the summary of the TimePreference to its value. When the value changes, the
// summary is updated to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_time"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
时间偏好.java
public class TimePreference extends DialogPreference {
// This is the same as the default value set in the XML. Keep them in sync.
private static final int DEFAULT_TIME = 7 * 60; // 0700
// The currently chosen time stored as the number of minutes after midnight.
private int time;
private TimePicker picker;
public TimePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public TimePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimePreference(Context context) {
super(context);
}
/**
* valueToSummary takes the raw value of the preference and converts it into a human-readable
* string fit for use in e.g. the preference's summary.
*
* @param value The raw value of the preference.
* @return The time formatted according to the current settings (locale, 12/24 hour clock)
*/
public String valueToSummary(int value) {
return DateFormat.getTimeFormat(getContext()).format(valueToCalendar(value).getTime());
}
public static Calendar valueToCalendar(int value) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, getHours(value));
calendar.set(Calendar.MINUTE, getMinutes(value));
calendar.set(Calendar.SECOND, 0);
return calendar;
}
private void setTime(int minAfterMidnight) {
time = minAfterMidnight;
persistInt(time);
notifyChanged();
}
private static int getHours(int minAfterMidnight) {
return minAfterMidnight / 60;
}
private static int getMinutes(int minAfterMidnight) {
return minAfterMidnight % 60;
}
@Override
protected View onCreateDialogView() {
picker = new TimePicker(getContext());
return picker;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
picker.setIs24HourView(DateFormat.is24HourFormat(getContext()));
if (Build.VERSION.SDK_INT >= 23) {
picker.setHour(getHours(time));
picker.setMinute(getMinutes(time));
} else {
picker.setCurrentHour(getHours(time));
picker.setCurrentMinute(getMinutes(time));
}
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
int hours, minutes;
if (Build.VERSION.SDK_INT >= 23) {
hours = picker.getHour();
minutes = picker.getMinute();
} else {
hours = picker.getCurrentHour();
minutes = picker.getCurrentMinute();
}
int newTime = hours * 60 + minutes;
if (callChangeListener(newTime)) {
setTime(newTime);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInt(index, DEFAULT_TIME);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
super.onSetInitialValue(restorePersistedValue, defaultValue);
setTime(restorePersistedValue ? getPersistedInt(time) : (int) defaultValue);
}
}
我的 AndroidManifest.xml 中的接收器:
<receiver android:name=".activity.NotificationPublisher" />
我可以在我的应用程序中设置时间,并为设备上的应用程序启用通知。它们根本不显示。
注意:我正在使用 Android API 29 进行开发。
最佳答案
在示例应用中,在 NotificationSchedulerApplication 中:
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
AndroidManifest.xml 中导致在应用程序中调用 onCreate 然后调用 createNotificationChannel 的位是这样的:
<application
android:name=".NotificationSchedulerApplication"
.../>
</application>
应用程序中的 onCreate 应该在您每次执行以下操作时被调用:运行 -> 调试
只要点击createNotificationChannel()左边的就可以设置断点。
关于java - 收到无法在 channel "channel_id_here"上发布通知的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63078084/
我们正在使用 VSTS 构建和发布通过 Xamarin 创建的 iOS 和 Android 应用程序。通过 VSTS 将 Android 应用发布到商店相对简单。有人可以指导我或提供一些如何通过 VS
我一直在研究 Spring Social Facebook 的 publish(objectId, connectionName, data) API ,但不确定此 API 的用法(遗憾的是,由于缺少
我正在使用 django viewflow 创建一个发布流程: 用户创建对象 它进入审核流程,其状态为待处理(公众不可见) 经过审核和批准后,就会发布并公开可见。 如果用户编辑同一实体,则会再次进入审
我正在尝试进行 API 调用,并且 API 需要格式为 XML: Security GetSessionInfo 999999999999 0 2 {
我已经查看了所有 StackOverflow,但没有找到适合我的案例的解决方案我有 405 HttpStatusCode 调用 API/Regions/Create 操作这是我的 baseContro
如果我切换到新版本的SpringBoot,我在启动应用程序时会得到上面的错误信息。这是为什么? 最美好的祝愿史蒂文 pom.xml 4.0.0 de.xyz.microservice spring
我有一个场景,页面导航是从一个域到另一个域完成的。例如,导航是从 http://www.foo.com到 http://www.bar.com在 JavaScript 中单击按钮 重定向时,我需要将用
这半年来一直深耕包头,这个城市比较不错,但是推进项目的难度确实挺大的。与开发产品相比,后者更省心。但是光研发产品,没有项目
我正在阅读有关 Github 版本 的信息,它似乎很适合您的项目。因为我们需要决定将哪些功能用于生产,哪些不用于。 我无法理解的部分是,master 和 release 分支如何在其中发挥作用。 Sh
我将一些代码推送到远程存储库,然后在 GitHub 上创建了第一个版本,并将其命名为 'v0.0.1'。 GitHub 现在显示我现在有一个版本,并且还在“标签”中显示我有一个标签 “v0.0.1”。
如果我有一个具有以下文件/文件夹结构的 GitHub 存储库 github.com/@product/template: /build /fileA /fileB /src /genera
我有一个 Maven 多模块项目。 当代码开发完成后,我们想在 Jenkins 中编写一个分支构建作业,它分支代码,增加主干中的 pom 版本,并删除 -SNAPSHOT 来自分支中的 pom 版本。
我有一个非常大的集合(约 40000 个文档,包含约 20-25 个字段,包括包含一组约 500 个项目的数组字段)和约 2000 个订阅者(他们现在只是机器人)。 因此,当用户订阅整个集合(不包括服
如果我正在使用消息队列构建一个包含数十个发布者/订阅者的系统,那么我似乎有一些网络配置选项: 我可以拥有一个所有机器都使用的集群代理 - 每台机器都没有本地队列 我可以在每台机器上本地安装代理,并使用
我正在使用 Flash Develop,并且创建了一个 ActionScript 3.0 项目。它启动并读取一个 xml 文件,其中包含图像的 url。我已将 url 保留在与 swf 相同的文件夹中
如果我在一个句子中使用 alloc 和 retain 声明一个 NSArray 那么我应该释放 NSArray 对象两次(即[arrayObject release] 2次)? 最佳答案 如果您在同一
我正在尝试在 Node 中实现发布/订阅模式,但不使用 Redis。功能应该是相同的;您可以发布到 channel ,订阅 channel 并收听数据(如果您已订阅);以下是 Redis 功能: pu
编辑:这个问题、一些答案和一些评论,包含很多错误信息。见 how Meteor collections, publications and subscriptions work准确理解发布和订阅同一服
我正在开发一款 DirectX 游戏,我发现在发布版本中我的平均帧速率为 170fps,但是在调试版本中我的帧速率约为 20fps。 我想知道发布和调试版本之间的巨大差异是否正常,特别是因为在调试中我
是否有办法回滚 Windows Azure 网站和 SQL 部署/发布? 我发布了一个网站,现在它导致了很多错误,我想回到之前的状态并进一步处理代码。 这可能吗? 最佳答案 如果您使用 Git 或 T
我是一名优秀的程序员,十分优秀!