我正在写一个AsyncTask如下:
class Load extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl) {
//do job seconds
//stop at here, and does not run onPostExecute
}
@Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
wait = false;
new Load().execute();
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法如下:
public void click() {
new Load().execute();
while(wait) {
;
}
}
Run Code Online (Sandbox Code Playgroud)
等待是一个全局布尔值。
在我的 Android 项目中,我AsyncTask用于Facebook API新闻提要请求。我收到错误:OnPostExecute method executed before doInBackground request finish.
private class NewsFeedAsyncTask extends AsyncTask < Integer, Integer, Boolean > {
@Override
protected Boolean doInBackground(Integer...params) {
if (Session.getActiveSession().getState().isOpened()) {
Get_news_feed();
return true;
}
return false;
}
@Override
protected void onPostExecute(Boolean t) {
super.onPostExecute(t);
adapter = new FacebookAdapter(data, context);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mPullRefreshListView.onRefreshComplete();
}
}
Run Code Online (Sandbox Code Playgroud)
fetchNewsFeed()
public void fetchNewsFeed() {
Session.openActiveSessionFromCache(context);
if (Session.getActiveSession().getState().isOpened()) {
Request.executeGraphPathRequestAsync(
Session.getActiveSession(), "me/home", new Request.Callback() {
@Override
public void onCompleted(
Response response) { …Run Code Online (Sandbox Code Playgroud) 在我的自定义中,DialogPreference我onClick使用View.onClickListener执行AsyncTask. 我的班级大致如下:
public class LoginDialog extends DialogPreference {
private Context mContext;
public LoginDialog(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setDialogLayoutResource(R.layout.login_dialog);
}
@Override
protected void showDialog(Bundle bundle) {
super.showDialog(bundle);
Button pos = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
pos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
...
new LoginTask(mContext, LoginDialog.this).doInBackground(user_name, user_password);
}
});
}
public class LoginTask extends AsyncTask<String, Void, Boolean> {
private LoginDialog mDialog;
private Context mContext;
public LoginTask(Context cx, LoginDialog loginDialog) …Run Code Online (Sandbox Code Playgroud) 我想用他的网址下载一个文件。我将 AsyncTask 与 HttpURLConnection 一起使用,但是当我收到响应代码时,服务器返回错误 403。我在 doInBackground 中使用了 HttpURLConnection。
代码 :
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
ext = FilenameUtils.getExtension(sUrl[0]);
fileName = FilenameUtils.getBaseName(sUrl[0]);
Log.i("Brieg", "storage : /storage/emulated/0/" + fileName + "." + ext);
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input …Run Code Online (Sandbox Code Playgroud) android httpurlconnection http-status-code-403 android-asynctask
我想知道 android 中是否有任何 API/类可以为我们提供原始日期,因为我不想从 android 设备获取日期/时间。
我有一个插入语句,我的应用程序需要大约 25 秒才能插入 ~1000 行。我试图用它Transactions来加快我的处理时间,但我在实现它时遇到了麻烦。
下面是我的方法inserting在我的DatabaseHandler:
public boolean insertQuestions(String gid, String qid, String qname) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_GID, gid);
contentValues.put(KEY_QID, qid);
contentValues.put(KEY_QNAME, qname);
long result = db.insert(TABLE_QUESTIONS, null, contentValues);
db.setTransactionSuccessful();
if (result == -1) {
db.close();
return false;
} else {
db.close();
return true;
}
} finally {
db.endTransaction(); //Error is here
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行上述方法时出现以下错误:
08-28 15:50:40.961 20539-20539/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.murrion.navigationdrawer, …Run Code Online (Sandbox Code Playgroud) 我有一个扩展 AsyncTask 的类,该类将消息发送到 WCF Web 服务。一条一条的简单消息可以正常工作,但是如果我在需要 30 秒才能完成的新线程上发送一条消息,那么在此过程中我发送一个快速请求,它不会执行 AsyncTask,直到长请求返回。
我认为 AsyncTask 的整个想法是这两条消息将在不同的线程上运行,因此不会堆叠?
这是我的代码:
private class RunnableTask extends AsyncTask<RunnableObj, RunnableObj, RunnableObj> {
@Override
protected RunnableObj doInBackground(RunnableObj... params) {
try {
if (params[0].requestBody != (null)) {
params[0].request.body(new JSONObject(params[0].requestBody));
}
params[0].request.asVoid();
return params[0];
}
catch (Throwable e) {
params[0].handler.onFailure(e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(RunnableObj runnableObj) {
super.onPostExecute(runnableObj);
runnableObj.handler.onSuccess();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我上面的 AsyncTask。
public void put(final String urlStr, final String requestBody, final HttpResponseHandler httpResponseHandler) {
RunnableObj obj = new RunnableObj(); …Run Code Online (Sandbox Code Playgroud) 我有一个扩展 AsyncTask 的类
public class MyClass extends AsyncTask<Void, Void, Void> {
private String response;
public String getResponse(){
return response;
}
@Override
protected Void doInBackground(Void... arg0) {
/* code */
return null;
}
@Override
protected void onPostExecute(Void result) {
response = aString;
super.onPostExecute(result);
}
}
Run Code Online (Sandbox Code Playgroud)
在其他活动中,我创建了一个 MyClass 实例
MyClass c = new MyClass();
c.execute();
response = c.getResponse();
Toast.makeText(getApplicationContext(), "response = " + response, Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)
但是我的响应变量为空,可能是因为 Toast 是在任务完成之前执行的。你能给我正确的方法,以便我在任务完成后得到结果吗?
我在远程服务器上有一个图像 url 列表。我需要在不使用任何第三方库的情况下将它们异步加载到 Grid View 中。我已经构建了以下任务:
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(String... params) {
if (isCancelled()) {
return null;
}
try {
URL url = new URL(params[0]);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Once complete, see …Run Code Online (Sandbox Code Playgroud) 假设我有一个名为UpdateInterfaceStatusesTask的Android AsyncTask :
private class UpdateInterfaceStatusesTask extends AsyncTask<Object, Object, Object> {
public UpdateInterfaceStatusesTask() {
;
}
protected Object doInBackground(Object... params) {
View header = ((NavigationView) findViewById(R.id.nav_view)).getHeaderView(0);
((TextView) header.findViewById(R.id.nav_head_status)).setText(ServerThread.getInstance().isInterrupted() ? "Offline" : "Online");
return null;
}
@Override protected void onPostExecute(Object param) {
;
}
}
Run Code Online (Sandbox Code Playgroud)
我想以编程方式创建它的新实例:
public void createNewInstance(Class<? extends AsyncTask<?, ?, ?>> clazz) {
try {
clazz.newInstance().execute();
} catch (Exception x) {
x.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
W/System.err: java.lang.InstantiationException: java.lang.Class<nl.hypothermic.offthegrid.ChatActivity$UpdateInterfaceStatusesTask> has no zero argument constructor
W/System.err: at java.lang.Class.newInstance(Native Method) …Run Code Online (Sandbox Code Playgroud)