How to communicate a service with a running thread in Android

删除回忆录丶 提交于 2019-12-12 20:13:08

问题


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..)


回答1:


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:)




回答2:


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



来源:https://stackoverflow.com/questions/8989099/how-to-communicate-a-service-with-a-running-thread-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!