2014-02-15 4 views
0

привет Я новичок в андроида кодирования, мне нужен пример программы, которые читают данные с акселерометра и отправлять их через Wi-Fi на моем компьютереЗапускать несколько классов за одно и то же время?

я имею программу акселерометр, который работает отлично, а также программу, передачу данных через Wi-Fi на мой компьютер

так что проблема в том, что я не знаю, как совместить эти две программ в результате я надеюсь, что класс акселерометра работать в фоновом режиме и вернуть й и у значения основной программы, которые посылают их

акселерометр класс

public class MainActivity extends Activity implements SensorEventListener { 
     private SensorManager mSensorManager; 
     private Sensor mAccelerometer; 

     TextView title,tv,tv1,tv2; 
     RelativeLayout layout; 

     @Override 
     public final void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 
     mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 

     //get layout 
     layout = (RelativeLayout)findViewById(R.id.relative); 

     //get textviews 
     title=(TextView)findViewById(R.id.name); 
     tv=(TextView)findViewById(R.id.xval); 
     tv1=(TextView)findViewById(R.id.yval); 
     tv2=(TextView)findViewById(R.id.zval); 


     } 

     @Override 
     public final void onAccuracyChanged(Sensor sensor, int accuracy) 
     { 
     // Do something here if sensor accuracy changes. 
     } 

     @Override 
     public final void onSensorChanged(SensorEvent event) 
     { 
     // Many sensors return 3 values, one for each axis. 
     float x = event.values[0]; 
     float y = event.values[1]; 
     float z = event.values[2]; 


     //display values using TextView 
     title.setText(R.string.app_name); 
     tv.setText("X axis" +"\t\t"+x); 
     tv1.setText("Y axis" + "\t\t" +y); 
     tv2.setText("Z axis" +"\t\t" +z); 

     } 

     @Override 
     protected void onResume() 
     { 
     super.onResume(); 
     mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); 
     } 

     @Override 
     protected void onPause() { 
     super.onPause(); 
     mSensorManager.unregisterListener(this); 
     } 
    } 

WiFi класс связи

package net.client; 

import eneter.messaging.diagnostic.EneterTrace; 
import eneter.messaging.endpoints.typedmessages.*; 
import eneter.messaging.messagingsystems.messagingsystembase.*; 
import eneter.messaging.messagingsystems.tcpmessagingsystem.TcpMessagingSystemFactory; 
import eneter.net.system.EventHandler; 
import android.R.string; 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.*; 

public class AndroidNetCommunicationClientActivity extends Activity 
{ 
    Thread anOpenConnectionThread = new Thread(); 
    boolean bool = false; 
    // Request message type 
    // The message must have the same name as declared in the service. 
    // Also, if the message is the inner class, then it must be static. 
    public static class MyRequest 
    { 
     public String Text; 
    } 

    // Response message type 
    // The message must have the same name as declared in the service. 
    // Also, if the message is the inner class, then it must be static. 
    public static class MyResponse 
    { 
     public int Length; 
    } 

    // UI controls 
    private Handler myRefresh = new Handler(); 
    private EditText myMessageTextEditText; 
    private EditText myResponseEditText; 
    private Button mySendRequestBtn , mbutton1; 


    // Sender sending MyRequest and as a response receiving MyResponse. 
    private IDuplexTypedMessageSender<MyResponse, MyRequest> mySender; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     // Get UI widgets. 
     myMessageTextEditText = (EditText) findViewById(R.id.messageTextEditText); 
     myResponseEditText = (EditText) findViewById(R.id.messageLengthEditText); 
     mySendRequestBtn = (Button) findViewById(R.id.sendRequestBtn); 
     mbutton1 = (Button) findViewById(R.id.button1); 
     // Subscribe to handle the button click. 
     mySendRequestBtn.setOnClickListener(myOnSendRequestClickHandler); 
     mbutton1.setOnClickListener(bot); 
     // Open the connection in another thread. 
     // Note: From Android 3.1 (Honeycomb) or higher 
     //  it is not possible to open TCP connection 
     //  from the main thread. 


    } 

    @Override 
    public void onDestroy() 
    { 
     // Stop listening to response messages. 
     mySender.detachDuplexOutputChannel(); 

     super.onDestroy(); 
    } 

    private void openConnection() throws Exception 
    { 
     // Create sender sending MyRequest and as a response receiving MyResponse 
     IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory(); 
     mySender = aSenderFactory.createDuplexTypedMessageSender(MyResponse.class, MyRequest.class); 

     // Subscribe to receive response messages. 
     mySender.responseReceived().subscribe(myOnResponseHandler); 

     // Create TCP messaging for the communication. 
     // Note: 10.0.2.2 is a special alias to the loopback (127.0.0.1) 
     //  on the development machine. 
     IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory(); 
     IDuplexOutputChannel anOutputChannel 
      = aMessaging.createDuplexOutputChannel("tcp://192.168.43.44:8060/"); 
      //= aMessaging.createDuplexOutputChannel("tcp://192.168.1.102:8060/"); 

     // Attach the output channel to the sender and be able to send 
     // messages and receive responses. 
     mySender.attachDuplexOutputChannel(anOutputChannel); 
    } 

    private void onSendRequest(View v) 
    { 
     // Create the request message. 
     final MyRequest aRequestMsg = new MyRequest(); 
     aRequestMsg.Text = myMessageTextEditText.getText().toString(); 

     // Send the request message. 
     try 
     { 
      mySender.sendRequestMessage(aRequestMsg); 
     } 
     catch (Exception err) 
     { 
      EneterTrace.error("Sending the message failed.", err); 
     } 

    } 

    private void onResponseReceived(Object sender, 
            final TypedResponseReceivedEventArgs<MyResponse> e) 
    { 
     // Display the result - returned number of characters. 
     // Note: Marshal displaying to the correct UI thread. 
     myRefresh.post(new Runnable() 
      { 
       @Override 
       public void run() 
       { 
        myResponseEditText.setText(Integer.toString(e.getResponseMessage().Length)); 
       } 
      }); 
    } 

    private EventHandler<TypedResponseReceivedEventArgs<MyResponse>> myOnResponseHandler 
      = new EventHandler<TypedResponseReceivedEventArgs<MyResponse>>() 
    { 
     @Override 
     public void onEvent(Object sender, 
          TypedResponseReceivedEventArgs<MyResponse> e) 
     { 
      onResponseReceived(sender, e); 
     } 
    }; 

    private OnClickListener myOnSendRequestClickHandler = new OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 

      onSendRequest(v); 
     } 
    }; 
    private OnClickListener bot = new OnClickListener() 
    { 
     @Override 
     public void onClick(View v) { 
      Thread anOpenConnectionThread = new Thread(new Runnable() 
      { 
       @Override 
       public void run() 
       { 
        try 
        { 
         openConnection(); 
        } 
        catch (Exception err) 
        { 
         EneterTrace.error("Open connection failed.", err); 
        } 
       } 
      }); 


       anOpenConnectionThread.start(); 





      } 
    }; 
} 

спасибо и простите мой бедный английский

+0

Ах, скопируйте функции одного вида деятельности в другой? –

ответ

0

Может попробовать просто скопировать и вставить одну в другую. Насколько мне известно, вы можете иметь несколько классов в одном файле, по крайней мере, в той программе, которую я использую. Если вы можете сделать это, вы сможете запустить один файл, и оба класса будут использоваться одновременно.

Смежные вопросы