第一步 : 创建l两个应用程序分别命名为app和anotherapp
第二步:1.在app的应用程序中MainActivity的代码如下:
package com.example.yangjian.startservicefromanotherapp; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //startService(new Intent(this, AppService.class)); } @Override protected void onDestroy() { super.onDestroy(); //stopService(new Intent(this, AppService.class)); } @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 will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
2.在AppService中的代码如下:
package com.example.yangjian.startservicefromanotherapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; public class AppService extends Service { public AppService() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return new IAppServiceRemoteBinder.Stub() { @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { } @Override public void setData(String data) throws RemoteException { AppService.this.data = data; } }; } @Override public void onCreate() { super.onCreate(); System.out.println("Service started"); //创建的线程,测试程序是否正在运行