不要在API 26+的Android设备上显示套接字消息

时间:2019-04-17 07:48:48

标签: java android sockets serversocket

我已经在较旧的设备API版本上测试了我的应用,并显示了套接字消息。但是在26+版本上不起作用。我不明白为什么我的功能在新版本中不起作用。

SocketMessageReceiver.java

public class SocketMessageReceiver extends BroadcastReceiver {

    interface ISocketMessageReceiver {
        void sendSocketMessage(String socketMessage);
    }

    private static ISocketMessageReceiver iSocketMessageReceiver;
    private final String TAG = "DEBUG";

    @Override
    public void onReceive(Context context, Intent intent) {
            iSocketMessageReceiver.sendSocketMessage(intent.getBundleExtra(SocketService.BUNDLE_DATA_KEY_VALUE).getString(SocketService.BUNDLE_DATA_KEY_VALUE));
    }

    public void registerCallback(ISocketMessageReceiver iSocketMessageReceiver) {
        this.iSocketMessageReceiver = iSocketMessageReceiver;
    }

}

在我的MainActivity.java中

public void sendSocketMessage(String socketMessage) {
    lblMessage.setText(socketMessage);
    setNotificationMessage(socketMessage, "Порака") ;
}

更新:我在onCreate中添加了BroadcasReceiver,还需要进行哪些其他更改?

private static SocketMessageReceiver.ISocketMessageReceiver iSocketMessageReceiver;

private ISocketInterface iSocketInterface;

private SocketMessageReceiver socketMessageReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    BroadcastReceiver br = new SocketMessageReceiver();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    this.registerReceiver(br, filter);

    iSocketMessageReceiver = this;

    socketMessageReceiver = new SocketMessageReceiver();
    socketMessageReceiver.registerCallback(iSocketMessageReceiver);
}

1 个答案:

答案 0 :(得分:1)

我不确定是否是这种情况,但是您可能正在清单中注册接收者。

Android O introduced在注册广播接收方方面有一些限制-通常,除了某些exceptions之外,您无法在清单中注册隐式接收方。

因此,您必须在runtime期间注册接收者,或者坚持使用明确的广播(可以通过setting intent's target component完成)。

更新

您正在这里注册接收者

this.registerReceiver(br, filter);

但是之后,您要创建SocketMessageReceiver的新实例并在其上调用registerCallback()

我认为您想要做的是在注册接收广播的同一实例上调用registerCallback()。另外,ISocketMessageReceiver几乎不需要为Activity设置变量。

您活动中的相关代码可能像这样

class MyActivity extends AppCompatActivity 
    implements SocketMessageReceiver.ISocketMessageReceiver {

    private SocketMessageReceiver mSocketReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mSocketReceiver = new SocketMessageReceiver();
        mSocketReceiver.registerCallback(this);

        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        registerReceiver(mSocketReceiver, filter);
    }
}

当然,您必须要小心,并根据活动的生命周期回调将您的活动注销为SocketMessageReceiver回调。

无论如何,这段代码只是为了说明这个想法,因此,我不建议您在应用中直接使用它。