Android 5.0+中的服务

时间:2015-04-27 13:04:34

标签: android service android-5.0-lollipop

我打算像这样工作: 用户打开一个功能:让我们说天气。 现在天气数据将每隔6小时从服务器发出一次,并显示给小部件(remoteview),现在用户关闭该功能。然后窗口小部件不应该显示天气,甚至不应每6小时刷新一次数据。 还有3-4个这样的功能。 现在我创建了一个服务来获取所有必需的数据,而不是将它们传递给remoteview。对于启动服务,我在TimeOut Activity中使用了它:

char startAnswer;
char gameAnswer;

在关闭代码时停止服务相同:

i = new Intent(TimeOut.this, TimeService.class);
i.setAction("com.example.Weather.Idle");
startService(i);

此代码在API< = 19中正常运行。但在Lollipop,它在启动或停止服务时崩溃。 我在SO中搜索了很多,并尝试了绑定或解除绑定服务的代码,但没有任何帮助。 请帮我一些代码,而不仅仅是链接...... 在此先感谢:)

2 个答案:

答案 0 :(得分:0)

从任何活动类启动服务

    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;
}

在此处添加您的逻辑。你可以在这里使用一个线程做一些工作。您可以随时停止服务,我希望您不会发现任何崩溃。

答案 1 :(得分:0)

我在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;
    }
}