我打算这样工作:用户打开一个功能:比方说天气。现在,天气数据将每6小时从服务器发送一次,并将显示到窗口小部件(远程视图),现在用户关闭了该功能。那么小部件就不应该显示天气,甚至不应该每6小时刷新一次数据。还有3-4个类似的特性。现在,我已经创建了一个服务来获取所有需要的数据,然后将它们传递给remoteview。为了启动服务,我在TimeOut活动中使用了以下代码:
i = new Intent(TimeOut.this, TimeService.class);
i.setAction("com.example.Weather.Idle");
startService(i);与关闭代码中的停止服务相同:
stopService(i)这段代码在<=19应用程序接口中运行良好,但在棒棒糖中,它在启动或停止服务时崩溃。我在SO中搜索了很多,也尝试了绑定或解除绑定服务的代码,但没有任何帮助。请帮助我一些代码,而不仅仅是链接…提前感谢:)
发布于 2015-04-27 21:12:30
从任何activity类启动服务
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;
}在这里添加你的逻辑。你可以在这里使用线程来做一些工作。你可以随时停止服务,我希望你不会发现任何崩溃。
发布于 2015-04-27 21:27:43
我在5.0的Service中遇到过类似的问题。这可能不是正确的答案,但它是有效的。你可以试试。我使用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;
}
} https://stackoverflow.com/questions/29896663
复制相似问题