C
C
CeBePHblY2016-04-26 18:24:05
Android
CeBePHblY, 2016-04-26 18:24:05

How to send data to an already running Service?

How to send data to an already running service?
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClickStart"
        android:text="@string/start">
    </Button>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:text="3" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText2" />
</LinearLayout>

MainActivity.java
package com.example.my.myapplication;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import android.view.View;
import android.widget.EditText;


public class MainActivity extends Activity {

    public final static String BROADCAST_ACTION = "com.example.my.myapplication";

    BroadcastReceiver br;
    EditText EditText1;
    EditText EditText2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText1 = (EditText) findViewById(R.id.editText1);
        EditText2 = (EditText) findViewById(R.id.editText2);

        // создаем BroadcastReceiver
        br = new BroadcastReceiver() {
            // действия при получении сообщений
            public void onReceive(Context context, Intent intent) {
                int result = intent.getIntExtra("result", 0);
                String re = Integer.toString(result);
                EditText2.setText(re);
            }
        };
        // создаем фильтр для BroadcastReceiver
        IntentFilter intFilt = new IntentFilter(BROADCAST_ACTION);
        // регистрируем (включаем) BroadcastReceiver
        registerReceiver(br, intFilt);


        Intent intent;

        // Создаем Intent для вызова сервиса,
        // кладем туда параметр времени и код задачи
        int s = Integer.parseInt(EditText1.getText().toString());
        intent = new Intent(this, MyService.class).putExtra("time", s);
        intent.putExtra("time", s);
        // стартуем сервис
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // дерегистрируем (выключаем) BroadcastReceiver
        unregisterReceiver(br);
    }

    public void onClickStart(View v) {
        Intent intent;
        int s = Integer.parseInt(EditText1.getText().toString());
        intent = new Intent(this, MyService.class).putExtra("time", s);
        intent.putExtra("time", s);
    }

}

MyService.java
package com.example.my.myapplication;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {

    ExecutorService es;

    public void onCreate() {
        super.onCreate();
        es = Executors.newFixedThreadPool(1);
    }

    public void onDestroy() {
        super.onDestroy();
    }

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

        int time = intent.getIntExtra("time", 1);
        MyRun mr = new MyRun(startId, time);
        es.execute(mr);

        return super.onStartCommand(intent, flags, startId);
    }

    public IBinder onBind(Intent arg0) {
        return null;
    }

    class MyRun implements Runnable {

        int time;
        int startId;

        public MyRun(int startId, int time) {
            this.time = time;
            this.startId = startId;
        }

        public void run() {
            Intent intent = new Intent(MainActivity.BROADCAST_ACTION);
            while (true) {
                try {
                    // начинаем выполнение задачи
                    TimeUnit.SECONDS.sleep(time);
                    // сообщаем об окончании задачи
                    intent.putExtra("result", time * 100);
                    sendBroadcast(intent);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
           // stop();
        }

        void stop() {
            stopSelfResult(startId);
        }
    }
}

What I want from the application: at startup, the service starts, a number is sent to it, it multiplies this number by 100 and sends the result to the activity in the second text field (and continues to work further). Next, I want to send a new number to the service without stopping its work, I enter a new number in the first test field, and when I click on the button, I need to send this number to the service, and it must also multiply it by 100 and send it back to the activity in the first text field . I can not figure out how to transfer data to an already running service. Tell.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2016-04-26
@onepavel

The documentation in Russian says
"Multiple service start requests result in multiple corresponding calls to the service's onStartCommand() method."

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question