跨应用使用Service
2017-03-03 本文已影响57人
csp
从AnotherApp启动App的Service:
首先,在App中创建AppService:
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 start");
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("service destroyed");
}
}
之后在AnotherApp里面启动App里面的AppService:
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();
serviceIntent.setComponent(new ComponentName("com.chenshipeng.startservicefromanotherapp","com.chenshipeng.startservicefromanotherapp.AppService"));
findViewById(R.id.btnStartAppService).setOnClickListener(this);
findViewById(R.id.btnStopAppService).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnStartAppService:
startService(serviceIntent);
break;
case R.id.btnStopAppService:
stopService(serviceIntent);
break;
}
}
}
这里的Intent通过设置组件名字,使用包名和服务的名字,来创建一个显示的Intent,这样就可以用来启动另外一个App的服务了。