我现在既要让应用退出时保持service运行,又要在activity中访问service中的方法,该怎么做?
startService可以保持service运行,但是不能访问binder对象;
bindServcie可以访问binder对象但是不能保持service运行;
上面是比较纠结的两点,我本不是安卓开发,写个SDK碰到的问题,请各位帮忙解答
我现在既要让应用退出时保持service运行,又要在activity中访问service中的方法,该怎么做?
startService可以保持service运行,但是不能访问binder对象;
bindServcie可以访问binder对象但是不能保持service运行;
上面是比较纠结的两点,我本不是安卓开发,写个SDK碰到的问题,请各位帮忙解答
首先,题主有个理解错误的地方, 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 成为前台进程的关键步骤
}
}
2 回答1.3k 阅读✓ 已解决
2 回答2.6k 阅读
2 回答1.7k 阅读
1 回答2.1k 阅读
1 回答1.1k 阅读
1 回答1.3k 阅读
1.3k 阅读
如果不使用
Binder
,可以使用Broadcast
让Activity
和Service
之间建立沟通。