我想写一个Android应用程序,它记录所有拍摄的照片,通过照片uri,时间戳和地理位置标记进入文本文件。这应该在点击照片时发生。
为此,我正在运行一个在默认照片目录中使用FileObserver的服务。 (我知道这不是万无一失的)。
用户最初受到GUI的欢迎,这将让他选择文件名和开始按钮开始录制。当用户按下开始录制时,后台服务启动,用户返回拍摄一些照片,1当他回来时,他应该有一个停止录制选项,结束后台服务。
现在我的问题是这个,
1.活动如何知道服务何时运行以及何时不运行?
2.活动的先前状态如何恢复并重新连接到特定服务?至于当我恢复活动时,活动与服务的关联如何发生? (如果我的活动必须停止服务,则认为某种关联是必要的)
以下是我的参考代码:[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;
}
}
}
答案 0 :(得分:1)
您不需要与服务“连接”即可将其从活动中停止。你可以这样做:
Intent intent = new Intent(this, ExperienceLoggerService.class);
stopService(intent);
我不确定您是否真的需要知道您的服务是否正在运行。如果您确实需要这样做,可以使用ActivityManager.getRunningServices()
执行此操作,请参阅http://developer.android.com/reference/android/app/ActivityManager.html#getRunningServices%28int%29
编辑:关于绑定服务的说明
您没有发布活动与服务绑定的代码,但在再次查看源代码后,我发现您使用的是绑定服务。在这种情况下,您的活动只需调用unbindService()
即可将调用ServiceConnection
时使用的bindService()
对象传递给它。一旦服务没有绑定客户端,它就会自行关闭。