Android使用Intent启动Service的Intent必须是显式的

  • Post author:
  • Post category:其他



今天使用Intent来启动Service时,代码如下:


 //为 Intent设置Action属性 
        intent.setAction("com.hust.service");
        start.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//启动指定的Service
				startService(intent);
			}
        	
        });


出现了如下错误:



有些时候我们使用Service的时需要采用隐式意图启动的方式,但是Android 5.0一出来后,


其中有个特性就是Service Intent must be explitict,就是说Intent必须是显示的才能启动Service




那么这里有两种解决方法:


1,设置Action和Package名


//为 Intent设置Action属性 ,Android 5.0之后就要求只能使用显示的Intent启动Service
        intent.setAction("com.hust.service");//设置Action
        intent.setPackage("com.hust.servicefirst");//设置包名
        start.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//启动指定的Service
				startService(intent);
			}
        	
        });


2,将隐式启动转为显示启动


Intent intent = new Intent();
intent.setAction("XXX.XXX.XXX");
Intent mintent = new Intent(getExplicitIntent(mContext,intent ));//转换成显示Intent
context.startService(mintent );



版权声明:本文为tuke_tuke原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。