有谁知道如何在android中重启服务?我有一个服务,当设备启动时调用..我有一个option.java用于保存我的配置..
如果我在option.java中编辑配置,那么我必须重新启动我的服务才能生效..
我只知道如何启动服务并在运行后,我不知道如何在进行新配置后重新启动它...任何想法?
startService(new Intent(this, ListenSMSservice.class));
答案 0 :(得分:3)
停止服务并重新启动
stopService(new Intent(this, ListenSMSservice.class));
startService(new Intent(this, ListenSMSservice.class));
答案 1 :(得分:1)
在你的元素中:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2)在你的元素中(确保为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);
}
}
有关详细说明:this
答案 2 :(得分:0)
所以observer-observable design pattern,我的意思是使用Android提供的FileObserver类。
例如,这是来自android的源代码WallPaperManagerService.jav的片段:
因此,在您的情况下,您将在配置文件上创建一个文件观察器(请参阅下面的示例代码),每次此配置文件更改时,您将读取(已在运行)服务中的所有值。
希望你有这个想法的精髓。
/**
* 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();
}
}
}
};