對於你們來說,這可能是一個簡單的問題,但它是我第一次嘗試創建一個應用程序,當我的應用程序關閉時應該在後臺運行。我的問題是:當我點擊我的「啓動服務」按鈕時,服務無法啓動。我沒有看到任何敬酒,也沒有看到logcat(也沒有錯誤)。提前致謝!服務未啓動
服務類
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
我的主要活動
public void startServiceClick(View v){
Log.d("foo", "onClick: starting srvice");
startService(new Intent(this, MyService.class));
}
public void stopServiceClick(View v){
Log.d("foo", "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
}
清單XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="se.johanberntsson.main"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<application
android:icon="@drawable/maps1"
android:label="@string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".LongitudeActivity"
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=".DebugActivity" />
<activity android:name=".GoogleMapsActivity" />
<service android:enabled="true" android:name=".MyService" />
</application>
</manifest>
你有沒有嘗試過context.startService? 正在啓動服務日誌是gettting生成的嗎? – AAnkit
@AnkitAwasthi現在試過了,沒有成功。是的,我在日誌中獲得了「onclick,starting service」。但沒有任何服務..:/ – Johan
我認爲答案張貼可以解決您的問題。如果不是發佈完整的活動代碼,將嘗試我的設置.. – AAnkit