[英]Service in android 5.0+
我打算这样工作:用户打开一个功能:假设天气。 现在,天气数据每隔6小时就会从服务器获取一次,并显示在小部件(remoteview)中,现在用户关闭该功能。 则小部件不应显示天气,甚至不应每6小时刷新一次数据。 还有3-4种类似的功能。 现在,我创建了一项服务来获取所有必需的数据,然后将它们传递给remoteview。 对于启动服务,我在超时活动中使用了此功能:
i = new Intent(TimeOut.this, TimeService.class);
i.setAction("com.example.Weather.Idle");
startService(i);
在关闭代码中停止服务也是如此:
stopService(i)
这段代码在API <= 19中运行良好。 但是在棒棒糖中,它在启动或停止服务时崩溃。 我在SO中进行了大量搜索,还尝试了用于绑定或取消绑定服务的代码,但没有任何帮助。 请帮助我提供一些代码,而不仅仅是链接...在此先感谢:)
从任何活动类启动服务
Intent intent = new Intent(MainActivity.this, BackgroundService.class);
startService(intent);
这是服务类代码
public class BackgroundService extends Service{
public static Context appContext = null;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (appContext == null) {
appContext = getBaseContext();
}
Toast.makeText(appContext, "Services Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
在这里添加您的逻辑。 您可以在这里使用线程来做一些工作。 您可以随时停止服务,我希望您不会发现任何崩溃。
我在5.0服务中也遇到过类似的问题。 这可能不是正确的答案,但是可以。 你可以试试看。 我使用EventBus
与我的服务进行通信。 因此,当我想停止要发送的服务时,
EventBus.getDefault().post(new ServiceEvent(ServiceEvent.STOP_SERVICE));
在服务中
public void onEvent(ServiceEvent event) {
if (event.getEvent() == ServiceEvent.STOP_SERVICE) {
methodToStopService();
}
}
private void methodToStopService() {
// do some stuff
stopSelf();
}
确保为事件注册了服务。
private void registerEventBus() {
EventBus eventBus = EventBus.getDefault();
if (!eventBus.isRegistered(this)) {
eventBus.register(this);
}
}
ServiceEvent类-这是与EventBus一起使用的我自己的类。
public class ServiceEvent {
private int event;
public static final int STOP_SERVICE = -1;
public ServiceEvent(int event) {
this.event = event;
}
public int getEvent() {
return event;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.