2010-02-25 199 views

回答

35

該應用程序可以藉助Context .startService方法啓動該服務。如果服務尚未創建,該方法將調用服務的onCreate方法;否則將調用onStart方法。下面是代碼:

Intent serviceIntent = new Intent(); 
serviceIntent.setAction("com.testApp.service.MY_SERVICE"); 
startService(serviceIntent); 
1

使用Context.startService()方法。

並閱讀this

44

在代碼中添加此

Intent serviceIntent = new Intent(this, ServiceName.class); 
    startService(serviceIntent); 

不要忘記添加在AndroidManifest.xml服務標籤文件

<service android:name="com.example.ServiceName"></service> 

Android official documentation

注意:一項服務在與 中的應用程序相同的進程中運行,該應用程序在該應用程序的主線程中聲明瞭該應用程序,默認情況下爲 。因此,如果您的服務在用戶與來自同一應用程序的活動進行交互時執行密集或阻止操作 ,則該服務會降低活動性能。爲避免影響應用程序的性能,您應該在 服務中啓動一個新線程。

+0

你可以給我如何開始s線程代碼 – 2016-09-21 18:56:53

1

首先從android Manifest.xml文件創建服務(即從應用程序選項卡),並給它一些名稱。
在像點擊或觸摸某些事件的活動,包括從服務代碼:

public void onClick(View v) 
{ 
    startService(new Intent(getApplicationContext(),Servicename.class)); 
} 

如果你想停止運行或啓動服務,則包括此代碼:

public void onclick(View v) 
{ 
    stopService(new Intent(getApplicationContext,Servicename.class)); 
} 
0

如果你想啓動一個服務,它應該在後臺運行,在你的相應服務中使用START_STICKY。

您可以在引導也開始servvice,

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

,打造接收機,

<receiver android:name=".auth.NotificationBroadcast" android:enabled="true" > 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter> 
</receiver> 

在Brodcast接收器添加,

@Override 
    public void onReceive(Context context, Intent intent) { 

     System.out.println("BroadcastReceiverBroadcast--------------------ReceiverBroadcastReceiverBroadcastReceiver----------------BroadcastReceiver"); 

     if (intent != null) { 
      String action = intent.getAction(); 

     switch (action) { 
      case Intent.ACTION_BOOT_COMPLETED: 
       System.out.println("Called on REBOOT"); 
       // start a new service 
       startService(new Intent(getApplicationContext(),Servicename.class)); 

       break; 
      default: 
       break; 
     } 
    } 
} 

而且你的服務是一樣,