首页 > 解决方案 > 为什么我没有从 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;

}

标签: androidserviceforeground-service

解决方案


您正在使用前台服务。

只有当您尝试在后台启动后台服务时,您才会收到 IllegalStateException。


推荐阅读