让Android服务在backgroung运行甚至应用程序关闭

时间:2016-05-21 09:32:45

标签: android

即使我的应用程序关闭或所有系统重新启动,我想制作两个在后台运行kip的android服务,但我不知道android。这就是我所做的:

的AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_ROOT_COMPLETED"/>

<service android:name="FirstService"></service>
<receiver android:name="FirstServiceReceiver">
        <intent-filter>
            <action android:name="com.android.techrainner"/>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>
<service android:name="SecondService"></service>
<receiver android:name="SecondServiceReceiver">
        <intent-filter>
            <action android:name="com.android.techrainner"/>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

这是我的MainActivity(WL:因为我使用的是IBM MobileFirst)

  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    WL.createInstance(this);

    WL.getInstance().showSplashScreen(this);

    WL.getInstance().initializeWebFramework(getApplicationContext(), this);

    Intent startFirstServiceIntent = new Intent(this,FirstService.class);
    Intent startSecondServiceIntent = new Intent(this,SecondService.class);
    startService(startFirstServiceIntent);
    startService(startSecondServiceIntent);

}

这是第一项服务:

class FirstService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public  int onStartCommand(Intent intent,int flags,int startId){    
    return START_STICKY;    
}

}

第二项服务与第一项服务相同

第一个接收者:

public class FirstServiceReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context,FirstService.class));

}

}

第二个接收器与第一个接收器相同。

只有在打开应用程序时才会在后台运行两个服务,并且当我关闭它时它们将被停止。

1 个答案:

答案 0 :(得分:0)

与在Android文档中一样,它是关于服务的:

服务已经开始&#34;当应用程序组件(例如活动)通过调用startService()启动它时。一旦启动,服务可以无限期地在后台运行,即使启动它的组件被销毁。通常,已启动的服务执行单个操作,并且不会将结果返回给调用者。例如,它可能通过网络下载或上载文件。操作完成后,服务应该自行停止。

因此,当操作完成时,服务会自动停止。如果您想要启动服务,即使您的应用程序被销毁,您也可以使用Alarm Manager Service。您可以在应用程序中设置重复警报以在后台启动服务。

如果您的要求是将您的应用与您的应用服务器同步并希望与服务器同步,即使您的应用已关闭,那么您也可以使用Android的SyncAdapter框架。