java - 线程在几次迭代后被杀死

标签 java android multithreading

我正在尝试创建一个应用程序,其中包含一项在设备启动时启动的服务,然后记录一些事件。

ma​​nifest.xml 中的服务条目

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

        <category android:name="android.intent.category.HOME" />
    </intent-filter>
</receiver>
<service android:name="com.myservices.MyService" >
</service>

BReceiver.java

public class BReceiver extends BroadcastReceiver {

    private static final String TAG = "BReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "onReceive started");
        // Main Logging Service
        Intent service = new Intent(context, MyService.class);
        context.startService(service);
        Log.e(TAG, "onReceive ended");
    }

}

MService.class

public class MyService extends IntentService {

    private static final String TAG = "MyService";
    private static final long TIMER = 2000;

    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        startLogginThread();

    }

    /**
     * For logging
     */
    private void startLogginThread() {
        Thread thread = new Thread() {
            public void run() {
                while (true) {
                    try {

                        // Logging events
                        myLogger();
                        Log.e(TAG, "Awake");
                        // TIMER
                        Thread.sleep(TIMER);
                    } catch (Exception e) {
                        Log.e("MyService", "local Thread error "+ e.toString());
                    }
                }
            }
        };
        thread.start();
    }

    private void myLogger() {

        // Creating new file to store logs.
        // Check if SD card is available else use internal memory.
        File dir = null;
        if (MyServiceUtil.isExternalStorageReadable() && MyServiceUtil.isExternalStorageWritable()) {
            // External Memory
            File sdCard = Environment.getExternalStorageDirectory();
            dir = new File(sdCard.getAbsolutePath() + "/MyLogger");
            dir.mkdirs();
        } else {
            // Internal Memory
            dir = getFilesDir();
        }

        // Rename to txt for reading
        File file = new File(dir, "log.txt");

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                Log.e(TAG, "Exception :" + e.toString());
            }
        }

        // Printing timestamp in file
        try {

            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
            String timeStamp = new SimpleDateFormat("dd.MM.yyyy '-' HH:mm:ss").format(Calendar.getInstance().getTime());
            out.println(timeStamp);

            // Log Location

            out.close();
            Log.e("Logggging", timeStamp);
        } catch (IOException e) {
            Log.e(TAG, "Exception :" + e.toString());
        }

    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy called");
        super.onDestroy();
    }

}

结果: 只有几次,比如 6-7 次,日志被打印并存储在文件中。 以下是日志:

11-16 17:00:02.438: E/BReceiver(3187): onReceive started
11-16 17:00:02.438: E/BReceiver(3187): onReceive ended
11-16 17:00:02.458: E/MyService(3187): onDestroy called
11-16 17:00:02.458: D/MyServiceUtil(3187): isExternalStorageReadable started
11-16 17:00:02.468: D/MyServiceUtil(3187): isExternalStorageWritable started
11-16 17:00:02.468: E/Logggging(3187): 16.11.2014 - 17:00:02
11-16 17:00:02.468: E/MyService(3187): Awake
11-16 17:00:04.468: D/MyServiceUtil(3187): isExternalStorageReadable started
11-16 17:00:04.468: D/MyServiceUtil(3187): isExternalStorageWritable started
11-16 17:00:04.478: E/Logggging(3187): 16.11.2014 - 17:00:04
11-16 17:00:04.478: E/MyService(3187): Awake
11-16 17:00:06.478: D/MyServiceUtil(3187): isExternalStorageReadable started
11-16 17:00:06.488: D/MyServiceUtil(3187): isExternalStorageWritable started
11-16 17:00:06.488: E/Logggging(3187): 16.11.2014 - 17:00:06
11-16 17:00:06.488: E/MyService(3187): Awake
11-16 17:00:08.488: D/MyServiceUtil(3187): isExternalStorageReadable started
11-16 17:00:08.488: D/MyServiceUtil(3187): isExternalStorageWritable started
11-16 17:00:08.488: E/Logggging(3187): 16.11.2014 - 17:00:08
11-16 17:00:08.488: E/MyService(3187): Awake

另外,我不明白为什么,如果线程已经在运行,则调用 onDestroy:

11-16 17:00:02.458: E/MyService(3187): onDestroy 被调用

PS - 这仅发生在 Kitkat 中。

最佳答案

你不太了解IntentService。 onHandleIntent方法是在框架启动的子线程中调用的,当onHandleIntent完成时,该Service将自行终止,因此原因是您将作业放在了您启动的新线程中。因此,您应该将代码放入 onHandleIntent 中。

while (true) {
  try {

     // Logging events
     myLogger();
     Log.e(TAG, "Awake");
     // TIMER
     Thread.sleep(TIMER);
  } catch (Exception e) {
    Log.e("MyService", "local Thread error "+ e.toString());
  }
}

关于java - 线程在几次迭代后被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26956514/

相关文章:

Android - 如何在微调器上获取所选项目的另一个值

c++ - XCode std::thread C++

java - 并发 HashMap 删除复杂值

java - 如何在 Eclipse 中跨项目共享源文件夹?

java - 找不到所需的类(javax.activation.DataHandler 和 javax.mail.internet.MimeMultipart)。附件支持已禁用

java - JGit 在工作副本中检测重命名

java - 连接两个表 Hibernate

android - RSS 提要空指针异常

java - 具有自定义数据源的 Android 分页库在 RecyclerView 中偏移项目

c# - 是否可以使用 ISynchronizeInvoke.BeginInvoke() 重载线程?