当应用程序在后台时停止服务 [英] Stop a service when application is in background

查看:84
本文介绍了当应用程序在后台时停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android的新手,正在创建一个MAC欺骗应用程序.我创建了一个IntentService来欺骗应用程序中每5秒钟的MAC地址,它工作正常.然后,我创建了一个BaseActivity,我的所有活动都从此扩展,这样我就可以检测到应用何时在后台运行,这也可以正常工作.我已经拥有了它,因此当应用程序在后台运行时,MAC地址不再更改并返回其原始状态,但是我想代替它,只是在应用程序在后台运行时停止服务,而在应用程序在运行时重新启动服务再次打开.到目前为止,这是我的代码:

I'm new to android and I am creating a MAC spoofing app. I have created an IntentService to spoof the MAC address in the app every 5 seconds and it is working fine. Then I created a BaseActivity which all of my activities extend from, this is so I can detect when the app goes in the background or not, this is also working fine. I already have it so when the app is in the background, the MAC address no longer changes and goes back to its original, but instead of this I want to just stop the service when the app is in background and restart the service when the app is opened again. Here is my code so far:

BaseActivity

BaseActivity

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

public class BaseActivity extends Activity {
    private static int sessionDepth = 0;
    public static boolean isInBackground = false;
    WifiManager wifiManager;
    private Intent myIntent;



    // app in foreground
    @Override
    protected void onStart() {
        super.onStart();
        sessionDepth++;
        isInBackground = false;

        // for MAC spoofing
        myIntent = new Intent(this, IntentService.class);
        startService(myIntent);

    }

    // app in background
    @Override
    protected void onStop() {
        super.onStop();
        if (sessionDepth > 0)
            sessionDepth--;
        if (sessionDepth == 0) {
            Toast.makeText(getApplicationContext(), "App is in background",
                    Toast.LENGTH_SHORT).show();
            isInBackground = true;
            Log.d("My log2", "background " + isInBackground);
            wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(false); // restart wifi
            wifiManager.setWifiEnabled(true);
            stopService(myIntent);
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        stopService(myIntent);
    }

    public boolean getStatus(){
        return isInBackground;
    }

}

IntentService

IntentService

package edu.fiu.mpact.reuproject;

import android.content.Intent;
import android.net.wifi.WifiManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;


    public class IntentService extends android.app.IntentService {
        Process p = null;
        String[] ouiList;
        Random gen = new Random();
        char[] charList = {'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9'};


        public IntentService() {
            super("MAC");
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            try {
                ouiList = loadOUIs();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                p = Runtime.getRuntime().exec("su");  // prompt for root access
            } catch (IOException e) {
                e.printStackTrace();
            }
            new Timer().scheduleAtFixedRate(new TimerTask() {
                BaseActivity b = new BaseActivity();

                @Override
                public void run() {
                  Log.d("my log2", b.getStatus() + "");

                    try {
                        if(!b.getStatus()) {
                            changeMac();
                        }

                        Log.d("my log3", Utils2.getMACAddress("wlan0"));
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, 0, 5000); // changes MAC every 3 seconds



        }
        private void changeMac() throws IOException, InterruptedException {
            String mac = generateMac();

            //commands to execute
            String[] cmds = {"ip link set wlan0 address " + mac};

            // execute the commands
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            for (String tmpCmd : cmds) {
                os.writeBytes(tmpCmd + "\n");
            }

        }
        private String generateMac(){
            String s = ouiList[gen.nextInt(20847)] + ":";

            for(int i = 0; i < 6; i++){
                s = s + charList[gen.nextInt(16)];

                //add colon
                if(((i + 1) % 2 == 0) && i != 5){
                    s = s + ":";
                }
            }

            return s;
        }

        private String[] loadOUIs() throws IOException {
            String[] ouiList = new String[20847];

            int i = 0;
            InputStream inStream = getApplicationContext().getResources().openRawResource(R.raw.oui2);
            InputStreamReader is = new InputStreamReader(inStream);
            BufferedReader reader = new BufferedReader(is);

            String word = reader.readLine();  //read first OUI
            while(word != null){             //continue until no more OUI's
                ouiList[i] = word;
                word = reader.readLine();
                i++;
            }

            return ouiList;

        }


    }

由于某种原因,尽管我调用了stopService(),但当应用程序进入后台时,该服务仍未停止.

For some reason the service is not stopping when the app goes to background, despite my stopService() calls.

推荐答案

由于某种原因,当应用程序进入后台时,服务不会停止

For some reason the service is not stopping when the app goes to background

它在您调用stopService()之前很久就停止了,因为一旦onHandleIntent()返回,它就在创建后的毫秒数内停止了.

It stopped long before your stopService() call, as it stopped once onHandleIntent() returned, milliseconds after it was created.

没有停止的是您的Timer,它在后台线程上运行,并且将继续运行,直到您取消它或进程终止.

What is not stopping is your Timer, which runs on a background thread and will continue running until you cancel it or your process terminates.

恕我直言,这是对IntentService的不当使用.如果要控制寿命,请使用Service,然后在onDestroy()中停止后台工作.

IMHO, this is an inappropriate use of IntentService. If you want to control the lifespan, use a Service, and stop background work in onDestroy().

这篇关于当应用程序在后台时停止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆