美文网首页
跨应用使用Service

跨应用使用Service

作者: csp | 来源:发表于2017-03-03 16:55 被阅读57次

    从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的服务了。

    相关文章

      网友评论

          本文标题:跨应用使用Service

          本文链接:https://www.haomeiwen.com/subject/nfdrgttx.html