android - 为什么我没有从 Android O 上的 startService 获得非法状态表达式
问题描述
根据这个https://www.youtube.com/watch?v=Pumf_4yjTMc&t=57s in 0:56 这意味着当您的应用程序在后台时您无法启动服务。
它将导致java.lang.IllegalStateException: Not allowed
启动服务Intent
。但是,当我在应用程序处于后台时尝试startService OnStop
或使用广播时,它并没有崩溃,我希望它会崩溃。onRecive()
我正在使用 Pixel 2 API 27 模拟器。
MainActivity.class
switch (view.getId()) {
case R.id.button:
Log.d(TAG, "onClick: start ");
intent =new Intent(this,MyService.class);
intent.putExtra("key123", editText.getText().toString());
startService(intent);
break;
case R.id.button2:
Log.d(TAG, "onClick: stop");
stopService(intent);
break;
}
我的服务类
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
String input=intent.getStringExtra("key123");
Intent notificationIntent=new Intent(this,MainActivity.class);
PendingIntent pendingIntent= PendingIntent.getActivity(this,0,notificationIntent,0);
Notification notification= new NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("TITLE").setContentText(input)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_drive_eta_black_24dp)
.build();
startForeground(1,notification);
return START_NOT_STICKY;
}
解决方案
您正在使用前台服务。
只有当您尝试在后台启动后台服务时,您才会收到 IllegalStateException。
推荐阅读
- python - 部署脚本时的最佳实践
- javascript - 无法删除动态创建的卡片的父 div
- dropbox - Dropbox api上传到根目录?
- javascript - 如何重新加载弹出窗口而不关闭以从内容中检索新数据?
- arrays - 如何测试字符串数组是否为空?
- python - 如何使用 matplotlib 重新缩放轴
- generics - 如何摆脱二叉树类中的原始类型问题
- mongodb - 在MongoDB中,创建文本索引后,使用文本过滤器查询时没有任何输出显示
- loops - 停止 time.NewTimer 在 for 循环中初始化
- android - Jetpack Compose:如何禁用 FloatingAction 按钮?