我想写一个android应用程序,它记录通过使用照片uri,时间戳和地理位置戳进入文本文件所拍摄的所有照片。这应该在点击照片时发生。
为此,我正在运行在默认照片目录上使用FileObserver的服务。 (我知道这不是傻瓜证明)。
在Android中恢复活动状态
用户最初受到GUI的欢迎,该GUI将允许他选择文件名和开始按钮以开始录制。当用户按下开始录制时,后台服务启动并且用户返回拍摄一些照片,1当他回来时他应该有一个停止录制的选项,这将结束后台服务。
现在我的问题是这样的
1.活动如何知道服务何时运行以及何时不运行?
2. Activity的前一状态如何恢复并重新连接到特定服务?就像我在恢复活动时活动与服务的关联是如何发生的? (consedring某种关联是必要的,如果我的活动已停止服务)
这里是我的参考代码:[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;
}
}
}
但是当我回到我的应用程序时,我的服务已经在运行(我早就开始了)。我没有得到的是如何创建一个新的意图,并调用stopService停止我以前的服务? – deepak
这就是你如何停止服务。通过调用'stopService()'并传递一个描述你想停止服务的'Intent'。 –
对不起,我没有意识到你正在使用**绑定服务**。我已经更新了我的答案以反映这一点。有不同的方式来使用服务,'startService()/ stopService()'就是其中之一。你也可以使用'bindService()/ unbindService()'。 –