我必须创建两个 android 应用程序。

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

我不确定是否对 App2 使用 ServiceIntentService。如果我为 App2 创建一个服务。我是否可以像这样使用 隐式 Intent 来使用它:

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

你能告诉我我该怎么做吗?

我的 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();
    }
  }
}

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();
    }
  }

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>

仍然 App1 无法连接到 App2 中的服务。 Adb logcat 不打印消息。

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

最佳答案

我应该使用 Service 还是 IntentService?
José Juan Sánchez Answer :
Tejas Lagvankar 写了一篇关于这个主题的不错的 post
以下是 Service 和 IntentService 之间的一些主要区别。
什么时候使用?

  • Service 可以在没有 UI 的任务中使用,但不应太长。如果需要执行长时间的任务,则必须在 Service 中使用线程。
  • IntentService 可用于通常不与主线程通信的长任务。如果需要通信,可以使用主线程处理程序或广播 Intent 。另一种使用情况是需要回调( Intent 触发的任务)。

  • 如何触发?
  • 该服务是通过调用方法 startService() 触发的。
  • IntentService 使用 Intent 触发,它产生一个新的工作线程,并在该线程上调用 onHandleIntent() 方法。

  • 触发
  • Service 和 IntentService 可以从任何线程、 Activity 或其他应用程序组件触发。

  • 上运行
  • Service 在后台运行,但它运行在应用程序的主线程上。
  • IntentService 在单独的工作线程上运行。

  • 限制/缺点
  • Service 可能会阻塞应用程序的主线程。
  • IntentService 不能并行运行任务。因此,所有连续的 Intent 都将进入工作线程的消息队列,并按顺序执行。

  • 什么时候停止?
  • 如果你实现了一个服务,你有责任在服务完成后通过调用 stopSelf()stopService() 来停止服务。 (如果只想提供绑定(bind),则不需要实现此方法)。
  • IntentService 在处理完所有启动请求后停止服务,因此您永远不必调用 stopSelf()

  • 更新
    解决问题的最佳方法?
    如果 Activity 或其他组件想要与服务通信,则可以使用 LocalBroadcastManager。该服务可以通过本地广播发送消息,该消息将被 Activity 接收。
    阅读更多详细信息,这些应该可以帮助您:
  • Communicating with the service
  • IntentService

  • 新更新
    正如@josemgu91 所说,LocalBroadcastManager 只能用于同一应用程序中的 Activity 和服务。
    我们可以通过 MessengerAIDL 与其他应用程序或进程通信,称为 IPC。
    由于使用 AIDL 传递数据非常乏味和冗长,如果需要绑定(bind)通信,更有效的方法是使用方便的 Messenger system 将绑定(bind)器包装成更易于使用的 Handler 对象。
    阅读更多信息:
  • Bound Service
  • Android Interprocess Communication (IPC) with Messenger (Remote Bound Services)
  • 10-08 03:17