Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Service or IntentService?

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.

like image 479
Vinit Gaikwad Avatar asked Dec 25 '22 03:12

Vinit Gaikwad


1 Answers

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)
like image 187
ישו אוהב אותך Avatar answered Dec 27 '22 11:12

ישו אוהב אותך