完成后如何让Android服务自行停止?

时间:2016-03-03 05:34:34

标签: android android-service

我在我的应用程序中实现了一项服务。我想在上传任务完成后自行停止服务。我试图检测网络,当wifi或移动网络可用时,然后开始在服务器上上传我的数据,并在完成上传任务后以onCreate()方法停止服务本身。我在服务启动时记录了一条消息,但我不明白为什么即使在通话this.stopSelf()之后它也会不断打印停止服务的消息。如何在Android中正确使用服务?

这是我的服务代码。

public class ServiceTest extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        mTimer = new Timer();
        mTimer.schedule(timerTask, 2000, 15 * 1000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private Timer mTimer;

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run()
        {
            getConnectivityStatusString(getApplicationContext());
        }
    };

    public String getConnectivityStatusString(Context context) {
        int conn = Constant.getConnectivityStatus(context);
        String status = null;
        if (conn == Constant.TYPE_WIFI)
        {
            status = "Wifi enabled";
            Log.e("", " status = " + status);

            ConnectivityManager conMgr =  (ConnectivityManager)context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            {
                NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
                if (netInfo == null)
                {
                    Log.e(" Not "," Accessible !!!");
                }
                else
                {

                    Log.e(" Start ", " To Loading !!!!");
                    //new Welcome_Page().execute();
                    this.stopSelf();
                    Log.e(" Stop ", " The Service !!!!");
                }
            }

        } else if (conn == Constant.TYPE_MOBILE) {
            status = "Mobile data enabled";
            Log.e(""," status = "+status);
            this.stopSelf();
            Log.e(" Stop ", " The Service !!!!");
        } else if (conn == Constant.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
            Log.e(""," status = "+status);
        }
        return status;
    }

    public void onDestroy() {
        try {
            mTimer.cancel();
            timerTask.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Intent intent = new Intent("com.android.techtrainner");
        intent.putExtra("yourvalue", "torestore");
        sendBroadcast(intent);
    }
}

这是我的BroadcastReceiver类代码。

public class ReceiverCall extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        context.startService(new Intent(context, ServiceTest.class));
    }
}

这是我的网络代码。

public class Constant
{
    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;


    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)

                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }
}

3 个答案:

答案 0 :(得分:2)

在清单中尝试这些

<service
    android:name=".ServiceTest"
    android:stopWithTask="true" />

对于程序,停止服务: -

stopService(new Intent(YOUR_CONTEXT.this, ServiceTest.class)) 

答案 1 :(得分:0)

您必须在此 onStartCommand 方法

上返回 START_NOT_STICKY
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return START_NOT_STICKY;
}

在您可以随时编写停止服务的 stopSelf(); 方法之后。 在menifest文件中添加您的服务,如

<service
        android:name=".YourService"
        android:enabled="true"
        android:exported="true" >
    </service>

答案 2 :(得分:0)

如果您希望服务在执行某项特定任务后自行停止

最好使用IntentService而不是Service class

您可以在此处找到更多信息

http://developer.android.com/guide/components/services.html

查找IntentService部分