Android 安卓5.0+;

Android 安卓5.0+;,android,service,android-5.0-lollipop,Android,Service,Android 5.0 Lollipop,我打算这样工作: 用户打开一个功能:比如说天气。 现在,天气数据将每6小时来自服务器,并将显示到小部件(remoteview),现在用户关闭该功能。然后小部件不应该显示天气,甚至每6小时刷新一次数据。 还有3-4个类似的功能。 现在,我创建了一个服务来获取所有必需的数据,然后将它们传递给remoteview。对于启动服务,我在超时活动中使用了此选项: i = new Intent(TimeOut.this, TimeService.class); i.setAction("com.example

我打算这样工作: 用户打开一个功能:比如说天气。 现在,天气数据将每6小时来自服务器,并将显示到小部件(remoteview),现在用户关闭该功能。然后小部件不应该显示天气,甚至每6小时刷新一次数据。 还有3-4个类似的功能。 现在,我创建了一个服务来获取所有必需的数据,然后将它们传递给remoteview。对于启动服务,我在超时活动中使用了此选项:

i = new Intent(TimeOut.this, TimeService.class);
i.setAction("com.example.Weather.Idle");
startService(i);
在关闭代码中停止服务时相同:

stopService(i)

这段代码在API中运行良好,可以从任何活动类启动服务

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

你能添加stracktrace吗?实际上它没有崩溃。。。但stopservice(i)并未停止服务。虽然我关闭了它,但它仍在运行。然后,您传递给
stopService()
意图不同,或者调用了
bindService()
,或者调用了
stopService()
@commonware之后调用了另一个名为
startService()
:我正在做的是。。。我有3-4功能,如天气,屏幕关闭,usb充电识别等。我开始相同的服务,在服务中,我做了每个逻辑部分。我应该为所有人创建单独的服务吗?“我应该为所有人创建单独的服务吗?”--我不知道。请解释这是如何回答这个问题的。谢谢@waheed,但它不会停止这是我的问题。我知道如何启动和停止服务。但是我的代码在android 5.0中不起作用:)我已经在android 5+上测试了这段代码。它工作正常。请尝试找出确切的问题。检查您的清单文件。您注册了您的服务吗???@waheed:正如我所说,这在API中起作用,请阅读关于START_not_STICKY和START_STICKY的内容,这里看起来很有希望。。。我很快就会试试,然后告诉你。Ty:)
ServiceEvent
是我与EventBus一起使用的一个POJO类。我为命名混乱道歉。它可能看起来像是SDK的一部分。EventBus也来自POJO??不。它是一个用于在任何事物之间进行通信的库。真的很有帮助。不工作。。。它与我使用的默认库冲突。它显示了我使用的@Nullable接口中的错误:(