错误:在android中启动服务时未定义的意图构造函数

时间:2013-11-19 10:17:30

标签: android android-intent

我尝试在activity中启动服务。但它显示错误,如“构造函数Intent(SampleService,MyService)未定义”

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);
      }
 }

在清单文件中初始化服务。

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

帮我解决错误。

2 个答案:

答案 0 :(得分:5)

不是Service.this你必须通过课程 所以这样改变..

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

答案 1 :(得分:2)

更改此

 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构造函数,你有错误的params。

http://developer.android.com/reference/android/content/Intent.html

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.