应用程序关闭后,保持连接广播接收器运行

时间:2016-05-12 14:50:20

标签: java android

当我需要使用互联网连接并且它不可行时,我想设置一个广播接收器,如果应用程序关闭,它将继续工作。

我正在使用一项服务,但它不起作用。当应用程序在屏幕上或暂停时它可以正常工作但如果我关闭它就会停止工作。我不确定我是否应该使用其他东西,或者我做错了什么。

这是我的代码:

package com.example.ana.exampleapp;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

public class TestsService extends Service {

    private static BroadcastReceiver networkChangeReceiver;
    private static String TAG = "Service";

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

    @Override
    public void onCreate() {
        Log.v(TAG, "Service created");
        boolean keep = needTokeepWaiting()
        if(!keep)
            stopSelf();
    }

    @Override
    public void onDestroy() {
        if (networkChangeReceiver != null)
            unregisterReceiver(networkChangeReceiver);
        networkChangeReceiver = null;
        Log.v(TAG, "Service destroyed");
    }

    private void registerNetworkChangeReceiver() {
        networkChangeReceiver = new BroadcastReceiver() {
            private String TAG = "NetworkReceiver";

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.v(TAG, "Connection changed received");
                            boolean keep = needTokeepWaiting()
                if(!keep)
                    stopSelf();
            }
        };
        IntentFilter filter = new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, filter);
    }
}

我的manisfest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ana.exampleapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RegisterActivity"></activity>
        <activity android:name=".FinishRegisterActivity"></activity>
        <activity android:name=".TestActivity"></activity>
        <activity android:name=".InformationActivity"></activity>
        <service android:name=".TestsService"></service>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

在TestActivity中,当我有必要时:

Intent service = new Intent(this, TestsService.class);
startService(service);

我正在做的与此处的建议类似,但它不起作用:

Keep broadcast receiver running after application is closed

我还试图在没有服务并在清单中注册的情况下这样做,但它既不起作用:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ana.exampleapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RegisterActivity">
        </activity>
        <activity android:name=".FinishRegisterActivity" >
        </activity>
        <activity android:name=".TestActivity">
        </activity>
        <activity android:name=".InformationActivity" >
        </activity>
        <receiver android:name=".NetworkChangeReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

2 个答案:

答案 0 :(得分:2)

我刚刚发现了这个问题。 Android 4.4.x中存在一个错误,它会在关闭应用程序时终止后台服务。我在Android 4.4.2中测试了我的应用。这里有一个详细的解释:

http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-is-on-the-way/

所以我的代码是正确的,因为我在Android 4.2.2中尝试过并且它有效(我已经尝试覆盖onStartCommand()所以可能需要这样做。)

答案 1 :(得分:-1)

如果您不希望在应用关闭时停止服务,则应覆盖onStartCommand()方法,执行以下操作:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_REDELIVER_INTENT;
}

您可以返回nextSTART_STICKY,无论哪种方式更适合您