这是我前段时间写的记录CPU频率的服务的修改代码片段。它缺少Application
和Activity
部分,但说明了我如何编写Service
来保持每十秒记录一次。当手机进入深度睡眠状态时,它不记录,所以如果你想不中断地登录,那么你将需要获得PARTIAL_WAKE_LOCK
s,但考虑到电池寿命将因此而严重降低。
public class YOURCLASS_Service extends Service {
private long mStartTime = 0L;
private final Handler mHandler = new Handler();
private Runnable mUpdateTimeTask;
private YOURAPP app;
@Override
public void onCreate() {
super.onCreate();
app = (YOURAPP) getApplicationContext();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service finished.", Toast.LENGTH_SHORT).show();
stopLog();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (app.isRunning())
return START_STICKY;
try {
File file = new File(Environment.getExternalStorageDirectory(), "yourlog.csv");
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file, false));
out.write("Log title");
out.close();
} catch (java.io.IOException e) {
stopLog();
Toast.makeText(this, "Error creating log file. Aborting.", Toast.LENGTH_SHORT).show();
}
mUpdateTimeTask = new Runnable() {
public void run() {
long millis = SystemClock.uptimeMillis() - mStartTime;
int seconds = (int) (millis/1000);
int minutes = seconds/60;
seconds = seconds % 60;
readYourSensors();
if (!writeLog (str)) stopLog();
mHandler.postAtTime(this, mStartTime + (((minutes * 60) + seconds + 10) * 1000));
mHandler.postDelayed (mUpdateTimeTask, 10000);
}};
mStartTime = SystemClock.uptimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
Notification notification = new Notification(R.drawable.notification_icon, "App title", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, YOURCLASS.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), "App title", "Please see /sdcard/yourlog.csv", contentIntent);
startForeground(startId, notification);
app.isRunning(true);
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void stopLog() {
mHandler.removeCallbacks(mUpdateTimeTask);
}
}
杰夫阿特伍德已经关闭了这个问题的原始副本,所以我想我们应该保持这一个开放。 – 2011-04-25 22:11:26