0

今天我做了我的第一个后台服务,如果我退出我的应用程序,它会继续运行。

它正在记录纬度和经度。

我想在我的代码中添加更多功能,我想请你帮忙,我应该以哪种方式继续编码,我已经做好了吗?

我使用Activity,使用从后台服务获取消息的处理程序:

public class MyActivity extends Activity {


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



    BackgroundLocationService.context=this;

    Intent i = new Intent(this, BackgroundLocationService.class);
    i.putExtra("handler", new Messenger(this.handler));
    startService(i);
            /*.......more code here......*/
}

    Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // get data from msg
        String result = msg.getData().getString("result");
        Log.i("Activiti map: Locationing Service handler: ", 
                          "get data: " + result);
        super.handleMessage(msg);
    }
};

这是我的后台服务:

public class BackgroundLocationService extends IntentService {

private static final String TAG = "Activiti map: Locationing Service";

private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
public static Context context;

private boolean gps_enabled = false;
private boolean network_enabled = false;

private boolean DEBUG=false;

private String latitude="0";
private String londitude="0";

Messenger messenger;
Timer t=new Timer();

public BackgroundLocationService()
{
    super("myintentservice");

    locManager = (LocationManager) context.getSystemService
                                   (Context.LOCATION_SERVICE);
    try {
        gps_enabled = 
                    locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
        if(DEBUG)
        Log.e(TAG, ex.toString());
    }
    try {
        network_enabled = 
                locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
        if(DEBUG)
        Log.e(TAG, ex.toString());
    }

    if (gps_enabled) {
        if(DEBUG)
        Log.i(TAG, "Gps is Enabled!");
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                     0, 0, locListener);
    } else {
        if(DEBUG)
        Log.i(TAG, "Gps is Disabled!");
    }
    if (network_enabled) {
        if(DEBUG)
        Log.i(TAG, "Network provider is enabled!");

                   locManager.requestLocationUpdates
                        (LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
    } else {
        if(DEBUG)
        Log.i(TAG, "Network provider is Disabled!");
    }
}



@Override
protected void onHandleIntent(Intent intent) {
    messenger=(Messenger) intent.getExtras().get("handler");

    t.schedule(new TimerTask() {

        @Override
        public void run() {
            // just call the handler every 3 Seconds

            Message msg=Message.obtain();
            Bundle data=new Bundle();
            data.putString("result", "latitude: " + latitude+
                           " londitude: "+londitude);
            msg.setData(data);

            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, 100,3000);

}


class MyLocationListener implements LocationListener {

    private static final String TAG = "Activiti map: LocationListener";

    public void onLocationChanged(Location location) {

        if (location != null) {
            locManager.removeUpdates(locListener);

            londitude = Double.toString(location.getLongitude());
            latitude = Double.toString(location.getLatitude());

            if(DEBUG)
            Log.i(TAG, "Londitude: " + londitude + " Latitude: " + latitude);

        }
    }

    public void onProviderDisabled(String arg) {
        if(DEBUG)
        Log.i(TAG, "Provider just Disabled: " + arg);
    }

    public void onProviderEnabled(String arg) {
        if(DEBUG)
        Log.i(TAG, "Provider just Enabled: " + arg);
    }

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


    }
}

}

我想解决的一些问题:

是否可以控制处理程序服务或我的代码中的任何内容以确保服务已停止、启动等?所以我想添加控件,例如从一个小部件按钮打开和关闭服务。这怎么可能 ?

还有一件事:如果我多次快速启动和退出我的应用程序,每次处理程序初始化时我都会收到多条日志消息。我怎样才能使这个或类似的东西成为单身?

感谢您的帮助

4

1 回答 1

1

Use Application for those purposes.

You can implement singleton logic into Application class and manage your service.

If you close your activity, the Service asks Application if Activity alive.

On Launch Activity, Application knows about and Service can bind with above mentioned Activity by using some Interfaces that Application stores.

** The main Activity must initiate Handler to make to Service to talk with Activity

Here is some code:

public class MyApplication extends Application{

 private static MyApplication mSingleton;


    private static final String PACKAGE = "com.code";
    private static final String PROCESS_NAME = PACKAGE + ".ui";
    private static final String SERVICE_NAME = PROCESS_NAME + "/" + PACKAGE + ".srvce.MyService";

      @Override
   public void onCreate() {
     super.onCreate();
     mSingleton = this;
   }

       public MyApplication getApp(){
         return mSingleton;
       }

      ....

      public boolean isServiceRun() {

    ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
    List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

    boolean isRunnig = false;

    for (int i = 0; i < services.size(); i++) {             
        RunningServiceInfo inf = services.get(i);
        if(PROCESS_NAME.equals(inf.process)){                   
            ComponentName cn = inf.service;                 
            String str = cn.toString();                 
            if(str.contains(SERVICE_NAME)){
                isRunnig = true;
                return isRunnig;
            }
        }               
    }  

    return isRunnig;        
}

 }
于 2013-01-21T15:13:18.757 回答