为什么在应用程序重新启动后BroadcastReciver不起作用?

时间:2018-07-26 11:54:40

标签: android

我试图创建我的第一个Android应用。

我的位置为Service

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;

public class LocationService extends Service {

private LocationListener listener;
private LocationManager locationManager;

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

@SuppressLint("MissingPermission")
@Override
public void onCreate(){

    listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Intent i = new Intent("location_update");
            i.putExtra("coordinates", location);
            sendBroadcast(i);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    };

    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);

}

@Override
public void onDestroy(){
    super.onDestroy();
    if(locationManager != null){
        locationManager.removeUpdates(listener);
    }
}

}

MainActivity

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.max.testapp.settings.SettingsManager;

public class MainActivity extends AppCompatActivity {

private BroadcastReceiver broadcastReceiver;
private Location currentLocation;

@Override
protected void onResume(){
    super.onResume();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                currentLocation = (Location)intent.getExtras().get("coordinates");
            }
        };
    }
    registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
}

@Override
protected void onStart(){
    super.onStart();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                currentLocation = (Location)intent.getExtras().get("coordinates");
            }
        };
    }
    registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
}

@Override
protected void onDestroy(){
    super.onDestroy();
    if(broadcastReceiver != null){
        unregisterReceiver(broadcastReceiver);
    }
}

@Override
protected void onPause(){
    super.onPause();
    if(broadcastReceiver != null){
        unregisterReceiver(broadcastReceiver);
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StartServices();
}


private void EnableButtons(){
    Button getLocationButton = findViewById(R.id.btnGetLocation);
    getLocationButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            TextView textView = (TextView) findViewById(R.id.textView);
            textView.append("\n");
            textView.append(currentLocation.getLongitude()+"/"+currentLocation.getLatitude());
        }
    });
}

private void StartServices(){
    Intent i = new Intent(getApplicationContext(),LocationService.class);
    startService(i);
}
}

当我启动模拟器时,应用程序运行良好。但是,如果我关闭应用程序并再次启动,则会看到broadcastReicver永远不会触发onRecive事件。所以我没有从服务获得位置。

我在这段代码中忘记了什么?

1 个答案:

答案 0 :(得分:1)

onResume()

中启动服务

-首先检查是否正在运行

public static boolean isServiceRunning(String serviceClassName){
        final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName)){
                return true;
            }
        }
        return false;
     }

如果未运行,则启动服务