Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 我应该使用Service还是IntentService?_Android_Android Intent_Android Service_Android Intentservice - Fatal编程技术网

Android 我应该使用Service还是IntentService?

Android 我应该使用Service还是IntentService?,android,android-intent,android-service,android-intentservice,Android,Android Intent,Android Service,Android Intentservice,我必须创建两个android应用程序 App1-从用户处获取一条输入消息(即“Hello World”),然后App2将消息打印到控制台,可通过ADB Logcat查看。来自App1的消息应通过Intents发送到App2。App2应该是一个服务 我不确定是为App2使用服务还是IntentService。如果我为App2创建服务。我是否能够通过使用隐式意图来使用它,如下所示: Intent serviceIntent = new Intent("com.example.vinitanilgai

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

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

我不确定是为App2使用
服务
还是
IntentService
。如果我为App2创建服务。我是否能够通过使用隐式意图来使用它,如下所示:

Intent serviceIntent = new Intent("com.example.vinitanilgaikwad.app2");
bindService(serviceIntent, myConnection, Context.BIND_AUTO_CREATE);
你能告诉我该怎么做吗

MyApp1具有以下源代码类

App1DisplayMessageActivity

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信使服务

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();
    }
  }
App2AndroidManifest.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开发新手。

你想做什么样的任务?IntentService和Service都可以像您希望的那样处理intent。IntentService是一种特殊的服务,当接收到一个Intent时,它在另一个线程中执行一个任务,然后停止自己。如果你想做一个简单的一次性任务,那么你可以使用它。另一方面,服务将保持活动状态,具体取决于您执行它的方式(绑定或取消绑定服务)。如果希望采用更灵活的方法,那么可以使用服务并在onStartCommand方法中处理意图。如果您想要更灵活的方法来处理复杂的数据类型,您需要在服务(Messenger或AIDL)中使用IPC技术。

我应该使用service还是IntentService? 发件人:

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

何时使用?

  • 该服务可以在没有UI的任务中使用,但不能太长。若需要执行长任务,则必须在服务中使用线程

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

如何触发?

  • 该服务是通过调用方法
    startService()
    触发的

  • IntentService是使用Intent触发的,它生成一个新的工作线程,并在此线程上调用方法
    onHandleIntent()

从触发

  • 服务和IntentService可以从任何线程、活动或其他应用程序组件触发
运行于

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

  • IntentService在单独的工作线程上运行

限制/缺点

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

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

何时停止?

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

  • IntentService在处理完所有启动请求后停止服务,因此您不必调用
    stopSelf()


更新 解决问题的最佳方法是什么? 如果活动或其他组件希望与服务通信,则可以使用。该服务可以通过本地广播发送消息,活动将接收该消息

有关详细信息,请阅读更多信息,这些信息应能帮助您:


  • 新更新 正如@josemgu91所说,LocalBroadcastManager只能用于同一应用程序中的活动和服务

    我们可以通过和与称为IPC的其他应用程序或进程通信

    由于使用AIDL传递数据非常繁琐,如果需要绑定通信,一种更有效的方法是使用方便的方法,将绑定器封装到一个更易于使用的处理程序对象中

    更多信息请访问:


  • 您应该在App2中使用
    服务

    使用
    IntentService
    的唯一原因是在UI线程以外的线程上执行工作。根据您的帖子,您的需求是进程间通信,而不是工作线程。。。因此,您应该只使用
    服务

    如果您只向App2发送信息(不希望返回),也没有理由绑定它的服务。只需使用:

    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)
    
    。。。从App1到App2触发意向

    不需要意向过滤器、广播管理器、意向服务或信使


    (修改为添加明确的意图)

    请检查我的代码好吗?我不明白怎么了。我已编辑了问题。您的应用程序2的意图过滤器具有“com.example.vinitailgaikwad.app2”操作,您的应用程序1正在发送意图“com.example.vinitailgaikwad.app2_try2”。您的意图必须相同,因为当您的app1发送“com.example.vinitailgaikwad.app2_try2”意图时,系统找不到与该意图匹配的服务(因为您的app2服务响应“com.example.vinitailga”)