簡體   English   中英

服務未向活動發送廣播

[英]Service is not sending broadcast to activity

我是Android App Dev的新手。 我正在嘗試創建將廣播發送到主要活動的服務。 GPS位置改變10米后。

我正在嘗試使用廣播,但是廣播無法到達MainActivity。

如果我做錯了,或者您有更好的想法,請提出其他更合適的方法。

當我在手機上運行該應用程序時,它不會崩潰或發生任何變化,它只是說

“ Walking App不斷停止”。 就是這樣。 我什至沒有在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

您可能必須將服務綁定到主要活動

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM