Ram
Ram

Reputation: 2530

Error:undefined intent constructor when start service in android

I'm try to start service in the activity.But it shows error like "The constructor Intent(SampleService, MyService) is undefined"

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


} 

Starting service from 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 initialized in manifest file.

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

Help me to solve the error.

Upvotes: 3

Views: 758

Answers (2)

Raghunandan
Raghunandan

Reputation: 133570

Change this

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

to

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

Look at the public constructors at you do not have a constructor as Intent(SampleService, MyService) .You have wrong params for the intent constructor.

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.

Upvotes: 2

kalyan pvs
kalyan pvs

Reputation: 14590

not Service.this you have to pass class so change like this..

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

Upvotes: 4

Related Questions