我試圖通過啓動服務來運行線程,但它不會啓動。它甚至不會記錄。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>
請幫我
我需要的backgroundthread在後臺運行,並做計算,這是由在MainActivity提供。並且需要將它們發回。我需要該服務來保持backgroundthread運行。也許你能以其他方式幫助我? –
@RobinDijkhof:「我需要服務來保持backgroundthread運行」 - 只有當您計劃在沒有活動的情況下運行該線程時。如果僅在活動存在時需要線程,則不需要服務。 – CommonsWare
謝謝你,你知道如何保持mainActivity在後臺運行嗎? –