Android:在服务中启动一个线程

时间:2014-12-02 22:47:48

标签: android multithreading service

我想在我自己的服务中启动一个新活动,该活动是从一个活动开始的。在这个线程中,我想每3秒后更新一次数据库中的数据。我创建了数据库并在我的onStartCommand()方法中初始化它。我应该在哪里实现我的线程以及如何实现?

我试过了,但它没有用,应用程序将不幸关闭。没有这种方法的调用,一切都有效。

我创建了这个方法,我在onStartCommand

中调用了这个方法
private void startThreadUpdatingDatabase(){
    Log.d("Database", "startThreadUpdatingDatabase(was called)");
    new Thread(new Runnable() { 
        public void run(){
            //do stuff
        }
    }).start();
}

2 个答案:

答案 0 :(得分:2)

如果您想开始重复性任务,可以尝试不同的方法:

1)报警
2)处理者
3)TimerTask(我最不喜欢的)

<强>警报

private AlarmManager mAlarmManager;
private static final long ALARM_INTERVAL = 3 * 60 * 1000;

private void issueAlarm() {
    if(mAlarmManager == null)
        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance(Locale.US);
    calendar.add(Calendar.MILLISECOND, (int) ALARM_INTERVAL);
    Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(this, ALARM_REQUEST_CODE, intent, 0);
    mAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), ALARM_INTERVAL, alarmIntent);
}

创建AlarmReceiver:

public class AlarmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //Do DB Stuff here
    }

}

不要忘记在清单中注册:

<receiver
    android:name=".AlarmBroadcastReceiver"
    android:exported="false" />

<强>处理程序

@Override
public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
        Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

排队你的postedTask

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //As danny117 pointed out, multiple clients starting the service
    //Can trigger this.
    mServiceHandler.removeCallbacks(yourRunnable);
    mServiceHandler.post(yourRunnable);
    return super.onStartCommand(intent, flags, startId);
}

Runnable应该如下所示:

private Runnable yourRunnable = new Runnable() {
        @Override
        public void run(){
        //DB work here
        if(mServiceHandler != null)
            mServiceHandler.postDelayed(this, ALARM_INTERVAL);
        }
}

服务停止后也要清理:

@Override
public void onDestroy() {
    super.onDestroy();
    mServiceHandler.removeCallbacks(yourRunnable);
    mServiceLooper.quit();
}

<强>定时器

创建你的计时器:

private Timer myTimer = new Timer();

创建定期计时器任务:

private void scheduleTask() {
    myTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            //Do DB stuff here
        }
    }, 0, ALARM_INTERVAL);
}

参考文献:
Scheduling Repeating Alarms
Creating a Service

答案 1 :(得分:0)

要延迟重复,您可以创建一个runnable,调用postDelayed处理程序,在设定的时间段后重新启动它。

//change the notificationSmallIcon (titlebar) so it flashes every few seconds
private static Runnable iconWarnRunnable = new Runnable() {
    @Override
    public void run() {
        if (isWarningRunning) {
            long dely;
            if (notificationSmallIcon == R.drawable.ic_launcher2) {
                notificationSmallIcon = R.drawable.ic_launcher2x;
                dely = iconWarnDelay1;
            } else {
                notificationSmallIcon = R.drawable.ic_launcher2;
                dely = iconWarnDelay2;
            }
            notifyHandler.postDelayed(this, dely);
            myShowNotification();
        } else {
            //just in nick of time
            notificationSmallIcon = R.drawable.ic_launcher2;
        }
    }
};

final HandlerThread myThread = new HandlerThread("myHandlerThread");
private static long iconWarnDelay1;
private static long iconWarnDelay2;


@Override
public void onCreate() {
    iconWarnDelay1 = 2500;
    iconWarnDelay2 = 500;
    myThread.start();
    myThread.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    notifyHandler = new Handler(myThread.getLooper());

......在你开始运行的某个地方,非常重要的是,当你开始时先移除它,这样你就可以只运行一次。

isWarningRunning = true;
notifyHandler.removeCallbacks(iconWarnRunnable);
notifyHandler.postDelayed(iconWarnRunnable, iconWarnDelay1);

...某处停止可运行的

isWarningRunning = false;
notifyHandler.removeCallbacks(iconWarnRunnable);