4

I have to create two android apps.

App1 - takes an input message (i.e. “Hello World”) from the user and App2 prints out the message to the Console viewable via ADB Logcat.  The message from App1 should be sent to App2 via Intents.  App2 should be a Service

I am not sure whether to use Service or IntentService for App2. If I create a service for App2. Would I be able to use it by using Implicit Intent like this:

Intent serviceIntent = new Intent("com.example.vinitanilgaikwad.app2");
bindService(serviceIntent, myConnection, Context.BIND_AUTO_CREATE);

Could you please advise me how should I proceed?

My App1 has following source code classes.

App1: DisplayMessageActivity

public class DisplayMessageActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
    layout.addView(textView);

    Intent serviceIntent = new Intent("com.example.vinitanilgaikwad.app2");

    bindService(serviceIntent, myConnection, Context.BIND_AUTO_CREATE);

    startService(serviceIntent);
  }

  Messenger myService = null;
  boolean isBound;

  private ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        myService = new Messenger(service);
        isBound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        myService = null;
        isBound = false;
    }
  };

  @Override
  public void onDestroy() {
    super.onDestroy();
    unbindService(myConnection);
  }

  public void sendMessage(View view) {
    // if (!isBound) return;
    Message msg = Message.obtain();
    Bundle bundle = new Bundle();
    bundle.putString("MyString", "Vinit");
    msg.setData(bundle);
    try {
     myService.send(msg);
    } catch (RemoteException e) {
     e.printStackTrace();
    }
  }
}

App2 has the service implementation.

App2: MessengerService

package com.example.vinitanilgaikwad.app2;

public class MessengerService extends Service {
  class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      Log.i("dddsds","fsdfdsfsfs");
      Bundle data = msg.getData();
      String dataString = data.getString("MyString");
      Toast.makeText(getApplicationContext(),
                    dataString, Toast.LENGTH_SHORT).show();
      Log.d("Me123",dataString);
    }
  }

  final Messenger myMessenger = new Messenger(new IncomingHandler());
    @Override
    public IBinder onBind(Intent intent) {
      return myMessenger.getBinder();
    }
  }

App2: AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MessengerService"
          >
            <intent-filter>
                <action android:name="com.example.vinitanilgaikwad.app2"></action>
            </intent-filter>
        </service>


    </application>

</manifest>

Still App1 is not able to connect to Service in App2. Adb logcat does not print the message.

Can someone help? I am new to Android development.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Vinit Gaikwad
  • 329
  • 9
  • 21

3 Answers3

7

Should I use Service or IntentService?

From José Juan Sánchez Answer:

Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.

When to use?

  • The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.

  • The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

How to trigger?

  • The Service is triggered by calling method startService().

  • The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

Triggered From

  • The Service and IntentService may be triggered from any thread, activity or other application component.

Runs On

  • The Service runs in background but it runs on the Main Thread of the application.

  • The IntentService runs on a separate worker thread.

Limitations / Drawbacks

  • The Service may block the Main Thread of the application.

  • The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.

When to stop?

  • If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).

  • The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().


UPDATE

Best way to solved your problem?

If an Activity or other component wants to communicate with a service, the LocalBroadcastManager can be used. The service can send messages through a local broadcast that will be received by the Activity.

Read more for details, these should help you:

  1. Communicating with the service.
  2. IntentService.

NEW UPDATE

As @josemgu91 says, LocalBroadcastManager can only be used for Activity and service in the same application.

We can communicate to other Application or processes, called as IPC, via Messenger and AIDL.

Since passing data using AIDL is quite tedious and verbose, a more efficient approach, if bound communication is desired, is to use the convenient Messenger system which wraps the binder into a much easier to use Handler object.

Read more at:

  1. Bound Service
  2. Android Interprocess Communication (IPC) with Messenger (Remote Bound Services)
Community
  • 1
  • 1
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
2

You should use a Service in App2.

The only reason for using an IntentService is to perform work on a thread other than the UI Thread. According to your post, your requirement is inter-process communication, not a worker thread. ... so you should just use a Service.

If you are only sending information to App2 (not expecting a return), there is no reason to bind its service, either. Just use:

Intent svc = new Intent();
svc.setComponent(new ComponentName(
   "com.wicked.cool.apps.app2",                    // App2's package
   "com.wicked.cool.apps.app2.svc.App2Service"));  // FQN of App2's service
svc.setStringExtra(STUFF_KEY, someStuff);
startService(svc)

... to fire an an intent from App1 to App2.

No need for intent filters, Broadcast Managers, IntentServices or Messengers.

(amended to add explicit intent)

G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40
1

What kind of task would you like to do? Both the IntentService and Service can handle Intents like you want to do. The IntentService is a special kind of service that when receives an Intent then executes a task in another thread and then stops itself. If you want to do a simple one-shot task then you could use it. The Service on the other hand remains active depending how you execute it (bound or unbkund service). If you want to have a more flexible approach then you could use a Service and handle the Intents in the onStartCommand method. If you want an even more flexible approach to handle complex data types, the you'll need to use IPC techniques with your service (Messenger or AIDL).

josemgu91
  • 719
  • 4
  • 8
  • Could you please check my code? I don't understand what is wrong. I have edited the question – Vinit Gaikwad Jul 24 '16 at 04:25
  • The intent filter of your app2 has the "com.example.vinitanilgaikwad.app2" action, your app1 is sending an intent "com.example.vinitanilgaikwad.app2_try2". Your Intents must be the same, because when your app1 sends the "com.example.vinitanilgaikwad.app2_try2" Intent, the system doesn't found a service that matchs that intent (because your app2 service responds to the "com.example.vinitanilgaikwad.app2" intent). – josemgu91 Jul 24 '16 at 04:42
  • I am sorry sir. That was a typo. Even If I keep it as "com.example.vinitanilgaikwad.app2", it still has some issue. Can you suggest? I have corrected the typo – Vinit Gaikwad Jul 24 '16 at 04:52