仅运行后台服务时,应用程序启动应用程序、后台

由网友(可爱又好听的小仙女)分享简介:我只想开始启动服务时,我的应用程序启动。这是我的code:I want to start only to start a service when my application start. Here is my code:我的服务类:public class MyService extends Service...

我只想开始启动服务时,我的应用程序启动。这是我的code:

I want to start only to start a service when my application start. Here is my code:

我的服务类:

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;
}
}

我的BroadcastReceiver的类:

My BroadcastReceiver class:

public class MyServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, MyService.class);
    context.startService(service);
}
}

和我AndroidManifest文件:

And my AndroidManifest file:

<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>

我希望在应用程序启动(安装了第一次),开始我的服务,并在设备启动。

I want to start my service when the application start (is installed the first time) and when the device boot.

P.S。如果code是对的,也许我已经设置了Eclipse运行按钮,一个特定的配置?如果尝试创建一个新的配置,我不能选择没有在启动行动,因为我的应用程序还没有一个活动,我不得不选择什么都不做。

P.S. If the code is right, maybe I have to setup a particular configuration for the eclipse "run" button? If try to create a new configuration I can't select nothing in "Launch action" because my application haven't an activity, and I have to select "Do nothing".

感谢

推荐答案

您将需要一个主要的活动来调用在的onCreate 此服务,如果你想在服务启动只要你启动应用程序。在您的主要活动包括此code。在您的onCreate。

You going to need an main activity to call this service within onCreate if you want the service to start as soon as you start your application. In your main activity include this code in your onCreate.

startService(新意图(Main_Activity.this,MyServiceReceiver.class));

这就是当你开始你的应用程序来调用服务。

This is just to call your service when you start up your application.

阅读全文

相关推荐

最新文章