Android - 如何在重新启动之前停止服务之前的执行?

发布于 2024-11-04 08:44:02 字数 2957 浏览 5 评论 0原文

我正在尝试从我的 PreferenceActivity 启动服务。我想在每个 onPreferenceChangeListenr 上启动一个服务。

我的 onPreferenceChangeListener 中有四个条件,每个条件都必须以不同的值启动相同的服务。

当我第一次更改首选项时,它会启动服务,当我第二次更改首选项时,它会以新值启动服务,但它不会停止先前条件的执行,所以现在我有一个正在生成结果的服务两个条件,如果我第三次更改首选项,它会开始生成三个条件的结果,但我需要的是仅针对当前条件运行此服务。

这是我的 PreferenceActivity 代码:-

public class Preferences extends PreferenceActivity
{
private Button button;
ListPreference lp;
private Context context;
private long duration;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    context = this;
    lp = (ListPreference)findPreference("autoduration");
    final Intent intent = new Intent(context, BackService.class);
    lp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
    {
        public boolean onPreferenceChange(Preference preference, Object newValue)
        {
            String newSelection = newValue.toString();
            int index = lp.findIndexOfValue(newSelection);
            stopService(intent);
            if(index==0)
            {
                duration = 15000;
            }
            else if(index==1)
            {
               duration = 12000;
            }
            else if(index==2)
            {
                duration = 10000;
            }
            else if(index==3)
            {
                IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
                filter.addAction(Intent.ACTION_SCREEN_OFF);
                BroadcastReceiver receiver = new ScreenReceiver();
                registerReceiver(receiver, filter);
            }
            intent.putExtra("duration", duration);
            startService(intent);
            return true;
        }
    });


}
@Override
public void onDestroy()
{
    super.onDestroy();
    unregisterReceiver(receiver);
}
}

它是我的服务代码,应该受到我的 PreferenceActivity 的影响。 :-

private static Timer myTimer = new Timer();
public static final String TAG = "BackService";
private MainTask mainTask = new MainTask();    

 public void onStart(Intent intent, int startId)
    {
        Long duration = intent.getLongExtra("duration", 7000);
        startServices(duration);
    }

public void startServices(Long dur)
    {
        myTimer.scheduleAtFixedRate(mainTask,0,dur);
    }
private class MainTask extends TimerTask
    {
        @Override
        public void run() {
            Log.e(TAG, "I am HERE");
        }
    }

这是我的广播接收器:-

public class ScreenReceiver extends BroadcastReceiver {
public static boolean screenOn = true;
private static final String TAG = "ScreenReceiver";

@Override
public void onReceive(Context context, Intent intent)
{
    if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
    {
        Log.e(TAG, "I am receiver");
    }
}
}

我不知道我做错了什么,所以请帮助!

谢谢

I am trying to start a Service from my PreferenceActivity. I want to start a service on every onPreferenceChangeListenr.

I have four conditions in my onPreferenceChangeListener and each condition has to start same Service with different values.

When i change the preference for the first time it starts the service and when i change the preference second time it starts the service with new value but it does not stop the execution of the previous condition so now i have a service which is producing results for two conditions and if i change the preference third time, it starts producing result for three condition but what i need is to run this service only for the current condition.

Here is my PreferenceActivity's code:-

public class Preferences extends PreferenceActivity
{
private Button button;
ListPreference lp;
private Context context;
private long duration;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    context = this;
    lp = (ListPreference)findPreference("autoduration");
    final Intent intent = new Intent(context, BackService.class);
    lp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
    {
        public boolean onPreferenceChange(Preference preference, Object newValue)
        {
            String newSelection = newValue.toString();
            int index = lp.findIndexOfValue(newSelection);
            stopService(intent);
            if(index==0)
            {
                duration = 15000;
            }
            else if(index==1)
            {
               duration = 12000;
            }
            else if(index==2)
            {
                duration = 10000;
            }
            else if(index==3)
            {
                IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
                filter.addAction(Intent.ACTION_SCREEN_OFF);
                BroadcastReceiver receiver = new ScreenReceiver();
                registerReceiver(receiver, filter);
            }
            intent.putExtra("duration", duration);
            startService(intent);
            return true;
        }
    });


}
@Override
public void onDestroy()
{
    super.onDestroy();
    unregisterReceiver(receiver);
}
}

And its my service code which should be affected by my PreferenceActivity. :-

private static Timer myTimer = new Timer();
public static final String TAG = "BackService";
private MainTask mainTask = new MainTask();    

 public void onStart(Intent intent, int startId)
    {
        Long duration = intent.getLongExtra("duration", 7000);
        startServices(duration);
    }

public void startServices(Long dur)
    {
        myTimer.scheduleAtFixedRate(mainTask,0,dur);
    }
private class MainTask extends TimerTask
    {
        @Override
        public void run() {
            Log.e(TAG, "I am HERE");
        }
    }

Here is my BroadcastReceiver :-

public class ScreenReceiver extends BroadcastReceiver {
public static boolean screenOn = true;
private static final String TAG = "ScreenReceiver";

@Override
public void onReceive(Context context, Intent intent)
{
    if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
    {
        Log.e(TAG, "I am receiver");
    }
}
}

I don't know what i am doing wrong so Please Help!!

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮坠入山谷 2024-11-11 08:44:02

您的服务可能会在您没有意识到的情况下重新启动。但是,您会遇到问题,因为在这种情况下,myTimer 不会被拆除。您需要在类中实现 onDestroy 方法,确定您的服务是否停止(因为正在调用 stopSelf 或 Context.stopService 的某个地方) )。

如果是这样,您应该从 myTimer 变量中删除 static 修饰符,以便它不会在服务启动之间和 onDestroy 中徘徊。 code> 方法,您需要调用 myTimer.cancel() 来停止它,否则它只会挂起,您将无法引用它来取消它。

startServices 方法中,在调用 myTimer.scheduleAtFixedRate 之前添加以下内容:

mainTask.cancel();
mainTask = new MainTask();

Your service may be getting restarted without you realizing. However, you have a problem because in that case, the myTimer is not getting torn down. You need to implement the onDestroy method in your class, determine if your service is getting stopped (because somewhere stopSelf or Context.stopService is being called).

If so, you should remove the static modifier from the myTimer variable, so that it doesn't hang around between starts of the service and in the onDestroy method you need to call myTimer.cancel() to stop it, since otherwise it will just hang around and you won't have any reference to it to cancel it.

In your startServices method, add the following before the call to myTimer.scheduleAtFixedRate:

mainTask.cancel();
mainTask = new MainTask();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文