Explicit Intent & Implicit Intent
Intent用于启动Activity,Service或发送Broadcast。Intent的使用有隐式和显式之分,即Explicit Intent和Implicit Intent。
Explicit Intent是指,能够明确指定class,或者package name的Intent。例如
Intent i = new Intent(Context,SecondActivity.class);
startActivity(i);
Implicit Intent是指,使用action,data或categroy的filter方式。
Intent intent = new Intent("myaction");
startActivity(intent);
Intent intent = new Intent();
intent.setAction("myAction");
intent.addCategory("myCategory");
startActivity(intent);
在同一APP种,两种方式都可以使用。相对而言,隐式可以降低耦合,而显式效率更高。
若要跨APP,则必须使用隐式。
需要注意的是,在Android 5.0之后,跨进程调用Service,需要使用显式的方法,否则将会报错。
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.breakloop.servicedemo.MyService }
解决方案有两种。
(1)添加App Package Name.
Intent mIntent = new Intent();
mIntent.setAction("serviceAction");
mIntent.setPackage("servicePackageName");
context.startService(mIntent);
(2)将隐式Intent进行嵌套,封装为显式Intent
Intent mIntent = new Intent();
mIntent.setAction("serviceAction");
Intent eintent = new Intent(getExplicitIntent(mContext,mIntent));
context.startService(eintent);
还没有评论,来说两句吧...