2012-04-05 68 views
4

我已经编写了一个服务,并计划让多个应用程序使用Messenger进行通信。我遵循Android Bound Services example for messenger的示例。 我已经把服务放在一个Android库项目中,所有其他的Android项目都使用这个库。Android - 为什么运行此服务的多个实例

我遇到的问题是服务的多个实例在绑定到它时运行。每个应用程序绑定到该服务以下列方式:

// Bind to the service 
bindService(new Intent(ApplicationOneActivity.this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE); 

的服务是:

public class MessengerService extends Service { 
    /** Command to the service to display a message */ 
    public static final int MSG_SAY_HELLO = 0; 
    /** Command to the service to display a message from App 1 */ 
    public static final int MSG_APP1_HELLO = 1; 

    public static final int MSG_APP2_HELLO = 2; 

    public static final int MSG_APP3_HELLO = 3; 

    private int[] stat = new int[3]; 

    private Timer timer = null; 

    /** 
    * Handler of incoming messages from clients. 
    */ 
    class IncomingHandler extends Handler { 
     @Override 
     public void handleMessage(Message msg) { 
      switch (msg.what) { 
      case MSG_SAY_HELLO: 
       Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show(); 
       break; 
      case MSG_APP1_HELLO: 
       Toast.makeText(getApplicationContext(), "App One says: " + msg.arg1, Toast.LENGTH_SHORT).show(); 
       stat[0] = msg.arg1; 
       break; 
      case MSG_APP2_HELLO: 
       Toast.makeText(getApplicationContext(), "App Two says: " + msg.arg1, Toast.LENGTH_SHORT).show(); 
       stat[1] = msg.arg1; 
       break; 
      case MSG_APP3_HELLO: 
       Toast.makeText(getApplicationContext(), "App Three says: " + msg.arg1, Toast.LENGTH_SHORT).show(); 
       stat[2] = msg.arg1; 
       break; 
      default: 
       super.handleMessage(msg); 
      } 
     } 
    } 

    /** 
    * Target we publish for clients to send messages to IncomingHandler. 
    */ 
    final Messenger mMessenger = new Messenger(new IncomingHandler()); 

    /** 
    * When binding to the service, we return an interface to our messenger 
    * for sending messages to the service. 
    */ 
    @Override 
    public IBinder onBind(Intent intent) { 
     Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show(); 

     return mMessenger.getBinder(); 

    } 

    @Override 
    public boolean onUnbind(Intent intent) { 
     Toast.makeText(getApplicationContext(), "unbinding", Toast.LENGTH_SHORT).show(); 
     return super.onUnbind(intent); 
    } 

    final Handler handler = new Handler() { 

     public void handleMessage(Message msg) { 
      // Create and send a message to the service, using a supported 'what' value 
      ReportAsyncTask report = new ReportAsyncTask(); 
      report.execute(""); 
     } 
    }; 


    @Override 
    public void onCreate() { 
     super.onCreate(); 

     if (timer == null) { 
      timer = new Timer(); 
      timer.schedule(new ScheduledTaskWithHandeler(), 10000); 
      Toast.makeText(getApplicationContext(), "Register Timer To Report Back ", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     if (timer != null) { 
      timer.cancel(); 
      timer = null; 
     } 
    } 

    class ScheduledTaskWithHandeler extends TimerTask { 

     @Override 
     public void run() { 
      handler.sendEmptyMessage(0); 
     } 
    } 

    private class ReportAsyncTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 
      String response = ""; 
      try { 
       String urlParams="device=" + URLEncoder.encode(android.os.Build.MODEL, "UTF-8") 
         + "&status="+URLEncoder.encode("App1 says " + stat[0] + ", App2 says " + stat[1] + ", App3 says " + stat[2],"UTF-8"); 
       String url = "http://192.168.43.143:8080/SimpleServlet3/monitor-servlet"; 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpGet httpget = new HttpGet(url+"?"+urlParams); 
       HttpResponse httpresponse = httpclient.execute(httpget); 
       HttpEntity entity = httpresponse.getEntity(); 
       if (entity != null) { 
        InputStream instream = entity.getContent(); 
        int l; 
        byte[] tmp = new byte[2048]; 
        while ((l = instream.read(tmp)) != -1) { 
         response += l; 
        } 
       } 
       timer.schedule(new ScheduledTaskWithHandeler(), 10000); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      return response; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      Toast.makeText(getApplicationContext(), "Server says " + result, Toast.LENGTH_SHORT).show(); 
     } 

    } 

} 

该清单为每个应用程序看起来更加的少,如:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.app1" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk android:minSdkVersion="11" /> 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

    <application 
     android:icon="@drawable/spinifex" 
     android:label="@string/app_name" > 
     <activity 
      android:name=".ApplicationOneActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <service 
      android:name="com.example.services.MessengerService" 
      android:process=":remote" /> 
    </application> 

</manifest> 

任何想法我做错了? Toast消息非常确定地表明同一服务的多个实例正在运行。我的项目结构错了吗?我应该不把这项服务放在单独的图书馆项目中吗?

回答

2

您必须在一个AndroidManifest中声明<service />标记,而在其他应用程序中,您必须通过完整的组件名称进行绑定。 如:

Intent intent = new Intent(); 
intent.setClassName(
    "com.example.app1" /* your package which contains service */, 
    "com.example.services.MessengerService" /* service name */ 
); 

bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 

此外,当你做android:process=":remote",你告诉到Android这个过程是私有的当前应用程序。

+0

我可以仅在我的Android库项目中声明服务,还是必须位于其中一个应用程序中? – Ali 2012-04-05 08:12:36

+0

我认为它会在应用程序中更好。 – pepyakin 2012-04-05 08:51:41

+0

根据android文档,如果一个进程以':开始,那么它对于一个应用程序是私有的,但是如果我删除':'并以一个小写字母开头,那么他应该是全局进程的名称,但是当我这样做时,部署我得到一个畸形的清单错误。你知道该服务是否必须在''标签内或外部声明?你知道创建一个我可以看到的全球服务的例子吗? – Ali 2012-04-10 00:50:31