This article describes the Android implementation of the activity, service and broadcaster of the three major components of the method of calling each other. Share to everyone for your reference, specific as follows:
We look at two problems,
1, service How to change the activity of a textview through broadcaster.
(Study this issue, taking msg back to the activity after the service gets the message from the server side)
2, how the activity through binder call a method of service.
(Study this problem, consider the action that interacts with server side, package to service,activity only render interface, invoke service method)
See the structure diagram below:
The effect chart is as follows:
Click the "Start Service" button to start the service and change the UI of the activity.
Click the "Send msg to Server" button to invoke the service method to display the Notificationbar
Code:
1, a new MyService class, inherit service
Package com.ljq.activity;
Import android.app.Notification;
Import Android.app.NotificationManager;
Import android.app.PendingIntent;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import Android.graphics.Color;
Import Android.os.Binder;
Import Android.os.IBinder;
public class MyService extends Service {private Notificationmanager notificationmanager = null;
Private final IBinder binder = new Localbinder ();
@Override public void OnCreate () {sendmsgtoactivty (' Service is oncreating.\n '); @Override public IBinder onbind (Intent Intent) {String msg = ' activity is sendding ' to service,\n service Sen
D msg to server!\n ";
Sendmsgtoactivty (msg);
return binder; /** * transmits information to activity * * @param msg/private void Sendmsgtoactivty (String msg) {Intent Intent = new Intent ("Co
M.android.yao.msg ");
Intent.putextra ("msg", MSG);
This.sendbroadcast (Intent);
@Override public void OnDestroy () {Super.ondestroy (); if (NotifiCationmanager!=null) {notificationmanager.cancel (0);
Notificationmanager=null; }/** * Displays notification in status bar * * @param msg/private void Shownotification (String msg) {Notificationmanager = (Notificati
Onmanager) Getsystemservice (Context.notification_service); Defines the various properties of Notification Notification Notification =new Notification (R.drawable.icon, "A message coming!", System.curr
Enttimemillis ()); Flag_auto_cancel the notification can be cleared out by the purge button of the status bar//flag_no_clear the notification cannot be cleared by the purge button of the status bar//flag_ongoing_event notification is placed in the running//flag_insist Whether the ENT has been carried out, such as music has been playing, know the user response notification.flags |= notification.flag_ongoing_event; Place this notice in the "ongoing", the "Running" group, in the notification bar notification.flags |= notification.flag_no_clear;
Indicates that after clicking on the "clear notice" in the notification bar, this notice is not cleared, often with flag_ongoing_event to use Notification.flags |= notification.flag_show_lights; Default_all uses all default values, such as sound, vibration, splash screen, and so on//default_lights use the default flash hint//default_sounds use the default hint sound//default_vibrate use the default phone vibration, add
<uses-permission android:name= "Android.permission.VIBRATE"/> PermissionsNotification.defaults = notification.default_lights; Superposition effect constant//notification.defaults=notification.default_lights|
Notification.default_sound;
Notification.ledargb = Color.Blue; NOTIFICATION.LEDONMS = 5000; Flash time, milliseconds/set event messages for notifications//intent notificationintent =new Intent (Mainactivity.this, Mainactivity.class); Click on the notification to jump to the activity Intent notificationintent = new Intent (Getapplicationcontext (), mainactivity.class);
Load class, if directly through the class name, will reload the page when clicked, unable to restore the last page state.
Notificationintent.setflags (Intent.flag_activity_single_top);
Pendingintent contentitent = pendingintent.getactivity (this, 0, notificationintent, 0);
Notification.setlatesteventinfo (this, ' message ', "message:" + MSG, contentitent);
Pass the notification to Notificationmanager notificationmanager.notify (0, notification); /** * Get information from activity * * @param msg/public void receivermsgtoactivity (String msg) {sendmsgtoactivty ("\ n Receive
Rmsgtoactivity: "+msg);
public void Sendmsgtoserver (String msg) {shownotification (msg);The public class Localbinder extends Binder {public MyService GetService () {return myservice.this;
}
}
}
2, new Mybroadcastreceiver class, inherit broadcastreceiver, used to send intent start service
Package com.ljq.activity;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
/**
* Intent start Service
*
* * @author jiqinlin * */Public
class Mybroadcastreceiver extends Broadcastreceiver {
@Override public
void onreceive (context, Intent Intent) {
Intent service = New Intent (context, myservice.class);
Context.startservice (service);
}
3, the new Mainactivity class, is actually an activity, used to render the interface
Package com.ljq.activity;
Import java.util.List;
Import android.app.Activity;
Import Android.app.ActivityManager;
Import Android.content.BroadcastReceiver;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.TextView;
public class Mainactivity extends activity implements View.onclicklistener {private String msg = "";
Private TextView txtmsg;
Private Updatereceiver receiver;
Private MyService MyService;
Private final static String tag=mainactivity.class.getsimplename ();
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Txtmsg = (TextView) This.findviewbyid (r.id.txtmsg);
This.findviewbyid (R.id.btnstart). Setonclicklistener (this); This.findviewbyid (R.id.btnsend). Setonclicklistener (this);
Subscribe to broadcast Intent receiver = new updatereceiver ();
Intentfilter filter = new Intentfilter ();
Filter.addaction ("com.android.Yao.msg");
This.registerreceiver (receiver, filter);
Start the service at initialization//intent Intent = new Intent (mainactivity.this, Myservice.class);
This.bindservice (Intent, Conn, bind_auto_create);
} @Override protected void OnDestroy () {Super.ondestroy ();
End service if (conn!=null) {unbindservice (conn);
Myservice=null; The public class Updatereceiver extends Broadcastreceiver {@Override the public void onreceive (context context, Intent in
Tent) {//Get information from the service msg = Intent.getstringextra ("msg");
Txtmsg.append (msg); } private Serviceconnection conn = new Serviceconnection () {@Override public void onserviceconnected (componentname
Name, IBinder service) {MyService = (myservice.localbinder) service). GetService ();
LOG.I (TAG, "onserviceconnected myservice:" +myservice); } @Override public void OnservicedisconnectEd (componentname name) {myservice = null;
}
};
@Override public void OnClick (View v) {Intent Intent = new Intent (mainactivity.this, Myservice.class); Switch (V.getid ()) {case R.id.btnstart://Determine if the service starts if (false==isservicerunning (this, MyService.class.getName ())) {L
OG.I (TAG, "Start" +myservice.class.getsimplename () + "service");
This.bindservice (Intent, Conn, bind_auto_create);
LOG.I (TAG, MyService.class.getName () + "Run Status:" +isservicerunning (This, MyService.class.getName ());
Break Case R.id.btnsend://To determine if the service starts if (false==isservicerunning (this, MyService.class.getName ())) {log.i (TAG, "Start" +myse
Rvice.class.getSimpleName () + "service");
This.bindservice (Intent, Conn, bind_auto_create);
LOG.I (TAG, MyService.class.getName () + "Run Status:" +isservicerunning (This, MyService.class.getName ()); LOG.I (TAG, "OnClick myservice:" +myservice); The first time the service is started is null (the small part thinks that although the service started successfully, but not all initialized) if (myservice!=null) {myservice.sendmsgtoserver ("I am sendinG msg to Server ");
Transmit information from the activity to the service myservice.receivermsgtoactivity ("This is a msg");
} break; }/** * To determine if the service is running * @param context * @param className the service name of the judge: Package name + class name * @return true not running false on run/public s
Tatic Boolean isservicerunning (context context, String ClassName) {Boolean isrunning = false;
Activitymanager Activitymanager = (activitymanager) context. Getsystemservice (Context.activity_service); Get all the Services list<activitymanager.runningserviceinfo> services= activitymanager.getrunningservices (Integer.MAX
_value); if (Services!=null&&services.size () >0) {for (Activitymanager.runningserviceinfo service:services) {if (
Classname.equals (Service.service.getClassName ())) {isrunning=true;
Break
}} return isrunning;
}
}
4. Main.xml Layout file
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:orientation=" vertical "android:layout_width=" fill_parent "
android:layout_height=" Fill_parent ">
<textview android:layout_width=" fill_parent "android:layout_height=" Wrap_content "
android:id= "@+id/txtmsg"/>
<linearlayout
xmlns:android= "http://schemas.android.com/apk/res/" Android "
android:orientation=" horizontal "
android:layout_width=" wrap_content "
android:layout_ height= "Wrap_content" >
<button android:layout_width= "wrap_content" android:layout_height= "WRAP_"
Content "
android:text=" "Start Service"
android:id= "@+id/btnstart"/>
<button android:layout_ Width= "Wrap_content"
android:layout_height= "wrap_content"
android:text= "send msg to Server"
Android:id= "@+id/btnsend"/>
</LinearLayout>
</LinearLayout>
5, listing file Androidmanifest.xml, used to configure information such as components
<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
package=" com.ljq.activity "
android:versioncode=" 1 "
android:versionname=" 1.0 ">
< 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>
<service android:name= ". MyService "/>
<receiver android:name=". Mybroadcastreceiver "/>
</application>
<uses-sdk android:minsdkversion=" 7 "/>
</ Manifest>
For more information on Android-related content readers can view the site topics: "Android Debugging techniques and common problems solution summary", "Android Development introduction and Advanced Course", "Android Multimedia operating skills Summary (audio, video, recording, etc.)", " Android Basic Components Usage Summary, Android View tips Summary, Android layout layout tips and Android Control usage summary
I hope this article will help you with the Android program.