我必须使用按钮上的JobDispatcher启动后台服务。我有一个带有很多片段的Activity,并且在我的一个片段中有一个按钮,该按钮应该在按钮单击后的10秒内调用后台服务,但是一旦我的应用程序启动,该服务就会启动。它应该在单击按钮之后开始,但是应该在单击按钮之前开始。
单击按钮后应显示吐司。请参阅下面我至今尝试过的代码。
服务等级
public class DayJobService extends JobService {
ExpenseClass expenseClass;
DatabaseReference dbref;
String username,currentdate,monthyr,expensesname,totaltxt;
Context context;
public DayJobService(){
}
@Override
public boolean onStartJob(final JobParameters job) {
Log.d("Started JOb","job started success");
Toast.makeText(getApplicationContext(),"JOB STARTED",Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onStopJob(JobParameters job) {
return true;
}
清单
<service
android:exported="false"
android:name=".JobService.DayJobService">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>
</service>
FragmentClass
public class DayExpensesFragment extends Fragment implements RecyclerItemTouchHelper.RecyclerItemTouchHelperListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_day_expenses, container, false);
startBtn=(Button)view.findViewById(R.id.startJob);
firebaseJobDispatcher=new FirebaseJobDispatcher(new
GooglePlayDriver(getContext()));
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startJob();
}
});
}
public void startJob(){
Job job=firebaseJobDispatcher.newJobBuilder().
setService(DayJobService.class).setTag(DAY_JOB_TAG).setLifetime(Lifetime.FOREVER).
setRecurring(true).setTrigger(Trigger.executionWindow(10,15)).
setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL).setReplaceCurrent(false).
setConstraints(Constraint.ON_ANY_NETWORK).build();
firebaseJobDispatcher.mustSchedule(job);
}
}