首页 > 开发 > Android > 正文

undefined intent constructor错误?

2017-09-08 15:24:07  来源:网友分享

我在Activity中尝试启动Service,但出现“undefined intent constructor”的报错信息。
MyService.java代码如下:

public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {    return null;}public static boolean isInstanceCreated() {       return instance != null;    }@Overridepublic void onCreate() {    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();    Log.d(TAG, "onCreate");     instance = this;}@Overridepublic void onDestroy() {    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();    Log.d(TAG, "onDestroy");    instance = null;}@Overridepublic void onStart(Intent intent, int startid) {            Toast.makeText(getBaseContext(), "Service started",Toast.LENGTH_SHORT).show();    }}

启动SampleService.java的代码如下:

  public class SampleService extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.grid_activity);    Intent myintent =new Intent(SampleService.this,MyService.this);//Error show here..    startService(myintent);      } }

在manifest file中设定service的初值如下:

<service android:enabled="true" android:name="com.MyApp.MyService" />

请大家帮我解决这个错误。

原问题:Error:undefined intent constructor when start service in android

解决方案

答:kalyan pvs(最佳答案)
你不应该使用Service.this,而应该按如下方法改变class:

Intent myintent =new Intent(SampleService.this,MyService.Class);

答:Raghunandan
做如下调整:

Intent myintent =new Intent(SampleService.this,MyService.this);

变为:

Intent myintent =new Intent(SampleService.this,MyService.Class); // first param is a context second param is a class in your case a MyServiceClass

你没有设置类似于Intent(SampleService, MyService)的构造函数,在intent constructor参数设定上出现错误。

public Intent (Context packageContext, Class<?> cls)Added in API level 1Create an intent for a specific component. All other fields (action, data, type, class) are null, though they can be modified later with explicit calls. This provides a convenient way to create an intent that is intended to execute a hard-coded class name, rather than relying on the system to find an appropriate class for you; see setComponent(ComponentName) for more information on the repercussions of this.ParameterspackageContext  A Context of the application package implementing this class.clsThe component class that is to be used for the intent.