android activity和service通信问题
伊谢尔伦
伊谢尔伦 2017-04-17 16:14:37
[Android讨论组]
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(3)
迷茫

如果不使用Binder,可以使用BroadcastActivityService之间建立沟通。

PHPz

用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 成为前台进程的关键步骤
        
    }

}

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号