如何在android中正确使用Intent Service,Broadcast Receiver

时间:2015-04-21 14:06:14

标签: java android broadcastreceiver intentservice

我有字符串数组,并在背景中找到从当前位置到阵列中每个区域的距离

但我的应用程序正在冻结,并且想要实现Intent Service,我尝试使用许多在线教程跟踪代码,但我的意图服务类从未被调用,这我做错了吗?请告诉我任何对我有帮助的事情,

我的清单文件

 <service android:name=".ServiceGoogle.MyIntentService" android:enabled="true" /> 
 <receiver android:name=".ServiceGoogle.MyIntentReceiver">
    </receiver>

我的mainActivity方法

public class MainActivity extends ActionBarActivity implements LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{
private void updateUI() {
       if (null != mCurrentLocation) {
        String lat = String.valueOf(mCurrentLocation.getLatitude());
        String lng = String.valueOf(mCurrentLocation.getLongitude());

        IntentFilter intentFilter=new IntentFilter(MyIntentReceiver.PROCESS_RESPONSE);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver=new MyIntentReceiver();
        registerReceiver(receiver,intentFilter);

        Intent myIntent=new Intent(MainActivity.this,MyIntentService.class);
        myIntent.putExtra("strAreas",strAreas);
        myIntent.putExtra("lat",lat);
        myIntent.putExtra("lng",lng);
        startService(myIntent);
}}
}

我的IntentService类

public class MyIntentService extends IntentService{
           protected void onHandleIntent(Intent intent) {

    Geocoder geocoder = new Geocoder(this, Locale.getDefault());

    try {
        List<Address> addressList = geocoder.getFromLocation(
                lat, longt, 1);
        if (addressList != null && addressList.size() > 0) {
            Address address = addressList.get(0);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                sb.append(address.getAddressLine(i)).append("\n");
            }
            currentLocation = sb.toString();
            for (int i = 0; i < strAreas.length; i++) {
                distanceHashList.put(strAreas[i],getLocationFromAddress(strAreas[i],this));
                }
            returnList();

            Intent intentBroadcast=new Intent(this,MyIntentReceiver.class);
            intentBroadcast.putExtra("CurrentLocation",currentLocation);
            intentBroadcast.putStringArrayListExtra("DistanceList", distanceAreas);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentBroadcast);

        }

    } catch (IOException e) {
        Log.e(TAG, "Unable to connect to Geocoder", e);
    }
}
}

MyReceiver

public class MyIntentReceiver extends BroadcastReceiver {
      public void onReceive(Context context, Intent intent) {
    currentlocation=intent.getStringExtra("CurrentLocation");
    distanceAreas=intent.getStringArrayListExtra("DistanceList");
}

提前致谢

0 个答案:

没有答案