Home > Mobile >  Pass array from activity to service (Android)
Pass array from activity to service (Android)

Time:10-23

i'm beginner to java and i'm trying to do the following: in MainActivity generate an array and pass it to the Service. The difficulty lies precisely in how to pass this array to the Service. Yes, I saw that there are many similar questions, but I can't understand the principle of how this happens.

What can you advise me?

MainActivity.java

package com.example.myservice;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int[] arr = new int[5];
        StringBuilder num = new StringBuilder();

        for(int i = 0; i < 5; i  ) {
            arr[i] = (int) (Math.random() * 10);
            num.append(arr[i]).append(" ");
        }

        TextView textView = findViewById(R.id.textView2);

        textView.setText(num);
        startService(new Intent(this, MyService.class));
    }
}

MyService.java

package com.example.myservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


public class MyService extends Service {
    @Override
    public void onCreate(){
        Log.i("MyLog", "onCreate");
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

CodePudding user response:

in MainActivity start your service like this

 Intent intent =new Intent(this,MyService.class);
        intent.putExtra("myArray",arr); 
        startService(intent);

on your service override onStartCommand method

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int myList[]=intent.getIntArrayExtra("myArray");
        for (int item:myList){
            Log.i("MyLog", "onStartCommand: " item);
        }
        return super.onStartCommand(intent, flags, startId);

    }

and don't forget to declare your service on AndroidManifest file inside Application tag add

<service android:name=".MyService"/>
  • Related