首先,题主有个理解错误的地方, 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 成为前台进程的关键步骤

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐