java - 如何在 Android Studio 中使用后台服务发送通知?
问题描述
我想在我的应用程序中发送推送通知,但几分钟后,android 杀死了我的后台服务并且通知没有显示。如何使android不会关闭的后台服务?
BackroundService.class
public Context context = this;
public android.os.Handler handler = new Handler();
public static Runnable runnable = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.e("Service", "Service crated!");
runnable = new Runnable() {
public void run() {
Log.e("Service", "Service is still running!");
Toast.makeText(context, "Service is still running", Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable, 50000);
}
};
handler.postDelayed(runnable, 15000);
}
@Override
public void onDestroy() {
}
@Override
public void onStart(Intent intent, int startid) {
Log.e("Service", "Service started by user!");
}
AlarmReceiver.class
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("ID", 0);
String message = intent.getStringExtra("TEXT");
String tittle = intent.getStringExtra("TITTLE");
Intent mainIntent = new Intent(context, BackgroundService.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.drawable.finance43)
.setContentTitle(tittle)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_MESSAGE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "REMINDERS";
NotificationChannel channel = new NotificationChannel(channelId,
"Reminder",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
notificationManager.notify(notificationId, builder.build());
}
当我启动应用程序时,我看到“服务仍在运行!” 约1小时。
解决方案
推荐阅读
- android - 警告:API 'variant.getMergeAssets()' 已过时 / Android Studio 3.3
- c# - 使用 WPF MVVM 缩放图像,将移动顶层控件。如何固定图像缩放时间?
- swagger - Swagger OpenAPI 使用带有模式的对象而不是数组
- docker - 启用在 docker 镜像中调用 webhook
- java - 字符串中单词之间额外空格的正则表达式条件
- php - 如何编写多个 .htaccess 重写规则?
- c++ - 在消息映射中创建按钮和引用
- javascript - 同位素 - jQuery - 内容更改后图像相互堆叠
- android-studio - Android Studio 3.3 中缺少 Instant Run
- python-2.7 - 从 dataset.variable 返回的 OrderedDict()