Development Tip

인 텐트를 사용하여 활동에서 서비스로 데이터 전달

yourdevel 2020. 11. 25. 21:18
반응형

인 텐트를 사용하여 활동에서 서비스로 데이터 전달


Service호출에서 전달 된 Android 내에서 데이터를 얻으려면 어떻게해야 Activity합니까?


첫 번째 컨텍스트 (활동 / 서비스 등일 수 있음)

Service의 경우 onStartCommand를 재정의해야하며 다음에 직접 액세스 할 수 있습니다 intent.

Override
public int onStartCommand(Intent intent, int flags, int startId) {

몇 가지 옵션이 있습니다.

1) 사용 번들 로부터 의도 :

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) 새 번들 생성

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

3) Intent putExtra () 단축키 메소드 사용

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

새 컨텍스트 (활동 / 서비스 등일 수 있음)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
     String value = myIntent.getExtras().getString(key);
}

참고 : 번들에는 모든 기본 유형, Parcelable 및 Serializable에 대한 "get"및 "put"메서드가 있습니다. 데모 용으로 Strings를 사용했습니다.


"활동에서 서비스로 인 텐트를 통해 데이터를 전송하는 방법"에 대한이 질문에 대한 정확한 답변을 onStartCommand()얻으려면 인 텐트 객체를받는 메서드 를 재정의해야 합니다.

를 만들 때 메서드를 Service재정의해야 onStartCommand()하므로 아래 서명을 자세히 살펴보면 intent여기에 전달 된 개체를 받을 수 있습니다.

  public int onStartCommand(Intent intent, int flags, int startId)

따라서 활동에서 인 텐트 객체를 만들어 서비스를 시작한 다음 인 텐트 객체 안에 데이터를 배치합니다. 예를 들어 UserIDfrom Activity전달하려는 경우 Service:

 Intent serviceIntent = new Intent(YourService.class.getName())
 serviceIntent.putExtra("UserID", "123456");
 context.startService(serviceIntent);

서비스가 시작되면 해당 onStartCommand()메서드가 호출되므로이 메서드에서 예를 들어 인 텐트 개체에서 값 (UserID)을 검색 할 수 있습니다.

public int onStartCommand (Intent intent, int flags, int startId) {
    String userID = intent.getStringExtra("UserID");
    return START_STICKY;
}

참고 : 위의 답변 getIntent()은 서비스 컨텍스트에서 올바르지 않은 방법 으로 의도를 가져 오도록 지정 합니다.


서비스를 바인딩하면 onBind(Intent intent).

활동:

 Intent intent = new Intent(this, LocationService.class);                                                                                     
 intent.putExtra("tour_name", mTourName);                    
 bindService(intent, mServiceConnection, BIND_AUTO_CREATE); 

서비스:

@Override
public IBinder onBind(Intent intent) {
    mTourName = intent.getStringExtra("tour_name");
    return mBinder;
}

또 다른 가능성은 intent.getAction을 사용하는 것입니다.

서비스 중 :

public class SampleService inherits Service{
    static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
    static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
    static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
    static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        //System.out.println("ACTION: "+action);
        switch (action){
            case ACTION_START:
                startingService(intent.getIntExtra("valueStart",0));
                break;
            case ACTION_DO_SOMETHING_1:
                int value1,value2;
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething1(value1,value2);
                break;
            case ACTION_DO_SOMETHING_2:
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething2(value1,value2);
                break;
            case ACTION_STOP_SERVICE:
                stopService();
                break;
        }
        return START_STICKY;
    }

    public void startingService(int value){
        //calling when start
    }

    public void doSomething1(int value1, int value2){
        //...
    }

    public void doSomething2(int value1, int value2){
        //...
    }

    public void stopService(){
        //...destroy/release objects
        stopself();
    }
}

활동 중 :

public void startService(int value){
    Intent myIntent = new Intent(SampleService.ACTION_START);
    myIntent.putExtra("valueStart",value);
    startService(myIntent);
}

public void serviceDoSomething1(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void serviceDoSomething2(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void endService(){
    Intent myIntent = new Intent(SampleService.STOP_SERVICE);
    startService(myIntent);
}

마지막으로 매니페스트 파일에서 :

<service android:name=".SampleService">
    <intent-filter>
        <action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
        <action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
    </intent-filter>
</service>

활동:

int number = 5;
Intent i = new Intent(this, MyService.class);
i.putExtra("MyNumber", number);
startService(i);

서비스:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getExtras() != null){
        int number = intent.getIntExtra("MyNumber", 0);
    }
}

이것은 훨씬 더 좋고 안전한 방법입니다. 매력처럼 작동합니다!

   private void startFloatingWidgetService() {
        startService(new Intent(MainActivity.this,FloatingWidgetService.class)
                .setAction(FloatingWidgetService.ACTION_PLAY));
    }

대신에 :

 private void startFloatingWidgetService() {
        startService(new Intent(FloatingWidgetService.ACTION_PLAY));
    }

두 번째를 시도하면 다음과 같은 오류가 발생하기 때문입니다. java.lang.IllegalArgumentException : 서비스 의도는 명시 적이어야합니다. Intent {act = com.floatingwidgetchathead_demo.SampleService.ACTION_START}

그러면 귀하의 서비스는 다음과 같습니다.

static final String ACTION_START = "com.floatingwidgetchathead_demo.SampleService.ACTION_START";
    static final String ACTION_PLAY = "com.floatingwidgetchathead_demo.SampleService.ACTION_PLAY";
    static final String ACTION_PAUSE = "com.floatingwidgetchathead_demo.SampleService.ACTION_PAUSE";
    static final String ACTION_DESTROY = "com.yourcompany.yourapp.SampleService.ACTION_DESTROY";

 @SuppressLint("LogConditional")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String action = intent.getAction();
    //System.out.println("ACTION: "+action);
    switch (action){
        case ACTION_START:
            Log.d(TAG, "onStartCommand: "+action);
            break;
        case ACTION_PLAY:
            Log.d(TAG, "onStartCommand: "+action);
           addRemoveView();
           addFloatingWidgetView();
            break;
        case ACTION_PAUSE:
            Log.d(TAG, "onStartCommand: "+action);
            break;
        case ACTION_DESTROY:
            Log.d(TAG, "onStartCommand: "+action);
            break;
    }
    return START_STICKY;

}

서비스 : startservice는 메신저를 사용하고 데이터를 전달하는 가장 좋은 방법, 부작용을 일으킬 수 있습니다.

private CallBackHandler mServiceHandler= new CallBackHandler(this);
private Messenger mServiceMessenger=null;
//flag with which the activity sends the data to service
private static final int DO_SOMETHING=1;

private static class CallBackHandler extends android.os.Handler {

private final WeakReference<Service> mService;

public CallBackHandler(Service service) {
    mService= new WeakReference<Service>(service);
}

public void handleMessage(Message msg) {
    //Log.d("CallBackHandler","Msg::"+msg);
    if(DO_SOMETHING==msg.arg1)
    mSoftKeyService.get().dosomthing()
}
}

활동 : 의도에서 메신저 가져 오기 데이터를 채우고 메시지를 서비스에 다시 전달

private Messenger mServiceMessenger;
@Override
protected void onCreate(Bundle savedInstanceState) {
mServiceMessenger = (Messenger)extras.getParcelable("myHandler");
}


private void sendDatatoService(String data){
Intent serviceIntent= new 
Intent(BaseActivity.this,Service.class);
Message msg = Message.obtain();
msg.obj =data;
msg.arg1=Service.DO_SOMETHING;
mServiceMessenger.send(msg);
}

Pass data from Activity to IntentService

This is how I pass data from Activity to IntentService.

One of my application has this scenario.

MusicActivity ------url(String)------> DownloadSongService

1) Send Data (Activity code)

  Intent intent  = new Intent(MusicActivity.class, DownloadSongService.class);
  String songUrl = "something"; 
  intent.putExtra(YOUR_KEY_SONG_NAME, songUrl);
  startService(intent);

2) Get data in Service (IntentService code)
You can access the intent in the onHandleIntent() method

public class DownloadSongService extends IntentService {

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        String songUrl = intent.getStringExtra("YOUR_KEY_SONG_NAME");

        //  Download File logic

    }

}

참고URL : https://stackoverflow.com/questions/3293243/pass-data-from-activity-to-service-using-an-intent

반응형