【问题标题】:How can I get thread from asyncTask into foreground?如何从 asyncTask 获取线程到前台?
【发布时间】:2014-08-25 11:09:07
【问题描述】:

请问,我怎样才能将thread 从我的doInBackground AsyncTask 变成foreground ?我需要永远不会被杀死的service,并使用Notify notification 来实现thread。我用谷歌搜索了startForeground,但我不知道怎么用。这是我的想法,但是当我杀死应用程序或手机进入睡眠状态时,thread 熄灭,Notify notification 不显示,但 foreground notification 始终打开。

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;
    }

}
}

【问题讨论】:

  • 我不清楚。尝试独立于所使用的技术来陈述您的问题。 “我想创建一个服务来做'某事',当'条件'时,我想'做其他事情'”。
  • 尝试实施 Bhupendra 建议...

标签: android multithreading service foregroundnotification


【解决方案1】:

您可以尝试以下步骤:-

您的线程的 doInBackground 的返回类型将在 onPostExecution 上处理。现在根据返回类型,您可以将后台线程跟踪为前台线程。

为什么不使用简单的用户定义线程?

【讨论】:

    【解决方案2】:

    将您的 Service 标记为前台需要使用通知,以便用户知道正在运行的某些东西没有直接的 UI 控件。您在Service 中实际执行的操作取决于您。但是请注意,AsyncTask 专门用于在后台(非 UI/主)线程中执行操作。标记为“前台”的Service 仍会在应用的主线程上执行其所有回调/生命周期操作。

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多