2017-07-28 221 views
-2

我想在启动设备时启动服务。如果我开始活动,那么它的工作正常,但在服务的情况下它坠毁。请指导我。我的代码在这里。在我的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

参考https://stackoverflow.com/questions/10909683/launch-android-application-without-main-activity-and-start-service-on-launching – sasikumar

+0

@sasikumar没有任何Theme.Translucent.NoTitleBar –

回答

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

Thnxx提醒我愚蠢的错误。我改为启动服务,但它仍然崩溃.. –

+0

你得到什么错误 –

+0

把你的logct错误 –