处理程序是抽象的,不能实例化

我试图在我的应用程序中使用 Handler,但是,当我像这样实例化它时:

Handler handler = new Handler();

我得到以下错误:

Error: Handler 是抽象的; 不能实例化

当我检查解决方案时,它要求我实现这些方法:

Handler handler = new Handler() {
@Override
public void close() {
        

}


@Override
public void flush() {


}


@Override
public void publish(LogRecord record) {


}
};

我从来没有使用过 Handlers之前,我使用它只是为了调用一个方法后,一些延迟。为了达到这个目的,我使用了:

handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);

但它表明了一个错误:

错误: 无法找到符号方法 postDelayed (,int)

57814 次浏览

It seems you have imported a wrong Handler class

import java.util.logging.Handler;

Change it to

import android.os.Handler;
    import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class ActionActivity extends ActionBarActivity {


final String LOG_TAG = "myLogs";
TextView tvInfo;
Button btnStart;
Handler h;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setContentView(R.layout.action_activity);
tvInfo = (TextView)findViewById(R.id.tvinfo);
btnStart = (Button)findViewById(R.id.btnstart);


h = new Handler() {
public void handleMessage(android.os.Message msg) {
// update TextView
tvInfo.setText("Закачано файлов: " + msg.what);
if (msg.what == 10) btnStart.setEnabled(true);
};
};


}


public void onclick(View v) {
switch (v.getId()) {
case R.id.btnstart:
btnStart.setEnabled(false);
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 10; i++) {
// some process
downloadFile();
h.sendEmptyMessage(i);


Log.d(LOG_TAG, "i = " + i);
}
}
});
t.start();
break;
case R.id.btnTets:
Log.d(LOG_TAG, "test");
break;
default:
break;
}
}


public void downloadFile(){
try{
TimeUnit.SECONDS.sleep(1);
}
catch (InterruptedException e){
e.printStackTrace();
};
}
}

In Place Of

import java.util.logging.Handler;

add

import android.os.Handler;

also if you use

Handler handler = new Handler() {
@Override
public void close() {


}


@Override
public void flush() {


}


@Override
public void publish(LogRecord record) {


}
};

it will give error that boolean found somthing like error so either use boolean handler = new Handler()... or simply use (new Handler()){....`

import android.os.Handler; this the handler needed for your purpous. Before importing the Handler class please try to import the above.

Android SDK auto imports the incorrect one. That's why people have problems.

It seems like you have implemented the wrong Handler class

import java.util.logging.Handler;

Change it to

import android.os.Handler;