如何在 Android 中与正在运行的线程进行服务通信

发布于 2024-12-28 11:44:34 字数 294 浏览 2 评论 0原文

我的目标是推出一项能够满足所有应用程序网络需求的服务。

我想也许打开2个套接字用于数据传输。我希望异步处理数据,所以我想我应该在两个单独的线程中运行它们,每个线程针对每个套接字,这样数据就可以在两个不同的“链接”异步中进行流式传输。

所以,我会欣赏两件事:

  1. 更好的整体设计。也许我完全弄错了..

  2. 有人可以向我解释一下,一旦我需要将数据传递给主服务或从主服务传递数据,我如何与这些线程进行通信?据我所知(操作系统),我需要使用信号:)(只是开玩笑..)

my goal is to lunch a service that will take care for all of the application network needs.

i thought maybe to open 2 sockets for data transfer. i want the data to be handled asynchronously, so i was thinking my be i should run them in two separated threads, each for every socket, and that way the data could be streamed in two different "links" async..

so, i would appreciate two things:

  1. a better overall design. maybe i completely got it all wrong..

  2. can someone explain to me how can i communicate with those threds once i need to pass data to/from them to/from the main service? as far as i learnt (OS) i need to use SIGNALS:) (just kidding..)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦醒时光 2025-01-04 11:44:34

好吧,我可以说我终于明白了,就在放弃之前。这是一个超级简单的应用程序,它在活动内运行一个线程,并为每个实体使用两个不同的处理程序处理双向通信!

代码:

public class MainActivity extends Activity  {   
//Properties:   
    private final   String TAG = "Activity";            //Log tag
    private         MyThread mThread;                   //spawned thread 
    Bundle          myB = new Bundle();                 //used for creating the msgs
    public          Handler mHandler = new Handler(){   //handles the INcoming msgs 
        @Override public void handleMessage(Message msg) 
        { 
            myB = msg.getData();
            Log.i(TAG, "Handler got message"+ myB.getInt("THREAD DELIVERY")); 
        } 
    }; 
//Methods:
    //--------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        mThread = new MyThread(mHandler);
        mThread.start();
        sendMsgToThread();
    }
    //-------------------------- 
    void sendMsgToThread() 
    { 
        Message msg = mThread.getHandler().obtainMessage(); 
        myB.putInt("MAIN DELIVERY", 321);
        msg.setData(myB);
        mThread.getHandler().sendMessage(msg);
    } 
}
//=========================================================================================
//=========================================================================================

public class MyThread extends Thread{   
//Properties:
    private final   String TAG = "MyThread";            //Log tag
    private         Handler outHandler;                 //handles the OUTgoing msgs 
    Bundle          myB = new Bundle();                 //used for creating the msgs
    private         Handler inHandler = new Handler(){  //handles the INcoming msgs 
        @Override public void handleMessage(Message msg) 
        { 
            myB = msg.getData();
            Log.i(TAG, "Handler got message"+ myB.getInt("MAIN DELIVERY")); 
        } 
    }; 

//Methods:
    //--------------------------
    public void run(){
        sendMsgToMainThread();  //send to the main activity a msg
        Looper.prepare();
        Looper.loop();
        //after this line nothing happens because of the LOOP!
        Log.i(TAG, "Lost message");
    }
    //--------------------------
    public MyThread(Handler mHandler) {
        //C-tor that get a reference object to the MainActivity handler.
        //this is how we know to whom we need to connect with.
        outHandler = mHandler;
    }
    //--------------------------
    public Handler getHandler(){
        //a Get method which return the handler which This Thread is connected with.
        return inHandler;
    }
    //--------------------------    
    private void sendMsgToMainThread(){
        Message msg = outHandler.obtainMessage();   
        myB.putInt("THREAD DELIVERY", 123);
        msg.setData(myB);
        outHandler.sendMessage(msg);
    }
}
//=========================================================================================
//=========================================================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.test.namespace"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

输出是:

01-26 06:25:40.683: I/Activity(19560): Handler got message123
01-26 06:25:40.683: I/MyThread(19560): Handler got message321

我在阅读 endian 提供的帖子时发现了这一点, 这里

我希望其他人会发现这很有用。祝你好运:)

Well, I can say i finally got it, just before giving up. Here is a super duper extremely simple app that runs a thread inside an activity and handles a bi-directional communication using two different Handlers for each entity!

The code:

public class MainActivity extends Activity  {   
//Properties:   
    private final   String TAG = "Activity";            //Log tag
    private         MyThread mThread;                   //spawned thread 
    Bundle          myB = new Bundle();                 //used for creating the msgs
    public          Handler mHandler = new Handler(){   //handles the INcoming msgs 
        @Override public void handleMessage(Message msg) 
        { 
            myB = msg.getData();
            Log.i(TAG, "Handler got message"+ myB.getInt("THREAD DELIVERY")); 
        } 
    }; 
//Methods:
    //--------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        mThread = new MyThread(mHandler);
        mThread.start();
        sendMsgToThread();
    }
    //-------------------------- 
    void sendMsgToThread() 
    { 
        Message msg = mThread.getHandler().obtainMessage(); 
        myB.putInt("MAIN DELIVERY", 321);
        msg.setData(myB);
        mThread.getHandler().sendMessage(msg);
    } 
}
//=========================================================================================
//=========================================================================================

public class MyThread extends Thread{   
//Properties:
    private final   String TAG = "MyThread";            //Log tag
    private         Handler outHandler;                 //handles the OUTgoing msgs 
    Bundle          myB = new Bundle();                 //used for creating the msgs
    private         Handler inHandler = new Handler(){  //handles the INcoming msgs 
        @Override public void handleMessage(Message msg) 
        { 
            myB = msg.getData();
            Log.i(TAG, "Handler got message"+ myB.getInt("MAIN DELIVERY")); 
        } 
    }; 

//Methods:
    //--------------------------
    public void run(){
        sendMsgToMainThread();  //send to the main activity a msg
        Looper.prepare();
        Looper.loop();
        //after this line nothing happens because of the LOOP!
        Log.i(TAG, "Lost message");
    }
    //--------------------------
    public MyThread(Handler mHandler) {
        //C-tor that get a reference object to the MainActivity handler.
        //this is how we know to whom we need to connect with.
        outHandler = mHandler;
    }
    //--------------------------
    public Handler getHandler(){
        //a Get method which return the handler which This Thread is connected with.
        return inHandler;
    }
    //--------------------------    
    private void sendMsgToMainThread(){
        Message msg = outHandler.obtainMessage();   
        myB.putInt("THREAD DELIVERY", 123);
        msg.setData(myB);
        outHandler.sendMessage(msg);
    }
}
//=========================================================================================
//=========================================================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.test.namespace"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

the output is:

01-26 06:25:40.683: I/Activity(19560): Handler got message123
01-26 06:25:40.683: I/MyThread(19560): Handler got message321

I figured this out while reading the offered post by endian, here.

I hope others will find this useful. good luck:)

恍梦境° 2025-01-04 11:44:34

这里是很好的帖子,解释了线程和通信处理程序。此外,同一博客还有许多关于 Android 中各种线程构造的帖子。

另一种可能性是使用 AsyncTasks。 此处查找一些说明

Here is good post explaining threads and communication using handlers. Also, the same blog has a number of posts regarding various thread constructs in Android.

Another possibility is to use AsyncTasks. Find some explanation here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文