android - 从BroadcastReceiver调用后台服务

标签 android

我试图从 BroadcastReceiver 类调用推送通知后台服务,但我的应用程序崩溃了。代码如下:

public class AlarmReceiver extends BroadcastReceiver {

    static int count=1;

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent myIntent=new Intent(context,NotifyService.class);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startActivity(myIntent);  
    }
} 

list 条目:

<receiver android:name=".AlarmReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>
<service android:name=".NotifyService">
</service>

错误:

05-24 15:17:00.042: ERROR/AndroidRuntime(424): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.alarm/com.android.alarm.NotifyService}; have you declared this activity in your AndroidManifest.xml?

当我通过 Activity 调用此服务时,它正在工作,但我的目标是从 BroadcastReceiver 调用此服务。

最佳答案

AlarmReceiver 正在调用 startActivity(),而不是 startService()。您可以使用 startService() 启动服务;您可以使用 startActivity() 启动 Activity 。

此外,服务不需要(或使用,据我所知)FLAG_ACTIVITY_NEW_TASK

关于android - 从BroadcastReceiver调用后台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2896080/

相关文章:

android - 双卡 Android 设备的通话记录

java - 如何知道选择 GridView 中的哪个 View 对象来打开上下文菜单

android - 如何通过坐标 x,y Android 在 View 中查找元素

Android:在xml中创建一个可变模块

android - 自定义 Android NumberPicker

java - 添加自签名证书 OkHttpClient

android - ListView 正在泄漏 Activity 上下文

Android:requestCode 和 resultCode

android - 如何在用户离线时发送图像,就像使用 firebase 的聊天应用程序中的短信一样?

android - 如何将二维数组作为 Intent 传递到android中