-1

How to start service after booting that run the onCreate() function on mainActivity? i already use broadcastRecivier, i can make the service, but i cannot execute the funtion from main activity.

this is my code broadcastReciver

public class BootStartUpReciver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        //Start service on Boot
        if(intent.getAction().equals(intent.getAction())){
        Intent service = new Intent(context,TestService.class);
        service.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(service);
        }
        //Start App on Boot Start up
    if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        //if(intent.getAction().equals(intent.getAction())){
        Intent app = new Intent(context,TestService.class);
        app.setClass(context,SatuActivity.class);
        app.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(app);
    }

        }   
    }
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • Try this https://stackoverflow.com/questions/2784441/trying-to-start-a-service-on-boot-on-android?answertab=active#tab-top – San Juan Oct 24 '17 at 21:26

3 Answers3

0

You cannot call startService() and start an Activity. You would have to call startActivity(). Note that this is not a recommended pattern as most users do not want to see an app every time they boot.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
  • i have change to start activity but i got some crash, and i cannot look logcat, cause it after reboot – lucgu qolfiera Muhammad Nov 19 '14 at 17:17
  • You can still examine logcat after boot. The logcat buffer is a circular RAM buffer and is rather large. So even after the device boots and you see the "This applications has stopped" dialog, you can still connect logcat. You'll need to look at this to see where your crash is occurring. – Larry Schiefer Nov 20 '14 at 00:23
0

I think you are starting Activity as a Service.. please change to startActivity()

  Intent app = new Intent(this,MainActivity.class);// pass main activity
  app.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  this.startActivity(app);
Blue_Alien
  • 2,148
  • 2
  • 25
  • 29
0

Here is the way it works for me :

final Intent i = new Intent(Intent.ACTION_MAIN, null);

i.addCategory(Intent.CATEGORY_LAUNCHER);

final ComponentName cn = new ComponentName(
                    "your.package",
                    "your.package.MainActivity");

i.setComponent(cn);

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(i);
Benoist Laforge
  • 127
  • 1
  • 6