2013-07-31 51 views
0

我試圖通過啓動服務來運行線程,但它不會啓動。它甚至不會記錄。Android服務不啓動,不知道爲什麼

這是我的內在服務類。服務類創建一個新的後臺線程並啓動它。 backgroundthread和服務類都是內部類,因此它們可以訪問變量。

public class MyService extends Service { 
    private BackgroundThread background; 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onCreate"); 
     background = new BackgroundThread();   
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onDestroy"); 
    } 


    public int onStartCommand(Intent intent, int flags, int startId) { 
     super.onStartCommand(intent, startId, startId); 
     Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onStart"); 
     background.start(); 
     return startId; 
    } 
} 

我被這起在MainActivity服務:

startService(new Intent(this, MyService.class)); 

這是我的清單:

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 


    <activity 
     android:name="com.example.antioversleepapp.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 

    </activity> 
    <activity 
     android:name="com.example.antioversleepapp.SettingsActivity" 
     android:label="@string/title_activity_settings" > 
    </activity> 
    <activity 
     android:name="com.example.antioversleepapp.InfoActivity" 
     android:label="@string/title_activity_info" > 
    </activity> 
    <service android:enabled="true" android:name="com.example.antioversleepapp.MyService" /> 
</application> 

請幫我

回答

1

這是我的內在服務類

這是不可能的。它或者需要是一個靜態的內部類(在這種情況下,您的<service>元素也需要更改),或者它需要成爲一個單獨的公共類。

backgroundthread和服務類都是內部類,所以它們可以到達變量。

我沒有看到您的服務需要「到達」的任何「變量」。而且,Android不可能創建一個內部類的實例,因爲它沒有外部類的實例。

+0

我需要的backgroundthread在後臺運行,並做計算,這是由在MainActivity提供。並且需要將它們發回。我需要該服務來保持backgroundthread運行。也許你能以其他方式幫助我? –

+0

@RobinDijkhof:「我需要服務來保持backgroundthread運行」 - 只有當您計劃在沒有活動的情況下運行該線程時。如果僅在活動存在時需要線程,則不需要服務。 – CommonsWare

+0

謝謝你,你知道如何保持mainActivity在後臺運行嗎? –

0

嘗試在啓動服務按鈕的代碼,我希望它的工作原理:

Intent intent = new Intent(MainActivity.this,Service.class); 

MainActivity.this.startService(intent); 
相關問題