在android中的一个Thread和两个Activity之间发送数据

时间:2017-01-26 03:11:40

标签: java android multithreading bluetooth

我有一个thread来监听inputStream并且可以发送一些数据,其中包含我从蓝牙套接字获得的一些ouputStream

以下是我要实现的目标:我有MainActvityActivity B。我需要让两者都能够从Thread接收数据或将数据发送到Thread

我不能只创建我的线程的新实例,因为它会切断连接。

我是Android和编程的新手,所以很难知道我真正需要什么。

我尽力使用处理程序,广播接收器但没有运气让它在Activity B中运行。 无论什么对我的情况都有用。有一个例子就好了。

1 个答案:

答案 0 :(得分:0)

您可以在运行您的线程的服务中使用LocalBroadcastManager,并让活动在其上注册接收器。

在您的活动中:

class CodeBlock(StructBlock):
    LANGUAGE_CHOICES = (
        ('aspx-cs', '.NET ASP/C#'),
        ('aspx-vb', '.NET ASP/VisualBasic'),
        ('csharp', '.NET C#'),
        ('fsharp', '.NET F#'),
        ('vbnet', '.NET VisualBasic'),
        ('ng2', 'Angular 2'),
        ('html+ng2', 'Angular 2 Html'),
        ('apache', 'Apache Config'),
        ('arduino', 'Arduino Sketch'),
        ('asm', 'Assembly'),
        ('bash', 'Bash Shell'),
        ('batch', 'Batch CMD File'),
        ('c', 'C'),
        ('cpp', 'C++'),
        ('cmake', 'CMake'),
        ('coffeescript', 'Coffee Script'),
        ('css', 'CSS'),
        # ... and many, many more ...
        ('vhdl', 'Vhdl'),
        ('registry', 'Windows Registry'),
        ('xml', 'XML'),
        ('xml+php', 'XML/PHP'),
        ('xslt', 'XSLT'),
        ('yaml', 'Yaml'),
    )

    COLORIZER_CHOICES = (
        ('abap', 'Abap'),
        ('algol', 'Algol'),
        ('algol_nu', 'Algol Nu'),
        # ... finish the list with all the highlight styles in the current version of pygments
        ('vs', 'Vs'),
        ('xcode', 'Xcode'),
    )

    language = ChoiceBlock(choices=LANGUAGE_CHOICES, classname='full')
    colors = ChoiceBlock(choices=COLORIZER_CHOICES, classname='full')
    code = TextBlock()
    line_numbers = BooleanBlock(classname='full')

    class Meta:
        icon = 'code'

    def render(self, value, context=None):
        src = value['code'].strip('\n');
        lang = value['language']
        line_nos = value['line_numbers']

        lexer = get_lexer_by_name(lang)
        formatter = get_formatter_by_name('html', linenos='table' if line_nos else False, cssclass='codehilite', style='default',noclasses=False)
        return mark_safe(highlight(src, lexer, formatter))

在您的服务中

    final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getApplicationContext());
    final IntentFilter filter = new IntentFilter();
    filter.addAction("SAMPLE_ACTION");
    lbm.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive() called with: context = [" + context + "], intent = [" + intent + "]");
        }
    }, filter);