我有一个AsyncTask
从我的Activity的onCreate()
方法运行,它从mysql数据库中获取一个列表。
在onStart()
方法中,我调用方法来启动一些动画。
我想在获取列表后才能启动这些动画
即:完成后AsyncTask
。
我知道我可以在AsyncTask对象的onPostExecute()
方法中启动动画
但我希望每次活动变得可见时都会启动这些动画。
应该是这样的:
FirstActivity (ListFetches和动画开始)。
SecondActivity 到 FirstActivity (动画开始,列表已经提取)。
以下是我的代码
public class FirstSelection extends ActionBarActivity {
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<String> records;
Intent i;
Intent j;
Intent k;
double version;
double oldVer = 1.0;
String downloadlink;
DownloadManager dm;
private long enqueue;
private Toolbar toolbar;
ValueAnimator colorAnimation;
FrameLayout myframe;
ValueAnimator statusAnim;
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> dadapter;
ImageView image;
Animation anim;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first_selection);
toolbar = (Toolbar) findViewById(R.id.new_tool);
myframe = (FrameLayout)findViewById(R.id.myframe);
menu = new String[]{"Refresh","Report Broken Link","Request songs"};
dLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
dList = (ListView)findViewById(R.id.navList);
image = (ImageView)findViewById(R.id.loader);
anim = AnimationUtils.loadAnimation(this, R.anim.myanim);
image.startAnimation(anim);
dadapter = new ArrayAdapter<String>(this,R.layout.drawer_list_item,menu);
dList.setAdapter(dadapter);
setSupportActionBar(toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
context=this;
records=new ArrayList<String>();
listProduct=(ListView)findViewById(R.id.product_list);
i = new Intent(this, ReportActivity.class);
j = new Intent(this, RequestActivity.class);
k = new Intent(this, AboutDeveloper.class);
BackTask bt=new BackTask();
bt.execute();
adapter=new CustomAdapter(context, R.layout.list_item_first,R.id.pro_name, records);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id){
Intent songIntent = new Intent(getApplicationContext(), SecondSelection.class);
startActivity(songIntent);
}
});
//Animation for Action Bar
Integer colorFrom = getResources().getColor(R.color.first);
Integer colorTo = getResources().getColor(R.color.last);
colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
toolbar.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
//Animation for Status Bar
Integer colorFirst = getResources().getColor(R.color.begin);
Integer colorLast = getResources().getColor(R.color.end);
statusAnim = ValueAnimator.ofObject(new ArgbEvaluator(), colorFirst, colorLast);
statusAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
myframe.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
//Start the Animations after fetching the list.
//After executing the bt.execute()
}
@Override
public void onBackPressed() {
if (dLayout.isDrawerOpen(dList)) {
dLayout.closeDrawer(dList);
}
else{
doExit();
}
}
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
doExit();
}
return super.onKeyDown(keyCode, event);
}**/
private void doExit() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
FirstSelection.this);
alertDialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.setMessage("Do you want to exit?");
alertDialog.setTitle("something");
alertDialog.show();
}
@Override
public void onStart() {
super.onStart();
//These are my animations
statusAnim.setDuration(800);
colorAnimation.setDuration(1300);
colorAnimation.start();
statusAnim.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
// background process to make a request to server and list product
// information
private class BackTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// pd = new ProgressDialog(context);
// pd.setTitle("Retrieving data");
// pd.setMessage("Please wait.");
// pd.setCancelable(true);
// pd.setIndeterminate(true);
// pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
records.clear();
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"somelink");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); // close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String record = json_data.getString("context") + "__"
+ json_data.getDouble("version");
version = json_data.getDouble("version");
downloadlink = json_data.getString("dlink");
records.add(record);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null)
// pd.dismiss();// close dialog
image.clearAnimation();
image.setVisibility(View.GONE);
adapter.notifyDataSetChanged();// notify the ListView to get new
// records
// statusAnim.setDuration(500);
// statusAnim.start();
// colorAnimation.setDuration(1000);
// colorAnimation.start();
if (oldVer < version) {
ifUpdateAvailable();
}
}
private void ifUpdateAvailable() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
FirstSelection.this);
alertDialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(downloadlink));
request.setDestinationInExternalPublicDir("/Download",
"Something_v1_1.apk");
enqueue = dm.enqueue(request);
}
});
alertDialog.setNegativeButton("Later", null);
alertDialog
.setMessage("A new version of something is available for download. Do you want to update now?");
alertDialog.setTitle("something");
alertDialog.show();
}
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
}
}
}
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
};
}
}
答案 0 :(得分:0)
你不需要这样做。如果首次创建活动,则仅在OnStart()
完成后才会调用onCreate()
。这些方法由android框架按顺序调用。
这里你可以做的是在onStart()
函数中启动重复计时器,检查AsyncTask
是否完成。一旦完成,您就可以开始动画了。您应该在活动的onStop()
方法中停止此计时器。
答案 1 :(得分:0)
我认为正确的方法是使方法同步。 对两个方法执行此操作,它们应该在运行另一个方法之前等待另一个方法完成:
method(){
synchronized(this){
//code
}
}
您可以在此处阅读:http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
当我这样做时,当我有两个线程在同一个类中调用单独的方法时,它对我有效。
解决问题的一种粗略方法是创建private boolean
并在调用onCreate()
方法时将其设置为true,然后在onCreate()
完成时将其设置为false。如果onStart()
为真,您可以在boolean
中返回,或者创建一个像这样的while循环:while(boolean){}
我确信有更好的方法可以做到这一点,但至少可以这样做。
如果可能,您只需在onStart()
onCreate()
方法即可
答案 2 :(得分:0)
在您的情况下,您无法保留onCreate()
,因为AsyncTask doInBackground()
方法在工作线程中运行。
建议:1。
onCreate()
:运行AsyncTask
onStart()
检查AsyncTask状态,检查其是否完成了任务。完成onPostExecte()
方法后开始动画。 3.
当你从SecondActivity
返回如果[onStart()
] AsyncTask完成其任务时,它就会开始动画。
实施例
public class MyActivity extends Activity {
BackTask backTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start AsyncTask
backTask = new BackTask();
backTask.execute();
}
@Override
protected void onStart() {
super.onStart();
if (backTask.getStatus() == Status.FINISHED) {
doAnimation();
}
}
private void doAnimation() {
// start animations
}
class BackTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// do web stuff
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// fetches data now start anim
doAnimation();
}
}
}