我想编写一个 android 应用程序,通过在带有照片 uri、时间戳和地理位置标记的文本文件中输入一个条目来记录所有拍摄的照片。这应该在单击照片时发生。
为此,我正在运行一个在默认照片目录上使用 FileObserver 的服务。(我知道这不是万无一失的)。
用户最初会受到 GUI 的欢迎,该 GUI 将允许他选择文件名和开始按钮以开始录制。当用户按下开始录制时,后台服务启动,用户返回拍摄一些照片,1 当他回来时,他应该可以选择停止录制,从而结束后台服务。
现在我的问题是这样的,
1.活动如何知道服务何时运行,何时不运行?
2. Activity 之前的状态如何恢复并重新连接到特定的服务?当我恢复活动时,活动与服务的关联是如何发生的?(如果我的活动必须停止服务,则需要某种关联)
这是我的参考代码:[ExperienceLoggerService 是 MainActivity 的内部类]
public class ExperienceLoggerService extends Service
/* This is an inner class of our main activity, as an inner class makes good use of resources of outer class */
{
private final IBinder mBinder = new LocalBinder();
File file;
FileOutputStream fOut;
OutputStreamWriter fWrite;
/** Called when the activity is first created. */
private void startLoggerService()
{
try
{
//initialise the file in which to log
this.file = new File(Environment.getExternalStorageDirectory(), "MyAPPNostalgia");
System.out.println("1:"+Environment.getExternalStorageDirectory()+ "MyAPPNostalgia");
file.createNewFile();
fOut = new FileOutputStream(file);
fWrite = new OutputStreamWriter(fOut);
}
catch(Exception e)
{
System.out.println("Error in logging data, blame navjot");
}
FileObserver observer = new MyFileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/100MEDIA");
observer.startWatching(); // start the observer
}
@Override
public void onCreate()
{
super.onCreate();
//mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
startLoggerService();
// Display a notification about us starting. We put an icon in the
// status bar.
//showNotification();
}
public void onDestroy()
{
try
{
//close the file, file o/p stream and out writer.
fWrite.close();
fOut.close();
}
catch(Exception e)
{
}
super.onDestroy();
}
class MyFileObserver extends FileObserver
{
public MyFileObserver(String path)
{
super(path);
}
public void onEvent(int event, String file)
{
if(event == FileObserver.CREATE && !file.equals(".probe"))
{ // check if its a "create" and not equal to .probe because thats created every time camera is launched
String fileSaved = "New photo Saved: " + file +"\n";
try
{
ExperienceLoggerService.this.fWrite.append(fileSaved);
}
catch(Exception e)
{
System.out.println("Problem in writing to file");
}
}
}
}
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
public class LocalBinder extends Binder
{
ExperienceLoggerService getService()
{
return ExperienceLoggerService.this;
}
}
}