我应该使用Service还是IntentService?

Vin*_*wad 4 android android-intent android-service android-intentservice

我必须创建两个Android应用程序.

App1 - 从用户处获取输入消息(即"Hello World"),App2将消息打印到可通过ADB Logcat查看的控制台.来自App1的消息应通过Intents发送到App2.App2应该是一个服务

我不确定是否使用ServiceIntentService用于App2.如果我为App2创建服务.我是否可以像这样使用Implicit Intent来使用它:

Intent serviceIntent = new Intent("com.example.vinitanilgaikwad.app2");
bindService(serviceIntent, myConnection, Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)

你能告诉我怎么办?

我的App1有以下源代码类.

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

App2具有服务实现.

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();
    }
  }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

仍然App1 无法连接到App2中的服务.Adb logcat不会打印邮件.

有人可以帮忙吗?我是Android开发的新手.

ישו*_*ותך 7

我应该使用Service还是IntentService?

来自JoséJuanoSánchez 答案:

Tejas Lagvankar写了一篇关于这个主题的好文章.以下是Service和IntentService之间的一些主要区别.

什么时候用?

  • 服务可用于没有UI的任务,但不应太长.如果需要执行长任务,则必须使用Service中的线程.

  • IntentService可以在较长的任务中使用通常与主线程没有沟通.如果需要通信,可以使用主线程处理程序或广播意图.另一种使用情况是需要回调时(Intent触发的任务).

怎么触发?

  • 服务是通过调用方法所触发startService().

  • IntentService使用触发的意图,它产生一个新的工作线程和方法onHandleIntent()调用这个线程.

触发来自

  • 服务IntentService可以从任何线程,活性或其它应用程序组件触发.

运行

  • 服务在后台运行,但其上运行的应用程序的主线程.

  • IntentService运行在一个单独的工作线程.

限制/缺点

  • 服务可能会阻止该应用程序的主线程.

  • IntentService不能并行运行的任务.因此,所有连续的意图将进入工作线程的消息队列,并将按顺序执行.

什么时候停?

  • 如果您实施服务,则您有责任在工作完成后通过调用stopSelf()或停止服务stopService().(如果您只想提供绑定,则不需要实现此方法).

  • IntentService停止服务后,都开始请求被处理,所以你从来没有打电话stopSelf().


UPDATE

解决问题的最佳方法是什么?

如果Activity或其他组件想要与服务通信,则可以使用LocalBroadcastManager.该服务可以通过活动将接收的本地广播发送消息.

阅读更多详情,这些应该可以帮助您:

  1. 与服务沟通.
  2. IntentService.

新的更新

正如@ josemgu91所说,LocalBroadcastManager只能用于同一应用程序中的Activity和service.

我们可以通过MessengerAIDL与其他应用程序或进程(称为IPC)进行通信.

由于使用AIDL传递数据是相当繁琐和冗长的,如果需要绑定通信,更有效的方法是使用方便的Messenger系统,它将绑定器包装成更易于使用的Handler对象.

阅读更多:

  1. 绑定服务
  2. 带Messenger的Android进程间通信(IPC)(远程绑定服务)