2

I made an app as a service which runs in background. This app is basically a battery alarm. It works fine but the only problem is that when this service is running it also displays this app in the active application task manager. So when I exit this app it stops that service as well. So what I want is to only stop this service when the user unchecks the box in the app settings. If it is checked then it should not be stopped even if it is closed in active application task manager.

How can I stop showing my app in task manager?

I think I should provide code over here This is my service class

public class BatteryService extends Service {
Notify notification = new Notify();
BatteryAlarm alarm = new BatteryAlarm();
private MediaPlayer mMediaPlayer;
boolean flag = false;

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

//method to start service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    notification.initNotification(this, false);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}

//Broadcast receiver to get battery info
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context c, Intent i) {
        //notification.initNotification(c);

        int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int plugged = i.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);

        SharedPreferences getAlarm = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String alarms = getAlarm.getString("ringtones", "content://media/internal/audio/media/45"); // /system/media/audio/ringtones/ANDROMEDA.ogg , content://media/internal/audio/media/45
        Uri uri = Uri.parse(alarms);

        if(plugged == 2) {
            if(level == 100) {
                if(uri != null) {
                    if(flag == false) {
                        playAlarm(c, uri);
                        notification.initNotification(c, true);
                        Toast.makeText(c, "Battery charge is completed. Unplug your mobile phone!", Toast.LENGTH_LONG).show();
                        flag = true;
                    }
                }
            }
        } else if (plugged == 0) {
            if(uri != null) {
                stopAlarm();
            }
            notification.cancelNotification(c);
            //Toast.makeText(c, "Mobile is unplugged", Toast.LENGTH_LONG).show();   
        }   
    }
};

//play alarm method
private void playAlarm(Context c, Uri uri) {

    mMediaPlayer = new MediaPlayer();
    try {
        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(getBaseContext(), uri);
        final AudioManager audioManager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        onDestroy();
    }

}

//method to stop playing alarm
private void stopAlarm() {
    mMediaPlayer.stop();
    flag = false;
}

//method to stop service
public void onDestroy() {
    super.onDestroy();
    notification.cancelNotification(this);
    unregisterReceiver(this.mBatInfoReceiver);
    stopAlarm();
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}

}

This is my main activity

public class BatteryNotify extends PreferenceActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.xml.prefs);
    addPreferencesFromResource(R.xml.prefs);

    SharedPreferences getCB = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean cb = getCB.getBoolean("checkbox", true);
    final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkbox");

    if(cb == true) {
        startService(new Intent(getBaseContext(), BatteryService.class));
    } else if(cb == false) {
        stopService(new Intent(getBaseContext(), BatteryService.class));
    }

    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if(newValue.toString().equals("true")) {
                startService(new Intent(getBaseContext(), BatteryService.class));
            } else {
                stopService(new Intent(getBaseContext(), BatteryService.class));
            }
            return true;
        }
    });

}

}

and here is my menifest file

<uses-sdk android:minSdkVersion="10" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".BatteryNotify"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".BatteryService"></service>
</application>

Om3ga
  • 30,465
  • 43
  • 141
  • 221
  • How are you starting the service? – techi.services May 13 '12 at 11:02
  • Is the service registered in the Manifest? The Activity should "just" handle control of the service.(Start and stop) but not containing the code of it. – nuala May 13 '12 at 11:02
  • What about this : FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS ? http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS – moujib May 13 '12 at 11:02
  • @techiServices I am starting my service in main activity based on the checkbox whether it is checked or not. – Om3ga May 13 '12 at 11:09
  • @yoshi Yes the service is register in menifest file but it still shows this app in task manager. – Om3ga May 13 '12 at 11:09

2 Answers2

2

The best way to do this would be to create a BroadcastReceiver, register it in the manifest with the appropriate intent-filters and when it receives one it starts the Service or Activity to perform whatever task you need.

EDIT:

Create your BroadcastReceiver as a separate class and register it in the manifest. When it receives a battery event, create a PendingIntent to start the Service. That way it doesn't matter if your app isn't running. It will be started for you.

techi.services
  • 8,473
  • 4
  • 39
  • 42
  • If you've never faced `PendingIntent` (like me ^,^) official documentation and this answer are good nodes to start: http://stackoverflow.com/a/4812421/1063730 – nuala May 13 '12 at 11:55
1

How can I stop showing my app in task manager?

You can't, for obvious security reasons.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • CommonsWare then how gmail and some other apps work? They are also not shown in task manager but still running in background. If I am not correct then please correct me. – Om3ga May 13 '12 at 11:15
  • @al0neevenings: That would be a question for whoever wrote your "task manager". Suffice it to say that if any piece of your app is running, a "task manager" can detect that and can elect to list you. There are perhaps a thousand "task manager" apps available, and they will all do things differently. – CommonsWare May 13 '12 at 11:18