服务不工作?

Service not working?

我正在构建一个游戏,我希望用户在 20 秒内完成许多活动。 20 秒结束后,我想将用户发送到 GameOver 屏幕。为了运行后台定时器,我用了一个服务。问题是,该服务似乎 运行ning?

奇怪的是,连吐司都没有显示。这是我调用服务的地方:

这是清单:

请告诉我为什么服务或计时器没有 运行ning。非常感谢您的所有帮助,我真的很感激!如果您需要更多代码,请告诉我,我会告诉您。谢谢!

:-)

{Rich}

服务无法与 UI 交互,而 Toast 可以。如果您想这样做,请尝试将 runOnUIThreadgetApplicationContext 一起使用,或者使用 binding/callbacks 的奇特方式。另外,看看 AlarmManager,可能是一个更简单的解决方案,而不是 运行 服务。

BroadcastReciever 应该是获得和展示敬酒的解决方案。只需从服务发送消息并在 activity 中捕获它。然后随心所欲地使用它。

//Service class
final static String ACTION = "ACTION";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    intent = new Intent();
    intent.setAction(ACTION);
    intent.putExtra("StartToast", "Started!");
    sendBroadcast(intent);

    return START_STICKY;
}

//Activity class
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    intent = new Intent(MainActivity.this, ServiceClass.class);

    myReceiver = new MyReceiver();
    intentFilter = new IntentFilter();
    intentFilter.addAction(ServiceClass.ACTION);
    registerReceiver(myReceiver, intentFilter);

}

private class MyReceiver extends BroadcastReceiver {

    public String startToast;

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub

        startToast = arg1.getStringExtra("StartedToast");
        Toast.makeText(MainActivity.this, startToast, Toast.LENGTH_SHORT).show();

    }

注册此接收器后,您会收到消息并在使用 intent.putExtra(....); 发送数据时自动创建 toast。