我正在尝试创建一个包含在设备启动时启动的服务的应用程序。然后记录一些事件。
manifest.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。
答案 0 :(得分:1)
要在BroadcastReceiver中执行后台任务,您需要调用goAsync(),sdk 11+,并在完成调用后调用PendingResult.finish()
这可以由onReceive(Context,Intent)中的应用程序调用 允许它在返回后保持广播活动 功能。这并没有改变相对的期望 响应广播(在10秒内完成),但确实允许 将与之相关的工作移动到另一个线程的实现 避免因磁盘IO而导致主UI线程出现故障。
您可以在接收器中移动代码并使用 goAsync 或直接在IntentService中运行代码,因为它不像Service,它有自己的后台线程。
<强>更新强>
final PendingResult pendingResult = goAsync();
new Thread() {
public void run() {
while (SOME_CONDITION) {
try {
// Logging events
myLogger();
Log.e(TAG, "Awake");
// TIMER
Thread.sleep(TIMER);
} catch (Exception e) {
Log.e("MyService", "local Thread error "+ e.toString());
}
}
// Finish the broadcast.
pendingResult.finish();
}
}.start();
答案 1 :(得分:1)
你不太了解IntentService。 onHandleIntent的方法是在框架启动的子线程中调用的,当onHandleIntent完成时,此服务将自行终止,因此他的理由是你将作业放在你启动的新线程中。所以,你应该把代码放到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());
}
}