Answer the question
In order to leave comments, you need to log in
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>
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);
}
}
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);
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question