我尝试根据用户Kapil Vats的代码编写一种蓝牙服务,该服务在后台运行并可以与应用程序中的任何Activity通信。[How to move Bluetooth activity into a Service 服务工作,但我没有收到消息。
我在MyApplication类中具有Handler,在AbstractActivity中具有Handler.Callback。
公共类MyApplication扩展了Application {
Handler.Callback realCallback = null;
@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (realCallback != null) {
realCallback.handleMessage(msg);
}
};
};
public Handler getHandler() {
return handler;
}
public void setCallBack(Handler.Callback callback) {
this.realCallback = callback;
}
}
公共抽象类AbstractActivity扩展了AppCompatActivity {
public static final int MESSAGE_STATE_CHANGE = 1 ;
public static final int MESSAGE_WRITE = 2;
public static final int MESSAGE_READ = 3 ;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5 ;
public static final String TOAST = "toast";
public static final String DEVICE_NAME = "device_name" ;
private static final String TAG = "BTSERVICE";
abstract void printReadMessage(String readMessage);
abstract void printWriteMessage(String readMessage);
Handler.Callback callback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case 1:
Toast.makeText(getApplicationContext(), getResources().
getText(R.string.connecting),
Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
printWriteMessage(writeMessage);
Log.d(TAG, writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
printReadMessage(readMessage);
Log.d(TAG, readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
String mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), getResources().
getText(R.string.con_to) + mConnectedDeviceName,
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
return true;
}
};
我看到setActivBack(Handler.Callback callback)和AbstractActivity中的回调从未使用过。我在这样的AbstractActivity集合中尝试: (((MyApplication)getApplication).setCallBack(callback),但这是错误的。 请说明如何实现setCallback方法?