为什么stopService(Intent)和stopSelf()方法不会停止我的独特服务?

时间:2019-09-15 19:23:41

标签: java android android-studio

嗨,朋友,我有一个IntentService,我想从IntentService停止stopSelf()停止它,但是我不工作,我试图通过stopService(Intent)从主要活动中停止它,但我也不能正常工作。 谢谢你的朋友,顺便说一句,我添加了以下内容:

right

这是我的IntentService代码:

function getSpiral(data) {
    var array = data.map(j => JSON.parse(j)),
        upper = 0,
        lower = array.length - 1,
        left = 0,
        right = array[0].length - 1,
        i = upper,
        j = left,
        result = [];

    while (true) {
        if (upper++ > lower) break;

        for (; j < right; j++) result.push(array[i][j]);
        if (right-- < left) break;

        for (; i < lower; i++) result.push(array[i][j]);
        if (lower-- < upper) break;

        for (; j > left; j--) result.push(array[i][j]);
        if (left++ > right) break;

        for (; i > upper; i--) result.push(array[i][j]);
    }
    result.push(array[i][j]);

    return result.join(',');
}

console.log(getSpiral(['[4, 5, 6, 5]', '[1, 1, 2, 2]', '[5, 4, 2, 9]']));
console.log(getSpiral(['[1, 2, 3, 4, 5]', '[6, 7, 8, 9, 10]', '[11, 12, 13, 14, 15]', '[16, 17, 18, 19, 20]']));

这是我的MainActivity:

<service android:name=".MiIntentService"></service>

1 个答案:

答案 0 :(得分:0)

您可以使用简单的服务而不是Intent Service,后者可以在需要时更容易立即停止。 否则,您可以使用此方法。 首先像这样在Manifest.xml中声明一个服务进程。这将使您的服务在单独的线程上运行。

<service 
android:name=".MiIntentService"
android:exported="false"
android:process=":myservice">
</service>

然后,当您想终止服务时,请调用此方法:

 public void killService(){


       ActivityManager am = (ActivityManager) getLMvdActivity().getSystemService(ACTIVITY_SERVICE);
       List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();

       Iterator<ActivityManager.RunningAppProcessInfo> iter = runningAppProcesses.iterator();

       while(iter.hasNext()){
           ActivityManager.RunningAppProcessInfo next = iter.next();

           String pricessName = getLMvdActivity().getPackageName() + ":myservice"; //i.e the process you named for your service

           if(next.processName.equals(pricessName)){
               Process.killProcess(next.pid);
               break;
           }
       }

   }

这将立即终止您的Intent服务。

有关更多信息,请查看此答案。 https://stackoverflow.com/a/23444116/7392868

相关问题