How can I get thread from asyncTask into foreground?

1.2k Views Asked by At

Please, how can I get thread from my doInBackground AsyncTask into foreground ?? I need service that will be never killed and doing that thread with Notify notification. I googled than I can use startForeground, but I don't know how. This was my idea, but when I kill app or phone go to sleep, thread goes off and Notify notification don't show, however foreground notification is on always.

public class NotifyService extends Service {

private DatabaseOp mDbHelper;
public Vibrator vibrator;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("NotifyService", "onStartCommand");

    startForegroundNotification();

    NotifyBackground nb = new NotifyBackground();
    nb.execute();

    return START_STICKY;
}

private void startForegroundNotification() {
    Notification note = new Notification(R.drawable.ic_launcher,
            "Can you hear the music?", System.currentTimeMillis());
    Intent i = new Intent(this, MainActivity.class);

    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

    note.setLatestEventInfo(this, "Fake Player",
            "Now Playing: \"Ummmm, Nothing\"", pi);
    note.flags |= Notification.FLAG_NO_CLEAR;

    startForeground(1337, note);
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@SuppressWarnings("deprecation")
private void Notify(String notificationTitle, String notificationMessage,
        String id, int typ) {
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(200);

    Uri notif = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager
            .getRingtone(getApplicationContext(), notif);
    r.play();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.icon_notif,
            getResources().getString(R.string.n_title),
            System.currentTimeMillis());
    notification.flags = Notification.DEFAULT_LIGHTS
            | Notification.FLAG_AUTO_CANCEL;

    Intent notificationIntent;
    PendingIntent pendingIntent;
    switch (typ) {
    case 0:
        notificationIntent = new Intent(NotifyService.this,
                UlohaShowerActivity.class);
        notificationIntent.putExtra(UlohaShowerActivity.ODOSLI, id);
        pendingIntent = PendingIntent.getActivity(NotifyService.this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(NotifyService.this,
                notificationTitle, notificationMessage, pendingIntent);
        break;
    case 3:
        notificationIntent = new Intent(NotifyService.this,
                SviatokShowerActivity.class);
        notificationIntent.putExtra(SviatokShowerActivity.ODOSLI, id);
        pendingIntent = PendingIntent.getActivity(NotifyService.this, 0,
                notificationIntent, 0);

        notification.setLatestEventInfo(NotifyService.this,
                notificationTitle, notificationMessage, pendingIntent);
        break;
    }

    notificationManager.notify(0, notification);
}

public class NotifyBackground extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        mDbHelper = new DatabaseOp(NotifyService.this);
        final boolean cyklus = true;

        Thread vlakno = new Thread(new Runnable() {
            @Override
            public void run() {
                while (cyklus) {
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    String sysDate = getSysDate();
                    String sysDate2 = getSysDate2();
                    String time = getSysTime();

                    mDbHelper.open();

                    Log.v("sysDate", sysDate);

                    Cursor cursorU = mDbHelper.fetchUlohaS(0, sysDate);
                    if (cursorU.getCount() > 0) {
                        String idU = cursorU.getString(cursorU
                                .getColumnIndexOrThrow(DatabaseOp.KEY_ID));
                        String dbDateU = cursorU.getString(cursorU
                                .getColumnIndexOrThrow(DatabaseOp.KEY_DATE));
                        String menoU = cursorU.getString(cursorU
                                .getColumnIndexOrThrow(DatabaseOp.KEY_NAZOV));

                        String mHodina = getResources().getString(
                                R.string.cas)
                                + " "
                                + cursorU.getString(cursorU
                                        .getColumnIndexOrThrow(DatabaseOp.KEY_HODINA));

                        Log.v("task", dbDateU + "/" + sysDate);

                        if (dbDateU.equals(sysDate)) {
                            Notify(menoU, mHodina, idU, 0);
                        }
                    }

                    Cursor cursorS = mDbHelper.fetchSviatokS(3, sysDate2);
                    if (cursorS.getCount() > 0) {
                        String idS = cursorS.getString(cursorS
                                .getColumnIndexOrThrow(DatabaseOp.KEY_ID));
                        String dbDateS = cursorS.getString(cursorS
                                .getColumnIndexOrThrow(DatabaseOp.KEY_DATUM));
                        String menoS = cursorS.getString(cursorS
                                .getColumnIndexOrThrow(DatabaseOp.KEY_NAZOV));

                        if (dbDateS.equals(sysDate2)
                                && time.equals("09:00")) {
                            Notify(menoS,
                                    getResources().getString(
                                            R.string.title_section4), idS,
                                    3);
                        }
                    }
                    mDbHelper.close();
                }
            }
        });

        vlakno.start();
        return null;
    }

}
}
2

There are 2 best solutions below

0
On

You can try the following step:-

Return type of doInBackground of your thread will handle on onPostExecution. Now on the basis of return type you can track your background thread as foreground thread.

and

Why you are not using a simple user define thread?

0
On

Marking your Service as foreground requires the use of a notification so the user is aware something is running that has no direct UI controls. What you actually do in your Service is up to you. However, note that an AsyncTask is specifically for performing things in a background (non-UI/main) thread. A Service marked as "foreground" still performs all of its callback/lifecycle operations on the main thread of the app.