我想从我的活动班级开始一项服务。问题是,onStartCommand
从未被调用。我在这里放置了断点,但它从未被击中。我的示例非常简单,我不明白为什么它不起作用。
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);
}
}
如果我删除serviceIntent.setPackage(this.getPackageName());
,则会出现以下错误:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=package.TestService (has extras) }
这就是为什么我添加它以消除此错误的原因。但它仍然无法正常工作。
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>
答案 0 :(得分:1)
请尝试
添加Activity类
Intent serviceIntent = new Intent(MainActivity.this, TestService.class);
serviceIntent.putExtra("UserID", "123456");
startService(serviceIntent);