首先,我不得不说我对原生 Android 开发还很陌生。我将以下代码放入我的 MainActivity
类中的 onCreate 内。
我从未使用过 AsyncTask,所以我不知道这是否是最佳实践。我应该创建一个新的 AsyncTask 类并以某种方式在 onCreate 方法中加载它吗?我将其放在 MainActivity onCreate 方法中,因为诸如 bp
(计费购买类)、polfish、计数应用程序启动等变量的范围。
我也不知道要返回什么?因为我有多个结果。有很多教程如何创建这样的 AsyncTask 以及在那里存储 SharedPreferences 的建议,但我想知道它的最佳实践。例如,稍后在我的 onResume 方法或类似操作中获取值。
new AsyncTask<Context, Void, String>()
{
@Override
protected String doInBackground(Context... params)
{
Context context = params[0];
SharedPreferences pref = context.getSharedPreferences("Pref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
// Count App Launches
totalCount = pref.getInt("counter", 0);
totalCount++;
editor.putInt("counter", totalCount);
editor.apply();
// Pollfish ADS
int pollfishPref = pref.getInt("pollfish", 0);
Log.d(TAG,"Application launch count: " + totalCount);
Log.d(TAG,"pollfish count: " + pollfishPref);
if (!bp.isPurchased(PRODUCT_ID) && (pollfishPref == 0 || (pollfishPref != 0 && pollfishPref <= totalCount)))
{
PollFish.ParamsBuilder paramsBuilder = new PollFish.ParamsBuilder("xxx")
.releaseMode(false)
.customMode(false)
.indicatorPosition(Position.MIDDLE_RIGHT)
.indicatorPadding(0)
.build();
PollFish.initWith(MainActivity.this, paramsBuilder);
mTracker.setScreenName("Pollfish Count: " + pollfishPref + " Applaunch Count: " + totalCount);
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
Boolean consumed = pref.getBoolean("consumed", Boolean.parseBoolean(null));
Log.d(TAG,"consumedPref: " + consumed);
if (!consumed)
{
editor.putBoolean("consumed", true);
editor.apply();
bp.consumePurchase(PRODUCT_ID);
Log.d(TAG,"consumed now!");
}
return xxx;
}
protected void onPostExecute(String result)
{
Log.d(TAG, "Preference received in background: " + result);
};
}.execute(this);
最佳答案
通常,最佳实践是通过使用单独的类来重用 AsyncTask 和更干净的代码。如果您担心变量范围,可以将它们传递到 AsyncTask
的构造函数中。
class MyAsyncTask extends AsyncTask<Params, Progress, Result> {
private Object arg1;
public MyAsyncTask(Object arg1) {
this.arg1 = arg1;
}
@Override
public Result doInBackground(Params... params) { }
@Override
public void onPostExecute(Result result) { }
}
当然,更新必要的对象类型,并像这样使用它
new MyAsyncTask(arg1).execute();
您可能希望从 AsyncTask
外部的 SharedPreferences
更新和检索值,然后将这些相应的值传递给构造函数,如图所示。
I don't know what to return? Because I have multiple results.
遗憾的是,您只能返回一种类型的类。如果您关心如何将 AsyncTask 的结果返回到调用它的位置,那么我会推荐 callbacks 。
关于java - 使用 AsyncTask 进行 SharedPreference 和一般初始化的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979512/