2017-07-28 220 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錯誤 –