由於某些原因,服務未啓動,我的調試日誌都未被調用,我在服務中創建的吐司也未顯示(Toasts通過處理程序顯示,吐司代碼未顯示,簡單的指南這裏供參考:http://www.jjoe64.com/2011/09/show-toast-notification-from-service.html)Android服務未能啓動
public class MainActivity extends Activity {
Intent locationPollingIntent;
Button updateLocationButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationPollingIntent = new Intent(this, LocationService.class);
updateLocationButton = (Button) findViewById(R.id.updateLocationButton);
updateLocationButton.setText("Start");
updateLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, updateLocationButton.getText().toString());
if (updateLocationButton.getText().toString() == "Start") {
MainActivity.this.startService(locationPollingIntent);
updateLocationButton.setText("Stop");
} else if (updateLocationButton.getText().toString() == "Stop") {
MainActivity.this.stopService(locationPollingIntent);
updateLocationButton.setText("Start");
}
}
});
}
}
從我的服務種類中的片段看起來像這樣:
public class LocationService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Location service started");
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Starting Service");
grabLocation();
return super.onStartCommand(intent, flags, startId);
}
// No implementation
@Override
public IBinder onBind(Intent arg0) {
return null;
}
最後,我的清單包含以下
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rperryng.intellilocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service
android:name=".LocationService"
android:label="Location Service" />
<activity
android:name="com.rperryng.intellilocation.activities.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>
</application>
</manifest>
還值得一提的是,我的mainActivity在包com.rperryng.intellilocation.activities
和我的com.rperryng.intellilocation.backgroundServices
服務我發現下面的日誌可能與此問題:
01-27 12:53:58.804: W/ActivityManager(262): Unable to start service Intent { cmp=com.rperryng.intellilocation/.backgroundServices.LocationService }: not found
不要在字符串比較中使用'==',請使用equals()'。 –