如何在android中重启服务



有人知道如何在android中重新启动服务吗??我有一个服务,当设备启动时调用…我有一个option.java来保存我的配置。

如果我在option.java中编辑了一个配置,那么我必须重新启动我的服务才能生效。

我只知道如何启动一个服务,在它运行后,我不知道如何在新的配置后重新启动它。任何想法?

startService(new Intent(this, ListenSMSservice.class));

请停止服务并重新启动

stopService(new Intent(this, ListenSMSservice.class));
startService(new Intent(this, ListenSMSservice.class));

在你的元素中:

<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

所以我所说的observer-observable设计模式是指利用Android提供的FileObserver类。

例如,下面是来自android源代码的WallPaperManagerService.java的一个片段:

因此,在您的示例中,您将在配置文件上创建一个文件观察者(请参阅下面的示例代码),并且每次该配置文件更改时,您将从(已经运行的)服务中读取所有值。

希望你明白了这个想法的精髓。

/**
 * 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();
                    }
                }
            }
        };

最新更新