我在启动后启动Service时崩溃了应用程序

时间:2017-07-28 05:54:34

标签: android

我想在打开设备时启动服务。如果我启动Activity,那么它的工作正常,但在服务的情况下它崩溃了。请指导我。我的代码在这里。在我的LogCat中。我收到此错误ActivityNotFoundException。如何解决这个问题?

My ScreenShot of Error When Device turn On

我的服务

public class StartServiceAfterBoot extends BroadcastReceiver {

public StartServiceAfterBoot() {
}

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        Intent i = new Intent(context, BackgroundLocationService.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

}

我的活动

public class MainActivity extends AppCompatActivity {

private Button mStartUpdatesButton;
private Button mStopUpdatesButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent intent = new Intent(MainActivity.this, BackgroundLocationService.class);
    startService(intent);
}

我的清单

<service android:name=".LocationUpdates" />
    <service android:name=".BackgroundLocationService" />
    <receiver
        android:enabled="true"
        android:exported="true"
        android:name="com.locationupdates.broadcast.StartServiceAfterBoot"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

    </receiver>

1 个答案:

答案 0 :(得分:2)

Intent i = new Intent(context, BackgroundLocationService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(i);