我想从我的活动类开始服务。问题是,这永远不会被调用。我在那里放置了断点,它永远不会被击中。我的例子非常简单,我不明白为什么它不起作用。onStartCommand主要活动.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) }这就是为什么我添加它以摆脱此错误的原因。但它仍然不起作用。测试服务.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); }}安卓智能.xml:<application ... <service android:name=".TestService" android:enabled="true" android:exported="true"></service> ...</application>
1 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
请尝试此操作
添加活动类
Intent serviceIntent = new Intent(MainActivity.this, TestService.class);
serviceIntent.putExtra("UserID", "123456");
startService(serviceIntent);
添加回答
举报
0/150
提交
取消