gpt4 book ai didi

java - 对于服务类,我看到 android.content.ActivityNotFoundException : Unable to find explicit activity class

转载 作者:行者123 更新时间:2023-12-01 07:16:55 30 4
gpt4 key购买 nike

我正在使用 Android,当我创建服务并从主 Activity 线程运行它时,遇到以下错误。我确实浏览了与此错误相关的所有线程,但他们看到的错误主要针对 Activity 任务。以下是错误和代码的详细信息

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.serviceexample/com.example.serviceexample.MyServiceBg}; have you declared this activity in your AndroidManifest.xml?

我确实检查了我的 AndriodManifest.xml,并且确实看到了声明的服务

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.serviceexample">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="ServiceExample"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service
android:name=".MyIntentService"
android:exported="false"></service>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service android:name=".MyBgService"/>
</application>

</manifest>

MainActivity.java:

package com.example.serviceexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btn = (Button)findViewById(R.id.displayBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent displayTost = new Intent(MainActivity.this, MyBgService.class);
startActivity(displayTost);
}
});
}

我的后台服务:

package com.example.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class MyBgService extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int i;
for (i = 1; i< 10; i++) {
Toast.makeText(getApplicationContext(), "Number = "+i, Toast.LENGTH_LONG).show();
}
return Service.START_NOT_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

我确实尝试链接​​ AndroidManifest.xml 中的路径。但仍然遇到同样的错误。不确定是什么问题。

这是 Gradle 的版本:3.5.3,我使用的是 SDK 版本29

任何帮助将不胜感激。

最佳答案

基本上单击按钮即可开始服务。而不是这个

startActivity(displayTost);

使用

startService(new Intent(MainActivity.this, MyBgService.class));

关于java - 对于服务类,我看到 android.content.ActivityNotFoundException : Unable to find explicit activity class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60051437/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com