android - Exchange between activity and a service -


i have 2 activities , 1 service in 1 app

activity2 start , stop service

activity1 main ui

the service have 2 supposed tasks: 1- receive data server though socket , pass activity1 update user interface

2- receive data activity1 , send sever

the problem wasn't able have clear idea how can make service exchange data activity

i read aidl , binding here http://developer.android.com/guide/components/bound-services.html

i couldn't apply on codes, after 3 weeks of hard work didn't !!!

thank !

service:

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 = 5; intent intent2;  notificationmanager mnm;  private final ibinder mbinder = new localbinder();  /**  * class used client binder.  because know service  * runs in same process clients, don't need deal 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 !!"      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 sample, we'll use same text ticker , expanded notification     charsequence text = ("remote_service_started");     // set icon, scrolling text , timestamp     notification notification = new notification(r.drawable.togon, text,             system.currenttimemillis());     // pendingintent launch our activity if user selects notification     pendingintent contentintent = pendingintent.getactivity(this, 0,             new intent(this, connect.class), 0);     // set info views show in notification panel.     notification.setlatesteventinfo(this, ("remote_service_label"),                    text, contentintent);     // send notification.     // use string id because unique number.  use later cancel.     mnm.notify(r.string.remote_service_started, notification); }} 

ui activity :

    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;      /**********************************************************************/     /* definitions of previous declarations below !!!!   */     /**********************************************************************/       @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);  // reference activity_main.xml @ layout folder           textview tv1 = (textview) findviewbyid ()          onstart();          tv1.settext(mservice.a1);            @override     protected void onstart() {         super.onstart();         // bind localservice         intent intent = new intent(this, netservice.class);         bindservice(intent, mconnection, context.bind_auto_create);     }      @override     protected void onstop() {         super.onstop();         // unbind service         if (mbound) {             unbindservice(mconnection);             mbound = false;         }     }      /** defines callbacks service binding, passed bindservice() */     private serviceconnection mconnection = new serviceconnection() {          @override         public void onserviceconnected(componentname classname,                 ibinder service) {             // we've bound localservice, cast ibinder , localservice instance             localbinder binder = (localbinder) service;             mservice = binder.getservice();             mbound = true;         }          @override         public void onservicedisconnected(componentname arg0) {             mbound = false;         }     };  }     

second activity (which start service):

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");                 }               }         });     }  } 

recommended way
broadcastreceiver & sendbroadcast

in activities register 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) + "");                 }                 } 

in service broadcast intent data want send extra

intent intent = new intent(app.intent_new_file_comming);      intent.putextra(intentextraskeys.nf_file_name, "img2.jpg" ) ;      ctx.sendbroadcast(intent); 

send more data service activities send more intents
there dirty way
u can let service write vaule in static class , read static class activities


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -