如何摆脱编译错误?
sendBroadcast(intent);
此方法在我制作的另一个应用程序中运行良好,但是在当前应用程序中存在编译错误。红色下划线的错误消息“未定义新类型Runnable”
sendBroadcast()是Context类的一部分,而不是Intent类。
public class Server { // external class
public class ServerThread implements Runnable { // nested class
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus = "Listening on IP: " + SERVERIP;
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.setAction("com.example.AudioPlay");
intent.putExtra("serverStatus","Connected");
sendBroadcast(intent);
}
});
<<<<编辑>>>>
我将问题的重点更改为编译错误。该方法在其他应用程序中正常工作。正是在这种特殊情况下,我对编译错误感到困惑。
答案 0 :(得分:3)
用于访问未扩展Activity,服务或其他Application组件的类中的sendBroadcast
方法,您需要使用类构造函数将组件上下文传递给它:
public class ServerThread implements Runnable { // nested class
Context context; //<< declare context here
public ServerThread(Context context){
this.context=context;
}
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.setAction("com.example.AudioPlay");
intent.putExtra("serverStatus","Connected");
// use context for calling sendBroadcast
context.sendBroadcast(intent);
}
});
并传递来自Activity的上下文:
ServerThread serverth=new ServerThread(Your_Current_Activity.this);
答案 1 :(得分:0)
Intent intent = new Intent();
intent.setAction("com.exmaple.AudioPlay");
intent.putExtra("serverStatus","Connected");
mContext.sendBroadcast(intent);
在另一个班级:
Server serv = new Server(getApplicationContext());