(vi) Service communication in Android

Source: Internet
Author: User

First, to start the service and pass parameter pass parameter, only need to pass in the data in the intent that StartService starts, can receive the parameter in the Onstartcommand function by reading the content of intent of the initial parameter to implement 1. Mainactivity.java
Package com.example.shiyanshi.serviceconnected;

Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;
Import Android.widget.EditText;


public class Mainactivity extends Activity implements View.onclicklistener {
Private EditText EditText;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

edittext= (EditText) Findviewbyid (R.id.edittext);
Findviewbyid (R.id.btnstartservice). Setonclicklistener (this);
Findviewbyid (R.id.btnstopservice). Setonclicklistener (this);
}

@Override
public void OnClick (view view) {
Switch (View.getid ()) {
Case R.id.btnstartservice:
Intent intent=new Intent (mainactivity.this,myservice.class);
Intent.putextra ("Data", Edittext.gettext (). toString ());
StartService (Intent);
Break
Case R.id.btnstopservice:
StopService (New Intent (Mainactivity.this,myservice.class));
}

}
}
2.myservice.java
Package com.example.shiyanshi.serviceconnected;

Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;

public class MyService extends Service {
Private String data;
Private Boolean flag;

Public MyService () {
}

@Override
Public IBinder Onbind (Intent Intent) {
Todo:return the communication channel to the service.
throw new Unsupportedoperationexception ("not yet implemented");
}

@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {

Data=intent.getstringextra ("Data");
Return Super.onstartcommand (Intent, flags, Startid);
}

@Override
public void OnCreate () {
Super.oncreate ();
Flag=true;
New Thread () {
@Override
public void Run () {
Super.run ();
while (flag) {
SYSTEM.OUT.PRINTLN (data);
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}.start ();
}

@Override
public void OnDestroy () {
Super.ondestroy ();
Flag=false;
}
}
3. Layout files
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
xmlns:tools= "Http://schemas.android.com/tools" android:layout_width= "Match_parent"
android:layout_height= "Match_parent" android:paddingleft= "@dimen/activity_horizontal_margin"
android:paddingright= "@dimen/activity_horizontal_margin"
android:paddingtop= "@dimen/activity_vertical_margin"
android:orientation= "Vertical"
android:paddingbottom= "@dimen/activity_vertical_margin" tools:context= ". Mainactivity ">

<edittext android:text= "@string/hello_world" android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:id= "@+id/edittext"/>

<button
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Start Service"
Android:id= "@+id/btnstartservice"/>

<button
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Stop Service"
Android:id= "@+id/btnstopservice"/>

</LinearLayout>

Second, binding Service for communication (1) After the activity passes the message binding service The activity and service can communicate through Android.os.Binder, and when the service is bound, the OnCreate function is called first, and then the Onbind function of the service class is called to return a binder, which is then invoked to implement the Onserv in the activity class. The iceconnected function, the second parameter of the function, IBinder IBinder is the return value of the Onbind method in the service class, and the binder can communicate successfully. 1.mainactivity.java
Package com.example.shiyanshi.serviceconnected;

Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;
Import Android.widget.EditText;


public class Mainactivity extends Activity implements View.onclicklistener, Serviceconnection {
Private EditText EditText;
Private Myservice.binder Binder=null;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

edittext= (EditText) Findviewbyid (R.id.edittext);
Findviewbyid (R.id.btnstartservice). Setonclicklistener (this);
Findviewbyid (R.id.btnstopservice). Setonclicklistener (this);
Findviewbyid (R.id.btnbindservice). Setonclicklistener (this);
Findviewbyid (R.id.btnunbindservice). Setonclicklistener (this);
Findviewbyid (R.id.btnsyncdata). Setonclicklistener (this);

}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.menu_main, menu);
return true;
}

@Override
public boolean onoptionsitemselected (MenuItem item) {
Handle Action Bar Item clicks here. The Action Bar would
Automatically handle clicks on the Home/up button, so long
As you specify a the parent activity in Androidmanifest.xml.
int id = item.getitemid ();

Noinspection simplifiableifstatement
if (id = = r.id.action_settings) {
return true;
}

return super.onoptionsitemselected (item);
}

@Override
public void OnClick (view view) {
Switch (View.getid ()) {
Case R.id.btnstartservice:
Intent intent=new Intent (mainactivity.this,myservice.class);
Intent.putextra ("Data", Edittext.gettext (). toString ());
StartService (Intent);
Break
Case R.id.btnstopservice:
StopService (New Intent (Mainactivity.this, Myservice.class));
Break
Case R.id.btnbindservice:
Bindservice (New Intent (Mainactivity.this, Myservice.class), this, context.bind_auto_create);
Break
Case R.id.btnunbindservice:
Unbindservice (this);
Break
Case R.id.btnsyncdata:
if (binder!=null) {
System.out.println ("Bind in NOT NULL");
Binder.setdata (Edittext.gettext (). toString ()); Invoking the data interaction method implemented in bind
}
Break
}

}

@Override
public void onserviceconnected (ComponentName componentname, IBinder ibinder) {
System.out.println ("*****connected successful*******");
Binder= (Myservice.binder) IBinder;
}

@Override
public void onservicedisconnected (ComponentName componentname) {
System.out.println ("*****disconnected successful*******");

}
}
2.myservice.java
Package com.example.shiyanshi.serviceconnected;

Import Android.app.Service;
Import android.content.Intent;
Import Android.os.Binder;
Import Android.os.IBinder;

public class MyService extends Service {
Private String data= "default Info";
Private Boolean flag;

Public MyService () {
}

@Override
Public IBinder Onbind (Intent Intent) {
Todo:return the communication channel to the service.
throw new Unsupportedoperationexception ("not yet implemented");
return new Binder (); The return value is passed to the second parameter of the onserviceconnected function IBinder
}
This class is an interface for activity and service to interact with data

public class Binder extends android.os.binder{
public void SetData (String data) {
Myservice.this.data=data;
}

}

@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {

Data=intent.getstringextra ("Data");
Return Super.onstartcommand (Intent, flags, Startid);
}

@Override
public void OnCreate () {
Super.oncreate ();
System.out.println ("*******oncreate********");
Flag=true;
New Thread () {
@Override
public void Run () {
Super.run ();
while (flag) {
SYSTEM.OUT.PRINTLN (data);
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}.start ();
}

@Override
public void OnDestroy () {
Super.ondestroy ();
System.out.println ("******ondestroy******");
Flag=false;
}
}
(2) The service transmits messages to the activity and displays the data passed to the activity primarily by setting a callback function in the service interface, and defining a reference to that interface, which is instantiated in the activity, Instantiating a callback function that is defined in the interface, causes the callback function to send a message, updates the contents of the UI thread in the Message Processor (Handler), and invokes the callback function in the newly-opened thread thread to update the data. 1.mainactivity.java
Package com.example.shiyanshi.serviceconnected;

Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import Android.os.Message;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;
Import Android.widget.EditText;
Import Android.widget.TextView;

Import Org.w3c.dom.Text;

Import Java.util.logging.Handler;


public class Mainactivity extends Activity implements View.onclicklistener, Serviceconnection {
Private EditText EditText;
Private Myservice.binder Binder=null;
Private TextView tvout;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

edittext= (EditText) Findviewbyid (R.id.edittext);
tvout= (TextView) Findviewbyid (r.id.tvout);

Findviewbyid (R.id.btnstartservice). Setonclicklistener (this);
Findviewbyid (R.id.btnstopservice). Setonclicklistener (this);
Findviewbyid (R.id.btnbindservice). Setonclicklistener (this);
Findviewbyid (R.id.btnunbindservice). Setonclicklistener (this);
Findviewbyid (R.id.btnsyncdata). Setonclicklistener (this);

}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.menu_main, menu);
return true;
}

@Override
public boolean onoptionsitemselected (MenuItem item) {
Handle Action Bar Item clicks here. The Action Bar would
Automatically handle clicks on the Home/up button, so long
As you specify a the parent activity in Androidmanifest.xml.
int id = item.getitemid ();

Noinspection simplifiableifstatement
if (id = = r.id.action_settings) {
return true;
}

return super.onoptionsitemselected (item);
}

@Override
public void OnClick (view view) {
Switch (View.getid ()) {
Case R.id.btnstartservice:
Intent intent=new Intent (mainactivity.this,myservice.class);
Intent.putextra ("Data", Edittext.gettext (). toString ());
StartService (Intent);
Break
Case R.id.btnstopservice:
StopService (New Intent (Mainactivity.this, Myservice.class));
Break
Case R.id.btnbindservice:
Bindservice (New Intent (Mainactivity.this, Myservice.class), this, context.bind_auto_create);
Break
Case R.id.btnunbindservice:
Unbindservice (this);
Break
Case R.id.btnsyncdata:
if (binder!=null) {
System.out.println ("Bind in NOT NULL");
Binder.setdata (Edittext.gettext (). toString ());
}
Break
}

}

@Override
public void onserviceconnected (ComponentName componentname, IBinder ibinder) {
System.out.println ("*****connected successful*******");
Binder= (Myservice.binder) IBinder;
        Set the callback function to modify the contents of the UI thread to be displayed by sending messages and message handlers in the callback function
Binder.getservice (). Setcallback (New Myservice.callback () {
@Override
public void OnDataChange (String data) {
Tvout.settext (data); This cannot be set directly because the newly created thread calls this function and does not allow direct modification of the contents of the UI thread
Message msg=new message ();
Bundle Bundle=new Bundle ();
Bundle.putstring ("Data", data);
Msg.setdata (bundle);
Handler.sendmessage (msg); Sending messages via handler
}
});
}

@Override
public void onservicedisconnected (ComponentName componentname) {
System.out.println ("*****disconnected successful*******");

}
    A message handler that receives a message and processes it

Private Android.os.Handler handler=new Android.os.Handler () {
@Override
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
Tvout.settext (Msg.getdata (). getString ("Data"));

}
};
}
2.myservice.java
Package com.example.shiyanshi.serviceconnected;

Import Android.app.Service;
Import android.content.Intent;
Import Android.os.Binder;
Import Android.os.IBinder;

public class MyService extends Service {
Private String data= "default Info";
Private Boolean flag;

Public MyService () {
}

@Override
Public IBinder Onbind (Intent Intent) {
Todo:return the communication channel to the service.
throw new Unsupportedoperationexception ("not yet implemented");
System.out.println ("******onbind*****");
return new Binder (); The return value is passed to the second parameter of the onserviceconnected function IBinder
}
This class is an interface for activity and service to interact with data
public class Binder extends android.os.binder{
public void SetData (String data) {
Myservice.this.data=data;
}

Gets a reference to the current MyService class
Public MyService GetService () {
return myservice.this;
}

}

@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {

Data=intent.getstringextra ("Data");
Return Super.onstartcommand (Intent, flags, Startid);
}

@Override
public void OnCreate () {
Super.oncreate ();
System.out.println ("*******oncreate********");
Flag=true;

New Thread () {
@Override
public void Run () {
Super.run ();
int i=0;
while (flag) {
i++;
String str=i+ ":" +data;
System.out.println (str);

This function is called by the newly created thread, and the contents of the UI thread are not allowed to be modified directly
if (callback!=null) {
Callback.ondatachange (str);
}
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}.start ();
}

@Override
public void OnDestroy () {
Super.ondestroy ();
System.out.println ("******ondestroy******");
Flag=false;
}
    The interface created is used for callbacks, and the callback function (OnDataChange) is specifically implemented in the activity


Private Callback Callback=null;

public void Setcallback (Callback Callback) {
This.callback = callback;
}

Public Callback Getcallback () {
return callback;
}

public static Interface callback{
void OnDataChange (String data);
}








}


(vi) Service communication in Android

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.