2
我想在應用程序啓動時僅啓動服務。這裏是我的代碼:在應用程序啓動時僅運行後臺服務
我的服務類:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
我的廣播接收器類:
public class MyServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
而且我AndroidManifest文件:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service
android:name=".MyService"
android:label="@string/app_name"
android:enabled="true"
android:process=":my_process" >
</service>
<receiver
android:name=".MyServiceReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
</application>
我想在應用程序啓動(第一次安裝)和設備啓動時啓動我的服務。
P.S.如果代碼是正確的,也許我必須爲eclipse「run」按鈕設置一個特定的配置?如果嘗試創建新配置,我不能在「啓動操作」中選擇任何內容,因爲我的應用程序沒有任何活動,我必須選擇「無所事事」。
感謝
但是當活動完成時服務完成,當我得到呼叫活動重新運行服務時,想法是服務運行時啓動應用程序時看到的一個服務。 –
在我第一次啓動時這不起作用 –