如何通过ServiceConnection从Service中获得更新通知

时间:2011-08-15 07:22:20

标签: android

我对ServiceActivityIntent概念感到困惑。我要做的是TrackerMapService每隔5秒检查一次位置后台工作,如果更改,TextView活动将更新跟踪的位置数。

public class TrackerService extends IntentService实现了LocationListener {

private static final String LOGTAG = "TrackerService";

private LocationManager manager;
private ArrayList<Location> storedLocations;

private boolean isTracking = false;

public TrackerService() {
    super("TrackerServiceName");
}

/* Service Setup Methods */
@Override
public void onCreate() {
    manager = (LocationManager)getSystemService(LOCATION_SERVICE);
    storedLocations = new ArrayList<Location>();
    Log.i(LOGTAG, "Tracking Service Running...");
}

public void startTracking() {
    if(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        return;
    }
    Toast.makeText(this, "Starting Tracker", Toast.LENGTH_SHORT).show();
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);

    isTracking = true;
}

public void stopTracking() {
    Toast.makeText(this, "Stopping Tracker", Toast.LENGTH_SHORT).show();
    manager.removeUpdates(this);
    isTracking = false;
}

public boolean isTracking() {
    return isTracking;
}

@Override
public void onDestroy() {
    manager.removeUpdates(this);
    Log.i(LOGTAG, "Tracking Service Stopped...");
}

/* Service Access Methods */
public class TrackerBinder extends Binder {
    TrackerService getService() {
        return TrackerService.this;
    }
}

private final IBinder binder = new TrackerBinder();

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

public int getLocationsCount() {
    return storedLocations.size();
}

public ArrayList<Location> getLocations() {
    return storedLocations;
}

/* LocationListener Methods */
@Override
public void onLocationChanged(Location location) {
    Log.i("TrackerService", "Adding new location");
    storedLocations.add(location);
}

@Override
public void onProviderDisabled(String provider) { }

@Override
public void onProviderEnabled(String provider) { }

@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override
protected void onHandleIntent(Intent intent) {
    int updatedLocNumber = getLocationsCount();
    Log.d("IntentService", "logged" + updatedLocNumber + "location in intent");

    // TODO Auto-generated method stub
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("LOCATION_UPDATED");
    getBaseContext().sendBroadcast(broadcastIntent);
}

}

public class ServiceActivity extends Activity实现了View.OnClickListener {

Button enableButton, disableButton;
TextView statusView;

TrackerService trackerService;
Intent serviceIntent;

IntentFilter intentFilter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    enableButton = (Button)findViewById(R.id.enable);
    enableButton.setOnClickListener(this);
    disableButton = (Button)findViewById(R.id.disable);
    disableButton.setOnClickListener(this);
    statusView = (TextView)findViewById(R.id.status);

    serviceIntent = new Intent(this, TrackerService.class);


    //intent to filter for updates
    intentFilter = new IntentFilter();
    intentFilter.addAction("LOCATION_UPDATED");
    registerReceiver(intentReceiver, intentFilter);
}

@Override
public void onResume() {
    super.onResume();
    //Starting the service makes it stick, regardless of bindings
    startService(serviceIntent);
    //Bind to the service
    bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}

@Override
public void onPause() {
    super.onPause();
    if(!trackerService.isTracking()) {
        //Stopping the service let's it die once unbound
        stopService(serviceIntent);
    }
    //Unbind from the service
    unbindService(serviceConnection);
}

@Override
public void onClick(View v) {
    switch(v.getId()) {
    case R.id.enable:
        trackerService.startTracking();
        break;
    case R.id.disable:
        trackerService.stopTracking();
        break;
    default:
        break;
    }
    updateStatus();
}

private void updateStatus() {
    if(trackerService.isTracking()) {
        statusView.setText(String.format("Tracking enabled.  %d locations logged.",trackerService.getLocationsCount()));
    } else {
        statusView.setText("Tracking not currently enabled.");
    }
}

private ServiceConnection serviceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        trackerService = ((TrackerService.TrackerBinder)service).getService();
        updateStatus();
    }

    public void onServiceDisconnected(ComponentName className) {
        trackerService = null;
    }
};

private BroadcastReceiver intentReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(getBaseContext(), "AAAAA", Toast.LENGTH_LONG);

    }
};

} 编辑LogCat: 08-15 14:40:36.982:ERROR / ActivityManager(67):com.tugce.TrackerService中的ANR 08-15 14:40:36.982:错误/ ActivityManager(67):原因:执行服务com.tugce.TrackerService / .TrackerService 08-15 14:40:36.982:ERROR / ActivityManager(67):载荷:0.63 / 0.19 / 0.15 08-15 14:40:36.982:ERROR / ActivityManager(67):CPU使用率从10147ms到0ms前: 08-15 14:40:36.982:ERROR / ActivityManager(67):1.1%133 / com.android.launcher:0.5%用户+ 0.5%内核/故障:31次 08-15 14:40:36.982:ERROR / ActivityManager(67):0.4%67 / system_server:0.2%用​​户+ 0.1%内核 08-15 14:40:36.982:ERROR / ActivityManager(67):0.1%229 / com.android.defcontainer:0.1%用户+ 0%内核/故障:33次 08-15 14:40:36.982:ERROR / ActivityManager(67):0%40 / adbd:0%user + 0%kernel 08-15 14:40:36.982:ERROR / ActivityManager(67):8.5%TOTAL:5.9%用户+ 2.5%内核 08-15 14:40:36.982:ERROR / ActivityManager(67):CPU使用率从988ms到1576ms之后: 08-15 14:40:36.982:ERROR / ActivityManager(67):12%67 / system_server:7%用户+ 5.2%内核 08-15 14:40:36.982:ERROR / ActivityManager(67):8.7%80 / ActivityManager:5.2%用户+ 3.5%内核 08-15 14:40:36.982:ERROR / ActivityManager(67):1.7%68 / HeapWorker:1.7%用户+ 0%内核 08-15 14:40:36.982:ERROR / ActivityManager(67):1.7%229 / com.android.defcontainer:0%user + 1.7%kernel 08-15 14:40:36.982:ERROR / ActivityManager(67):1.7%230 / HeapWorker:0%用户+ 1.7%内核 08-15 14:40:36.982:ERROR / ActivityManager(67):15%TOTAL:12%用户+ 3.4%内核

PS:请不要写任何其他不合适的方法,而是“保存当天”的解决方案,例如sharedPreferences。我想以最好的方式做到这一点..

1 个答案:

答案 0 :(得分:1)

您可以从服务广播意图。

   Intent i = new Intent(NEW_UPDATE);  
   sendBroadcast(i);

updateStatus()

中的活动致电BroadcastReceiver
public class Receiver extends BroadcastReceiver 
{
@Override
   public void onReceive(Context context, Intent intent) 
   {    
    String action = intent.getAction();
       if(action.equalsIgnoreCase(NEW_UPDATE)){  
           updateStatus();
       }
   }
}

创建广播接收器类的对象

private Receiver mUpdateReceiver= new Receiver();

并通过调用

注册broadcastreceiver
registerReceiver(mUpdateReceiver, new IntentFilter(NEW_UPDATE));