Search code examples
androidintentservicepreferencefragment

Start service from PreferenceFragment


I want to start background service from my PreferenceFragment. In order to achieve that first I created Service:

public class MyService extends IntentService {

    private static final String TAG = makeLogTag(MyService.class);

    public MyService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Toast.makeText(this, "It's working", Toast.LENGTH_SHORT).show();
    }
}

Then I added preference which should start intent:

 <PreferenceScreen
       android:title="@string/my_preference">
       <intent android:action="MY_SERVICE"/>
 </PreferenceScreen>

And of course I added special attribute to AndroidManifest.xml

<service
       android:name=".MyService"
       android:exported="false">
       <intent-filter>
            <action android:name="MY_SERVICE"/>
       </intent-filter>
</service>

QUESTION

Unfortunately I'm getting error that could not find Activity with act="MY_SERVICE". I understand that with Activity there is no problem, but how to start Service?


Solution

  • The Intent in the preference screen is started using startActivity(), but you need to do it with startService() instead.

    You should make your preference XML like this

     <PreferenceScreen
           android:key="pref_open_service_key"
           android:title="@string/my_preference">
     </PreferenceScreen>
    

    and start the service inside your code.

    Preference myPref = (Preference) findPreference("pref_open_service_key");
    myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
         public boolean onPreferenceClick(Preference preference) {
             Intent intent = new Intent(PreferenceActivity.this, MyService.class);
             startService(intent);
         }
    });