2015-04-29 4 views
0

У меня есть два мероприятия и одну услуги все в одном приложенииОбмена между деятельностью и службами

деятельности2 начнет и остановить службу

activity1 является основным UI

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

2- получать данные от активности1 и отправлять его на адрес

проблема я не был в состоянии иметь четкое представление о том, как я могу сделать данные обмена услуг с деятельностью

я прочитал о AIDL, Связывание здесь http://developer.android.com/guide/components/bound-services.html

я не мог применить его на моих кодах, даже после трех недель тяжелой работы я этого не понял !!!

спасибо!

обслуживание:

public class NetService extends Service { 

public static Client client = new Client("192.168.1.5"); 
Thread call; 
BufferedWriter out; 
int a; 
String a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15; 
public static int get = 5; 
Intent intent2; 

NotificationManager mNM; 

private final IBinder mBinder = new LocalBinder(); 

/** 
* Class used for the client Binder. Because we know this service always 
* runs in the same process as its clients, we don't need to deal with IPC. 
*/ 

public class LocalBinder extends Binder { 
    NetService getService() { 
     return NetService.this; 
    } 
} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return mBinder; 
} 


@Override 
public void onCreate() { 
    super.onCreate(); 

    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
    showNotification(); 

} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    a1 ="Hello everyone !!" 

    new Thread(new Runnable(){ 


     public void run() { 

      try { 
       client.connectToServer(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      try { 
       client.setstream(); 
      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } 


      while(true){ 

      try { 
       client.getFromServer(); 
      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } 




      try { 
       out.close(); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 



      try { 
       client.sendToServer(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 


      try { 
       Thread.sleep(2000); 
      } catch (InterruptedException e2) { 
       // TODO Auto-generated catch block 
       e2.printStackTrace(); 
      } 

     } 
     } 

    }).start(); 



    return super.onStartCommand(intent, flags, startId); 
} 

@Override 
public void onDestroy() { 
    client.closeall(); 
    super.onDestroy(); 
} 


private void showNotification() { 
    // In this sample, we'll use the same text for the ticker and the expanded notification 
    CharSequence text = ("remote_service_started"); 
    // Set the icon, scrolling text and timestamp 
    Notification notification = new Notification(R.drawable.togon, text, 
      System.currentTimeMillis()); 
    // The PendingIntent to launch our activity if the user selects this notification 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
      new Intent(this, Connect.class), 0); 
    // Set the info for the views that show in the notification panel. 
    notification.setLatestEventInfo(this, ("remote_service_label"), 
        text, contentIntent); 
    // Send the notification. 
    // We use a string id because it is a unique number. We use it later to cancel. 
    mNM.notify(R.string.remote_service_started, notification); 
}} 

UI активность:

package com.bannob.shms; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 

import com.bannob.shms.NetService.LocalBinder; 

import android.app.Activity; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.graphics.Typeface; 
import android.media.MediaPlayer; 
import android.media.MediaPlayer.OnPreparedListener; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.animation.AccelerateInterpolator; 
import android.view.animation.Animation; 
import android.view.animation.TranslateAnimation; 
import android.widget.ImageButton; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.Switch; 
import android.widget.Toast; 
import android.widget.TextView; 
import android.widget.ToggleButton; 
import android.widget.VideoView; 
import android.widget.ViewFlipper; 




public class Main extends Activity { 

    public static ViewFlipper vf, lightvf, secvf; 
    private Float oldTouchValue; 
    public static TextView tv1, lighttv, sectv, tvlight1, tvlight2, tvlight3, 
    tvlight4, gasactivetv, flameactivetv, mdetect1tv, automodtv, indoortv, hmdtv; 
    public static LinearLayout wallpaper, fansbanner; 
    public static ToggleButton envtog1, envtog2, envtog3, envtog4; 
    public static Switch lights1, lights2, lights3, lights4; 
    public static VideoView vview; 
    public static ImageView safeiv1, safeiv2, seciv1, seciv2, secbubble, safebubble; 
    Typeface tf; 
    BufferedReader in = null; 
    File file; 
    File values; 
    String[] valuesArray= new String[30]; 
    int a; 
    String a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20; 
    NetService mService; 
    boolean mBound = false; 

    /**********************************************************************/ 
    /* Look for the definitions of the previous declarations below !!!! */ 
    /**********************************************************************/ 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); // reference to activity_main.Xml at layout Folder 


     TextView tv1 = (TextView) findViewById() 

     onStart(); 

     tv1.setText(mService.a1); 







    @Override 
    protected void onStart() { 
     super.onStart(); 
     // Bind to LocalService 
     Intent intent = new Intent(this, NetService.class); 
     bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     // Unbind from the service 
     if (mBound) { 
      unbindService(mConnection); 
      mBound = false; 
     } 
    } 

    /** Defines callbacks for service binding, passed to bindService() */ 
    private ServiceConnection mConnection = new ServiceConnection() { 

     @Override 
     public void onServiceConnected(ComponentName className, 
       IBinder service) { 
      // We've bound to LocalService, cast the IBinder and get LocalService instance 
      LocalBinder binder = (LocalBinder) service; 
      mService = binder.getService(); 
      mBound = true; 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName arg0) { 
      mBound = false; 
     } 
    }; 

}  

вторая активность (которая запуска службы):

package com.bannob.shms; 



import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class Connect extends Activity { 

    EditText conet1; 
    Button con ; 
    public static Boolean state = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.connect); 

     con = (Button) findViewById(R.id.conb1); 

     conet1 = (EditText) findViewById(R.id.conet1); 

     con.setOnClickListener(new View.OnClickListener(){   

      public void onClick(View v) { 
       if(state == false){ 
       startService(new Intent(getBaseContext(), NetService.class)); 
       state = true; 
       con.setText("Disconnect"); 

       } 
       else{ 
       stopService(new Intent(getBaseContext(), NetService.class));  
       state = false; 
       con.setText("Connect"); 
       } 


      } 
     }); 
    } 

} 

ответ

0

Рекомендуемый способ
BroadcastReceiver & sendBroadcast

в вас деятельности зарегистрировать BroadcastReciver

IntentFilter newFileReceiverfilter = new IntentFilter(App.INTENT_NEW_FILE_COMMING) ; 
     registerReceiver(newfileReceiver, newFileReceiverfilter); 

     newfileReceiver = new BroadcastReceiver() { 

       @Override 
       public void onReceive(Context arg0, Intent in) { 
            Log.i("FileName", in.getStringExtra(IntentExtrasKeys.NF_FILE_NAME) + ""); 
       } 
       } 

в вас Сервис транслируют Намерение с данными, которые вы хотите передать, как Extra

Intent intent = new Intent(App.INTENT_NEW_FILE_COMMING); 
    intent.putExtra(IntentExtrasKeys.NF_FILE_NAME, "img2.jpg") ; 
    ctx.sendBroadcast(intent); 

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

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