has anyone know how to restarting a service in android?? i have a service that called when device is booting.. and i have an option.java for saving my configuration..
if i editing a configuration in option.java, then i must restarting my service to takes the effect..
i only know how to start a开发者_运维技巧 service and after it running, i don't know how to restart it after a new configuration was made.. any idea??
startService(new Intent(this, ListenSMSservice.class));
Just stop the service and start it again
stopService(new Intent(this, ListenSMSservice.class));
startService(new Intent(this, ListenSMSservice.class));
In your element:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) In your element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver):
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class MyBroadcastreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}
for more elaboration : this
So by observer-observable design pattern, I meant making use of FileObserver class provided by Android.
For example, here is a snippet from WallPaperManagerService.java from android's source code:
So, in your case, you would create a file observer (see sample code below) on the config file, and each time this config file changes, you will read all the values from your (already running) service.
Hope you got the essence of the idea.
/**
* Observes the wallpaper for changes and notifies all IWallpaperServiceCallbacks
* that the wallpaper has changed. The CREATE is triggered when there is no
* wallpaper set and is created for the first time. The CLOSE_WRITE is triggered
* everytime the wallpaper is changed.
*/
private final FileObserver mWallpaperObserver = new FileObserver(
WALLPAPER_DIR.getAbsolutePath(), CREATE | CLOSE_WRITE | DELETE | DELETE_SELF) {
@Override
public void onEvent(int event, String path) {
if (path == null) {
return;
}
synchronized (mLock) {
// changing the wallpaper means we'll need to back up the new one
long origId = Binder.clearCallingIdentity();
BackupManager bm = new BackupManager(mContext);
bm.dataChanged();
Binder.restoreCallingIdentity(origId);
File changedFile = new File(WALLPAPER_DIR, path);
if (WALLPAPER_FILE.equals(changedFile)) {
notifyCallbacksLocked();
}
}
}
};
精彩评论