如何在 android 中最好地做到这一点?

How to best do this in android?

我正在考虑制作一个与 Web 交互的应用程序 API。

要求:

  1. 开始投注并显示通知
  2. 通过 POST 将投注发送到网站。
  3. 当结果到达时,用结果更新 UI。
  4. 如果用户没有按下停止按钮,返回#2 否则停止投注并删除通知。
  5. 如果应用程序已关闭或不是活动应用程序,投注仍将继续
  6. 如果点击通知,show/start 应用

经过大量的研究和阅读,我认为绑定的前台服务可以实现这一点,但我找不到(或者我可能只是不明白)怎么做...

这是我的问题:

如果我创建一个服务并将投注逻辑放入其中,我的 activity/app 将启动该服务并与之绑定..

  1. 如何让服务开始使用来自 activity 的初始投注数据进行投注?
  2. 服务如何知道应用程序何时关闭或不是屏幕上的活动应用程序?
  3. 服务如何更新应用程序的UI?

我仍然会寻找一种可能的方法来做到这一点。我希望有人能指导我正确的方法..

更新

(3) 我最终使用 LocalBroadcast 向应用程序组件发出何时更新 UI 服务的信号。

(2) 通过使用 LocalBroadcast,我认为我的服务不应该介意我的应用程序的状态。

(1) 我使用了 Bound Service 并且只是调用服务上的方法来传递数据并开始投注。

您通过 Intent 向服务发送数据:

Intent serviceIntent = new Intent(YourService.class.getName());
serviceIntent.putExtra("data", "123456");
context.startService(serviceIntent);

然后在服务中覆盖OnStartCommand方法:

public int onStartCommand (Intent intent, int flags, int startId)
{
   String userID = intent.getStringExtra("data");
   return START_STICKY;//or non-sticky
}

关于处理应用关闭事件你可以查看这个答案(我自己没用过):

关于你最后一个问题,你可以use BroadcastReciever to send data from service to activity and update UI

如需进一步阅读,请查看此链接:

  1. Services Tutorials
  2. Official Developers Guide To Services
  3. BroadCastReceivers Tutorial

使用齐射api。 将其添加为 build.gradle

中的依赖项
dependencies {
    compile 'com.android.support:design:+'
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.android.volley:volley:+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}