我正在尝试使用JobScheduler在后台运行会计计算器,但不知何故,它不会进行计算。该程序运行顺利,这就是为什么它让我困惑为什么它不起作用。感谢您的帮助。
这是我的职业服务课程:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService extends JobService {
private JobParameters params;
int num1a;
int num1b;
int num2a;
int num2b;
int num3a;
int num3b;
int num4a;
int num4b;
int num5a;
int num5b;
int sum1;
int sum2;
int sum3;
int sum4;
int sum5;
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
public boolean onStartJob(JobParameters params) {
this.params = params;
Toast.makeText(getApplicationContext(), "Start", Toast.LENGTH_LONG).show();
new MonthlyTask().execute();
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
private class MonthlyTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void xVoid) {
super.onPostExecute(xVoid);
jobFinished(params, false);
Toast.makeText(getApplicationContext(), "Finish", Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... params) {
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = preferences.edit();
try {
num1a = preferences.getInt("expense1", 0);
num1b = preferences.getInt("subtotal1", 0);
num2a = preferences.getInt("expense2", 0);
num2b = preferences.getInt("subtotal2", 0);
num3a = preferences.getInt("expense3", 0);
num3b = preferences.getInt("subtotal3", 0);
num4a = preferences.getInt("expense4", 0);
num4b = preferences.getInt("subtotal4", 0);
num5a = preferences.getInt("expense5", 0);
num5b = preferences.getInt("subtotal5", 0);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
sum1 = num1a + num1b;
sum2 = num2a + num2b;
sum3 = num3a + num3b;
sum4 = num4a + num4b;
sum5 = num5a + num5b;
editor.putInt("subtotal1", sum1);
editor.putInt("subtotal2", sum2);
editor.putInt("subtotal3", sum3);
editor.putInt("subtotal4", sum4);
editor.putInt("subtotal5", sum5);
return null;
}
}
}
这是我的主要活动
public class MainActivity extends AppCompatActivity implements android.view.View.OnClickListener{
//Do stuffs
public void onClick(View view) {
if (view == findViewById(R.id.btnSave)) {
JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(),
MyJobService.class.getName()));
//run job service after every 5 seconds, which put back to 15 mins...but thats fine
builder.setPeriodic(5000);
builder.setPersisted(true);
jobScheduler.schedule(builder.build());
finish();
}}
答案 0 :(得分:1)
我正在尝试使用JobScheduler在后台运行会计计算器
这个例子真的很奇怪。
嗯,嗯,如果通过&#34;计算&#34;,你的意思是加法,它正在做加法。但是,然后你扔掉了结果。您但不知何故,它不会进行计算
SharedPreferences
apply()
而未调用commit()
或{{1}}来保存更改。