undefined intent constructor错误?

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

public class MyService extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

public static boolean isInstanceCreated() { 
      return instance != null; 
   }

@Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

     instance = this;
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    instance = null;

}

@Override
public void onStart(Intent intent, int startid) {
            Toast.makeText(getBaseContext(), "Service started",Toast.LENGTH_SHORT).show();
    }


}

启动SampleService.java的代码如下:

  public class SampleService extends Activity{
@Override
protected 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

阅读 4.1k
1 个回答

答: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 1
Create 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.

Parameters
packageContext  A Context of the application package implementing this class.
cls

The component class that is to be used for the intent.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏