我需要在背景服务中启动倒计时器并在My片段上显示它。这就是我目前所处的位置。
调用startService后,ComponentName c为null。 我不知道如何使用调试器来调试它。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_map, container, false);
setUpMapIfNeeded();
controlv = rootView.findViewById(R.id.controls_parked);
parker_info = (TextView)rootView.findViewById(R.id.parked_info);
take_to_car_btn= (Button)rootView.findViewById(R.id.walk_to_Car);
unPark = (Button)rootView.findViewById(R.id.un_park);
timer = (Button)rootView.findViewById(R.id.timer_btn);
myContext = getActivity();
mDpi = getActivity().getResources().getDisplayMetrics().densityDpi;
timer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ComponentName c = getActivity().startService(new Intent(getActivity(), TimerService.class));
Log.i(TAG, "Started service");
}
});
return rootView;
}
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
private void updateGUI(Intent intent){
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
}
Toast.makeText(myContext, "Timer", Toast.LENGTH_SHORT).show();
}
这是我的服务:
public class TimerService extends Service {
private final static String TAG = "TimerService";
public static final String TIMER_BR = "parking.group6.csc413.projectmap_timer";
Intent timer_intent = new Intent(TIMER_BR);
CountDownTimer cdt = null;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
timer_intent.putExtra("countdown", millisUntilFinished);
sendBroadcast(timer_intent);
}
@Override
public void onFinish() {
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
@Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
是的,我的清单文件有:
<service android:name=".TimerService"/>
答案 0 :(得分:-1)
仅当服务已启动或已在运行时,ComponentName才为空。如果该服务尚不存在,则返回null。要启动CountDownTimer,您可以使用操作:
Intent intent = new Intent(getActivity(), TimerService.class);
intent.setAction("START");
getActivity().startService(intent);
调用onStartCommand
时,请检查操作是否等于START
。如果是,请启动CountDownTimer
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ("START".equals(intent.getAction()) {
// start CountDownTimer
}
return super.onStartCommand(intent, flags, startId);
}