服务不向活动发送广播

问题描述 投票:0回答:1

我是Android App Dev的新手。我正在尝试创建一个向主要活动发送广播的服务。 GPS位置改变10米后。

我正在尝试使用广播,但广播没有达到MainActivity。

如果我做错了,或者你有更好的想法,请建议任何其他更合适的方法。

当我在手机上运行时,应用程序不会崩溃或任何事情,它只是说

“行走应用程序一直在停止”。就是这样。我甚至没有在Logcat中创建任何异常。任何帮助,将不胜感激。

这是我的代码:

MainActivity.class :

public class MainActivity extends AppCompatActivity implements Tab1.OnFragmentInteractionListener, Tab2.OnFragmentInteractionListener, Tab3.OnFragmentInteractionListener {


DBHelper helper;
World world;
Location location;
GPSTracker tracker;
BroadcastReceiver locationBroadcast;

public static final String BROADCAST_ACTION = "e.wolverine2.thewalkingapp";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    registerMyReceiver();
    Intent intent = new Intent(this, MyService.class);

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);

    startService(intent);


    tracker = new GPSTracker(getApplicationContext());
    location = tracker.getLocation();
    helper = new DBHelper(getApplicationContext());

    final TabLayout tabLayout = (TabLayout) findViewById(R.id.myTabLayout);
    tabLayout.addTab(tabLayout.newTab().setText("List"));
    tabLayout.addTab(tabLayout.newTab().setText("Total Distance"));
    tabLayout.addTab(tabLayout.newTab().setText("Fuel Burnt"));


    locationBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String data = intent.getStringExtra("data");
            Toast.makeText(getApplicationContext(), "BroadCast Recieved : " +data, Toast.LENGTH_SHORT).show();

        }
    };

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
    final PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(pagerAdapter);

    viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {


        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

}


@Override
public void onFragmentInteraction(Uri uri) {

}

private void registerMyReceiver() {

    try {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BROADCAST_ACTION);
        registerReceiver(locationBroadcast, intentFilter);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}


public void locationChanged(Location location) {


    world = new World();

    Toast.makeText(this, "Location Recieved!", Toast.LENGTH_SHORT).show();
    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
    world.setLongitude(location.getLongitude());
    world.setLatitiude(location.getLatitude());
    world.setDate(timeStamp);
    world.setTime(timeStamp);
    world.setLocation("Anon");

    helper.addRow(world);
}
}

MyService.class:

public class MyService extends Service {

private static final String TAG = "MY TAG : ";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 5000;
private static final float LOCATION_DISTANCE = 10f;

public static final String NOTIFY = "e.wolverine2.thewalkingapp";


public MyService(String name){
    super();
}

class LocationListener implements android.location.LocationListener {

    Location mLastLocation;
    double distance;

    public LocationListener(String provider) {
        Log.e(TAG, "LocationListener " + provider);
        mLastLocation = new Location(provider);
    }

    @Override
    public void onLocationChanged(Location location) {

        Log.e(TAG, "onLocationChanged: " + location);

        distance = mLastLocation.distanceTo(location);
        mLastLocation.set(location);

        sendMyBroadCast();

    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.e(TAG, "onProviderDisabled: " + provider);
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.e(TAG, "onProviderEnabled: " + provider);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.e(TAG, "onStatusChanged: " + provider);
    }
}

LocationListener[] mLocationListeners = new LocationListener[]{
        new LocationListener(LocationManager.GPS_PROVIDER),
        new LocationListener(LocationManager.NETWORK_PROVIDER)
};

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


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e(TAG, "onStartCommand");
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}

@Override
public void onCreate() {

    Log.e(TAG, "onCreate");
    initializeLocationManager();
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[1]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "network provider does not exist, " + ex.getMessage());
    }
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[0]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "gps provider does not exist " + ex.getMessage());
    }
}

@Override
public void onDestroy() {
    Log.e(TAG, "onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG, "fail to remove location listners, ignore", ex);
            }
        }
    }
}

private void initializeLocationManager() {
    Log.e(TAG, "initializeLocationManager");
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}

private void sendMyBroadCast()
{
    try
    {
        Intent broadCastIntent = new Intent(NOTIFY);
        broadCastIntent.putExtra("data","My Data");
        sendBroadcast(broadCastIntent);

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

}

Android清单:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".MyService" android:process=":my_service"/>

</application>

Logcat:

03-04 16:09:46.539 18792-18792/e.wolverine2.thewalkingapp D/AbsListView:  in onLayout changed 
03-04 16:09:46.555 18792-18912/e.wolverine2.thewalkingapp I/OpenGLRenderer: Initialized EGL, version 1.4
03-04 16:09:46.556 18792-18912/e.wolverine2.thewalkingapp D/OpenGLRenderer: Swap behavior 1
03-04 16:09:46.556 18792-18912/e.wolverine2.thewalkingapp W/Adreno-EGL: <qeglDrvAPI_eglCreateContext:2475>: EGL_BAD_ATTRIBUTE
03-04 16:09:46.556 18792-18912/e.wolverine2.thewalkingapp I/OpenGLRenderer: KHR Debugger is Disabled - EGL_BAD_ATTRIBUTE
03-04 16:09:46.734 18792-18792/e.wolverine2.thewalkingapp D/ViewRootImpl@9ca6737[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
03-04 16:09:46.734 18792-18792/e.wolverine2.thewalkingapp D/ViewRootImpl@9ca6737[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1
03-04 16:09:46.734 18792-18792/e.wolverine2.thewalkingapp D/ViewRootImpl@9ca6737[MainActivity]: mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true -1981835264}
03-04 16:09:46.737 18792-18792/e.wolverine2.thewalkingapp V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@4b1a2a nm : e.wolverine2.thewalkingapp ic=null
03-04 16:09:46.737 18792-18792/e.wolverine2.thewalkingapp I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
03-04 16:09:46.753 18792-18805/e.wolverine2.thewalkingapp D/InputTransport: Input channel constructed: fd=80
03-04 16:09:46.763 18792-18792/e.wolverine2.thewalkingapp D/ViewRootImpl@9ca6737[MainActivity]: Relayout returned: oldFrame=[0,0][720,1280] newFrame=[0,0][720,1280] result=0x1 surface={isValid=true -1981835264} surfaceGenerationChanged=false
03-04 16:09:46.782 18792-18792/e.wolverine2.thewalkingapp V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@86f201b nm : e.wolverine2.thewalkingapp ic=null
03-04 16:09:46.813 18792-18792/e.wolverine2.thewalkingapp D/ViewRootImpl@9ca6737[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
java android
1个回答
0
投票

您可能必须将服务绑定到主活动

© www.soinside.com 2019 - 2024. All rights reserved.