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”按钮设置一个特定的配置?如果尝试创建新配置,我不能在“启动操作”中选择任何内容,因为我的应用程序没有任何活动,我必须选择“无所事事”。
感谢
但是当活动完成时服务完成,当我得到呼叫活动重新运行服务时,想法是服务运行时启动应用程序时看到的一个服务。 –
在我第一次启动时这不起作用 –