android - 当我清理我的应用程序时,android studio 服务不起作用
问题描述
当有人收到消息时,我使用服务推送通知,当我打开应用程序和关闭应用程序时我的服务运行良好,但是当我清理我的应用程序时,它就停止了。是我自己编写 startForeground 而不是使用的问题他们给的startForeground?一开始是可以的,但是当我添加startMyOwnForeground和Runnable时,它不起作用 Runnable 是每 2 秒连接到我的数据库以检查是否有新消息,它会向用户推送通知
这是我的代码
public class MyService extends Service implements getcheckfriend {
private static final int NOTIF_ID = 1;
final Handler handler = new Handler();
private static final String NOTIF_CHANNEL_ID = "Channel_Id";
public String user;
public String type = "bgnotify";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
// do your jobs here
Bundle extras = intent.getExtras();
user = (String) extras.get("user");
update(user);
System.out.println("123465897");
Runnable runnable = new Runnable() {
@Override
public void run() {
update(user);
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(runnable, 2000);
return super.onStartCommand(intent, flags, startId);
}
private void startMyOwnForeground(List<Notify> result) {
if (!CollectionUtils.isEmpty(result)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name,
importance);
Notification newMessageNotification1 =
new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_comment_24)
.setContentTitle("VoCo")
.setContentText(result.get(1).getname()+"")
.setGroup("request")
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
assert notificationManager != null;
notificationManager.createNotificationChannel(mChannel);
notificationManager.notify(random(), newMessageNotification1);
}
}
}
public void update(String user){
Notifybackground notifybackground = new Notifybackground(this,this);
notifybackground.execute(type,user);
}
@Override
public void checkfriendresult(List<Notify> result) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground(result);
else
startForeground(1, new Notification());
}
public int random(){
Random ran = new Random();
return ran.nextInt(9999)+1;
}
}
解决方案
有时它还取决于您的移动设备。如今,移动设备的电池寿命更长。因此某些应用程序不会自动启动(或在专门打开之前接收通知)。要克服此问题,您可以在电池设置中免除您的应用程序,例如不要优化此应用程序的使用。我个人在 Oneplus 设备和小米设备中遇到过这样的问题。您还可以在此处获取有关 Mi 设备的更多信息
推荐阅读
- android - 将适配器与不同的布局管理器合并
- python - 有没有办法将屏幕上的所有文本放入 python3 中的数组中
- java - 在共享对象文件中查找 Android Java 可用方法
- c# - Unity 想要从另一个数组中获取游戏对象
- c - 为什么 Helgrind 显示“违反锁定顺序”错误消息?
- java - 不接受文件中的更改
- c# - 检查逗号分隔字符串中的 id 是否与另一个字符串数组中的任何 id 匹配
- flutter - Flutter - 单个项目中 Web 和 Android 的不同点击操作
- ionic-framework - 配置APP名称的正确位置在哪里?
- javascript - 如何根据角度的行内容在摩纳哥编辑器中打开上下文菜单