2010-12-05 63 views
6

我正在創建我的第一個Android應用程序,我需要使用服務。用戶界面將有一個複選框(CheckBoxPreference),用於打開/關閉服務,服務只能被我的應用程序訪問(不需要共享)。在Android中創建服務

到目前爲止,此功能的用戶界面已準備就緒,我知道如何響應該事件,我不知道如何創建服務以及如何連接到該服務。

這個想法是,服務繼續監聽事件並在後臺響應它們,並且應用程序僅用於打開/關閉或更改某些設置。

我在網上尋找教程,但我似乎沒有得到過程。

回答

10
CheckBox checkBox = 
    (CheckBox) findViewById(R.id.check_box); 
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      startService(new Intent(this, TheService.class)); 
     } 
    } 
}); 

,服務:

public class TheService extends Service { 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onStart(Intent intent, int startid) { 
     Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show(); 
    } 
} 
+3

線startService(新意圖(此,TheClass.class));應該閱讀:startService(新的意圖(this,TheService.class))。並且不要忘記將該服務添加到AndroidManifest.xml – PedroC88 2010-12-05 17:55:50

1

在Android Studio中,右鍵單擊包,然後選擇新建|服務|服務。現在添加這個方法:

@Override 
int onStartCommand(Intent intent, int flags, int startId) { 
    // Your code here... 
} 

注意:在onStart已被棄用。

要啓動服務:從一個活動的onCreate方法(或廣播接收機的的onReceive法):

Intent i = new Intent(context, MyService.class); 
context.startService(i);