-2

I want to start service when I turn on my device. If I start Activity, then its working fine but in case of Service its crashed. Please guide me. My code is here. In my LogCat. I am getting this Error ActivityNotFoundException. How to solve this issue?

My ScreenShot of Error When Device turn On

My Service

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);
    }
}

}

My Activity

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);
}

My Manifest

<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>
coder_baba
  • 447
  • 3
  • 21

1 Answers1

3
Intent i = new Intent(context, BackgroundLocationService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(i);
Sagar Patel
  • 224
  • 1
  • 9
  • Thnxx for reminding my silly mistake. I changed to startService but still its getting crashed.. – coder_baba Jul 28 '17 at 06:13
  • thnxx dear.. there was an error in manifest.. I made it correct. an Thank you for pointing out my this mistake... :) Now working fine – coder_baba Jul 28 '17 at 06:23