扫码关注官方订阅号
小伙看你根骨奇佳,潜力无限,来学PHP伐。
如果不使用Binder,可以使用Broadcast让Activity和Service之间建立沟通。
Binder
Broadcast
Activity
Service
用eventBus吧
首先,题主有个理解错误的地方, startService 只是开启 service ,service运行在后台,还是有可能因内存不足而被杀死.
第二点, service 可以以混合启动的形式启动,也就是先 startService 再 bindService ,此时 service 对象只要不被杀死, Activity中就可以通过调用 mBinder中的方法进行操作
所以问题就变成了如何保证 service 在后台得到一个较高的优先级,从而不被轻易杀死给 service 添加一个状态栏效果 可以让它成为前台进程 提高优先级,防止被回收 看以下代码
public class MyService extends Service { private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); //通知 R.drawable.ic_launcher是图片资源文件 可以自定义 Notification notification = new Notification(R.drawable.ic_launcher, "这里有个通知", System.currentTimeMillis()); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, "可以自定义标题", "可以自定义内容", pendingIntent); startForeground(1, notification); //让 service 成为前台进程的关键步骤 }
}
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
如果不使用
Binder,可以使用Broadcast让Activity和Service之间建立沟通。用eventBus吧
首先,题主有个理解错误的地方, startService 只是开启 service ,service运行在后台,还是有可能因内存不足而被杀死.
第二点, service 可以以混合启动的形式启动,也就是先 startService 再 bindService ,此时 service 对象只要不被杀死, Activity中就可以通过调用 mBinder中的方法进行操作
所以问题就变成了如何保证 service 在后台得到一个较高的优先级,从而不被轻易杀死
给 service 添加一个状态栏效果 可以让它成为前台进程 提高优先级,防止被回收 看以下代码
}