APP
Mainactivity.java
Package Com.xfeng.startservicefromanotherapp;import Android.content.intent;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;public class Mainactivity extends appcompatactivity { @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); Start Service StartService (new Intent (This,appservice.class)); } @Override protected void OnDestroy () { Super.ondestroy (); Stop service StopService (new Intent (This,appservice.class));} }
Appservice.java
Package Com.xfeng.startservicefromanotherapp;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import Java.sql.sqloutput;public class Appservice extends Service {public appservice () { } @Override public ibinder onbind (Intent Intent) { //Todo:return The communication channel to the SERVICE.
throw New Unsupportedoperationexception ("not yet implemented"); } @Override public void OnCreate () { super.oncreate (); System.out.println ("Service started"); } @Override public void OnDestroy () { Super.ondestroy (); System.out.println ("Service destory");} }
Anotherapp
Package Com.xfeng.anotherapp;import Android.content.componentname;import Android.content.intent;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;public Class Mainactivity extends Appcompatactivity implements View.onclicklistener {private Intent serviceintent; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Serviceintent = new Intent (); Show Intent Serviceintent.setcomponent (New ComponentName ("Com.xfeng.startservicefromanotherapp", " Com.xfeng.startservicefromanotherapp.AppService ")); Findviewbyid (R.id.btnstartappservice). Setonclicklistener (this); Findviewbyid (R.id.btnstopappservice). Setonclicklistener (this); } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btnstartappservice:// Intent i = new Intent ();///Display Intent//i.setcomponent (New ComponentName ("Com.xfeng.startservicefromanotherapp", "Com.xfeng.startservicefromanot Herapp. Appservice ")); StartService (serviceintent); Break Case R.id.btnstopappservice:stopservice (serviceintent); Break } }}
"Xfeng Android Development Notes" four basic components--launch service across apps