首先我们创建两个android 工程 这里我们称被启动的app为甲,启动被启动的app为已,首先我们在甲 app类中new一个Myservice类 在类的onCreate函数中我们写一个匿名线程
public class MyService extends Service {
private boolean Runing=false;
private String Data=null;
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) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
Runing =true;
new Thread(){
@Override
public void run() {
super.run();
while(Runing)
{
System.out.println(Data);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void onDestroy() {
super.onDestroy();
Runing =false;
}
}
写完之后 我们把这个app 启动 安装到手机上面
然后我们打开乙app
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editText; @Override
Intent intent = new Intent();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_startAnotherApp).setOnClickListener(this);
findViewById(R.id.btn_stopAnotherApp).setOnClickListener(this);
intent.setComponent(new ComponentName("com.example.blue.anotherapp","com.example.blue.anotherapp.MyService"));//设置一个组件名称 同组件名来启动所需要启动Service
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_startAnotherApp:
startService(intent);
break;
case R.id.btn_stopAnotherApp :
stopService(intent);
break;
}
}
}
在这里我们声明了一个intent 这个指明了一个组件大家都知道启动一个Service可以用intent 这里我们声明的intent可以指明我们要启动的app 这里声明的第一个字符串为 app 甲的包名地址 第二个为甲app中的Service类的地址
当我们启动时就点击启动按钮 甲app就会不断的输出了