如何确保执行一段代码?

时间:2014-05-29 05:21:11

标签: android multithreading android-asynctask android-service

我对如何运行Android应用程序的一段代码有疑问。

这段代码对于运行所有代码非常重要,并且需要一定量的处理而不需要与用户进行迭代。

我怀疑它应该在哪里运行,我确信它不应该在Activity或AsyncTask中。

不知道是线程还是服务,因为我认为它本身不是服务。 如果一个线程,如果应用程序关闭,暂停或关闭所有活动,我会怀疑会发生什么......

4 个答案:

答案 0 :(得分:3)

如果您不确定您的代码是否正在运行,那么您可以使用Log来确定。

如果它在您的logcat上,则使用Log.i("Classname", "Executed");表示它已被执行。

了解有关此处记录的详情:Log

答案 1 :(得分:2)

将代码放在后台service中,并将该服务设置为在启动时自动启动:

  <receiver android:name="com.example.MyService">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
  </receiver>

通过这种方式,您将有机会执行一些代码,无需用户打开应用程序UI。

答案 2 :(得分:0)

问题:如何确保执行一段代码?

答案:只需使用Log.i("key", "I am here");

即可

然后转到logcat并搜索关键字密钥,如果您发现与密钥对应的我在这里,则表示您的代码已成功执行到这一行,否则返回并使用此方法以相同的方式对代码的安静存在疑问,您可以在单个活动中使用 multiple log.i ,即使在每一行也是如此。 如果您希望自己快速轻松地解决问题,我的个人建议总是使用logcat。

以下是一些相关要点:

注意:以下给出的内容不是我的,我是从here

获取的
    Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch statment. You know and error has occurred and therefore you're logging an error.

    Log.w: Use this when you suspect something shady is going on. You may not be completely in full on error mode, but maybe you recovered from some unexpected behavior. Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind of like a "hey, this happened, and it's weird, we should look into it."

    Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.

    Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so you can log the exact flow of your program, use this. If you want to keep a log of variable values, use this.

    Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason you've decided to log every little thing in a particular part of your app, use the Log.v tag.

And as a bonus...

    Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those catch blocks where you're catching errors that you never should get...yea, if you wanna log them use Log.wtf

非常感谢Kurtis Nusbaum和Jakobud。

答案 3 :(得分:0)

在您的函数中,添加一个日志,以便您可以查看它是否已执行。

样品:

private void sampleFxn(){
  some code here...
  Log.d("YourTag", "Executed");
}