Reputation: 65
I want to start a service from my activity class. The problem is, that onStartCommand
never gets called. I placed breakpoint there and it is never hit. My example is really simple and I don't understand why it doesn't work.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(TestService.class.getName());
serviceIntent.putExtra("UserID", "123456");
serviceIntent.setPackage(this.getPackageName());
startService(serviceIntent);
}
}
If I remove serviceIntent.setPackage(this.getPackageName());
I get the following error:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=package.TestService (has extras) }
That's why I added it to get rid of this error. But it still isn't working.
TestService.java:
public class TestService extends Service {
public TestService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
AndroidManifest.xml:
<application
...
<service
android:name=".TestService"
android:enabled="true"
android:exported="true"></service>
...
</application>
Upvotes: 0
Views: 1163
Reputation: 353
Please try this
Add in Activity class
Intent serviceIntent = new Intent(MainActivity.this, TestService.class);
serviceIntent.putExtra("UserID", "123456");
startService(serviceIntent);
Upvotes: 3