我尝试编写一个活动(buildImage),以便自动"关闭"在指定的时间之后。我正在使用CountDown计时器类,但没有成功。它什么都不做,没有错误,或其他任何东西。
问题可能是什么(Looper.prepare()行是为了防止抛出错误)
这是我的代码:
package midamcorp.com.burgerkingapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Looper;
import android.preference.Preference;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import java.io.InputStream;
public class buildImage extends AppCompatActivity {
private SimpleCursorAdapter adapter;
private ImageButton back;
ImageView buildContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_build_image);
super.onCreate(savedInstanceState);
buildContainer = (ImageView) findViewById(R.id.fullSizeImage);
back = (ImageButton) findViewById(R.id.backButton);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new CountDownTimer(1000, 0) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
back.callOnClick();
}
}.start();
}
}).start();
}
protected void onStart() {
super.onStart();
Intent i = getIntent();
if (i.hasExtra("position"))
{
int position = i.getExtras().getInt("position");
int lto = i.getExtras().getInt("lto");
int location = i.getExtras().getInt("location");
gridAdapter adapter = new gridAdapter(this, lto, location);
Bitmap buildImage = BitmapFactory.decodeByteArray(adapter.buildImages.get(position), 0, adapter.buildImages.get(position).length);
buildContainer.setImageBitmap(buildImage);
} else
{
byte[] imageId = i.getByteArrayExtra("imageID");
Bitmap buildImage = BitmapFactory.decodeByteArray(imageId, 0, imageId.length);
buildContainer.setImageBitmap(buildImage);
}
}
}
逻辑上,我认为一旦活动启动就会开始倒计时,然后,在1秒后,调用后退按钮的点击监听器,从而完成活动,但显然不是这样。
非常感谢您的帮助!
答案 0 :(得分:1)
将您的线程代码更改为:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 1000L);
您还必须了解活动生命周期。