我已经完全阅读了关于服务的文档,但对于如何使用/编码服务我仍然完全困惑。Android服务感到困惑
我试图做到: 我的主要活动: 用户选择了定时器的所有选项,然后点击一个按钮来启动一个定时器(在服务)与点击。我试图通过putExtra将选项传递给服务。
该服务将收集变量到服务使用的新变量中。
我有一个onCreate节调用我公开的计数器,这是我在服务中声明的,但不是在onCreate节中。我还声明了所有需要从这里的活动传递的选项中枚举的变量。
我是否需要绑定到服务才能真正通过putExtra传递变量?
我有一个onStart,这是我试图通过一系列获取来枚举变量值的地方。这由活动前面提到的按钮触发。里面的活动 - 实例:
mSet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//if toggled on
if (mEnableDisable.isChecked()){
getCurrentTime();
//start passing our variables to the service
Intent passvars = new Intent(getBaseContext(),TimerService.class);
passvars.putExtra("mHour24", mHour24);
//start the service now
startService(new Intent(TimerService.class.getName()));
}
}
});
里面的服务 - 例如:
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
//Collecting data from Activity for calcs
Bundle getvars = intent.getExtras();
mHour24 = getvars.getInt("mHour24");
//start the counter now that I have my values
countDown.start();
}
另外,如果我能得到开始没有崩溃,我需要传递一个值的服务回到活动。所以我想我正在用putExtra在服务和getExtra中做这件事。再一次,我是否需要绑定到服务以获取新值?
要绑定,如果我需要我会做这个按钮按下。如果程序退出,我还会在主要活动的一部分中添加一段,但随后会恢复重新绑定并收集该值。我试图拉的价值是柜台剩余的时间。因此,在计数器服务中,我需要一个onTick将剩余时间放入一个变量中,并对该变量执行putExtra,在活动中,我希望收集该值并将其显示在UI中。
这是我第一次尝试服务,我不确定如何正确创建和使用。预先感谢所有的帮助,对于如此冗长的复杂帖子感到抱歉。
更新: 所以我现在有服务工作。我只是无法从服务中获取信息回到主要活动。
我添加了一个功能,试图取回从中按钮点击后推出该服务的数据启动服务:
startService(passvars);
//Init. variable for getDisplayInf() function to update the display with counter strings
Running = 1;
getDisplayInf();
而且getDisplayInf()例如:
public void getDisplayInf() {
//Intent stIntent = new Intent(MainActivity.this,MainActivity.class);
//Intent passvars = new Intent(MainActivity.this,Service.class);
Bundle getvars = getIntent().getExtras();
String Remaining;
String CountDown;
do {
Remaining = getvars.getString("Remaining");
CountDown = getvars.getString("CountDown");
mRemaining.setText(Remaining);
mCountDown.setText(CountDown);
Running = getvars.getInt("Running");
}
while (Running == 1);
};
计时器将完成时将Running变量设置为0。 只要我点击这个新功能的按钮就会崩溃应用程序。
在服务上,我在柜台上的onTick这样做:
@Override
public void onTick(long millisUntilFinished) {
Running = 1;
Remaining = "Time Remaining: ";
CountDown = formatTime(millisUntilFinished);
ticker();
}
股票代码:
public void ticker() {
Intent passvars = new Intent(Service.this,MainActivity.class);
//this is for the activity to keep looping to grab the countdown values while running this timer
//now send it to the activity
passvars.putExtra("Running", Running);
//String Values to be passed to the activity
//now send it to the activity
passvars.putExtra("mRemaining", Remaining);
//now send it to the activity
passvars.putExtra("mCountDown", CountDown);
};
查看[this](http://stackoverflow.com/questions/3197335/android-restful-api-service/3197456#3197456)对服务/活动“通信”用例的回答。 – FrVaBe 2011-04-21 15:59:00
'startService(new Intent(TimerService.class.getName()));' 你创建一个新的Intent,当你创建一个叫做passvars的。请尝试使用那个!另外,您应该将'getBaseContext()'改为'this'(或者例如'MainActivity.this') – 2011-04-21 16:03:12