Java android 意图服务只工作一次
Java android intent service works only one time
我想创建一个意图服务,它在整个应用程序中(在所有 activity 中)都有时间段并执行任务。我使用 Handler 。我在 activity 开始了一项服务。我看到只有一次服务工作(执行任务)为什么?
这是我的服务:
public class SenderXML extends Service {
public static boolean running = false;
private Timer timer = new Timer();
private SendXMLTask sendXMLTask;
private Context context;
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
Gson gson = new Gson();
MainActivity.xmlList = null;
MainActivity.xmlList = new ArrayList<>();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
List<String> productFromShared1 = new ArrayList<>();
String jsonPreferences1 = sharedPref.getString("TAG1", "");
Type type1 = new TypeToken<List<String>>() {
}.getType();
productFromShared1 = gson.fromJson(jsonPreferences1, type1);
if (productFromShared1 != null)
MainActivity.xmlList.addAll(productFromShared1);
Log.e("tworzenie serwisu ", "tworzenie");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Dziełanie serwisu ", "Dziełanie");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.e("Dziełanie serwisu 1111", "Dziełanie 111");
if (!MainActivity.xmlList.isEmpty()) {
if (NetworkUtil.isNetworkAvailable(context)) {
if (!running) {
sendXMLTask = new SendXMLTask();
sendXMLTask.execute();
}
}
}
}
}, 1000 * 60 * 2);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if (running) {
timer.cancel();
sendXMLTask = new SendXMLTask();
sendXMLTask.cancel(true);
running = false;
}
Log.e("service ", "nie działa");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
class SendXMLTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
Log.e("xml ", MainActivity.xmlList.size() +"");
running = true;
HttpClient httpclient = HttpClientUtil.getHttpClient(getApplicationContext());
HttpPost httppost = new HttpPost(Util.getServerUrl(getApplicationContext()) + "/SetData");
ArrayList<NameValuePair> namevaluepairs = new ArrayList<>(2);
namevaluepairs.add(new BasicNameValuePair("token", String.valueOf(E_Gps.TOKEN)));
namevaluepairs.add(new BasicNameValuePair("xml", MainActivity.xmlList.get(0)));
if (MainActivity.xmlList.size() > 0) {
MainActivity.btTransfer.setBackgroundColor(Color.YELLOW);
}
try {
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
return null;
}
InputStream responseInputStream = null;
try {
responseInputStream = new BufferedInputStream(response.getEntity().getContent());
try {
int tt = ResponseParser.getResponseType(responseInputStream);
if (tt == 0) {
return null;
}
} catch (EmptyResponseException | UnknownAnswerName | XmlPullParserException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
Log.e("xml", MainActivity.xmlList.get(0));
Log.e("xml wys ", convertStreamToString(responseInputStream));
return convertStreamToString(responseInputStream);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
MainActivity.xmlList.remove(0);
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(MainActivity.xmlList);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TAG1", jsonCurProduct);
editor.apply();
}
if (!MainActivity.xmlList.isEmpty()) {
sendXMLTask = new SendXMLTask();
sendXMLTask.execute();
} else {
MainActivity.btTransfer.setBackgroundColor(Color.GREEN);
}
running = false;
}
}
}
您是否尝试过使用警报管理器定期启动您的 Intent 服务?
如果您还没有尝试过,可以按照此 link 进行操作
Alarm Manager Example
您可以使用警报管理器定期启动您的 Intent 服务。
当您在 Activity
中调用 startService()
时,将创建 Service
(如果它尚不存在)并调用 onStartCommand()
。除非您再次调用 startService()
,否则不会再次调用 onStartCommand()
。
由于您是在 onStartCommand()
中发布 Runnable
,您应该让 Runnable
在一段时间后将自己重新发布到 运行(如果您想要这到 运行 连续)。
确保在用完后停止 Service
。
我想创建一个意图服务,它在整个应用程序中(在所有 activity 中)都有时间段并执行任务。我使用 Handler 。我在 activity 开始了一项服务。我看到只有一次服务工作(执行任务)为什么? 这是我的服务:
public class SenderXML extends Service {
public static boolean running = false;
private Timer timer = new Timer();
private SendXMLTask sendXMLTask;
private Context context;
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
Gson gson = new Gson();
MainActivity.xmlList = null;
MainActivity.xmlList = new ArrayList<>();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
List<String> productFromShared1 = new ArrayList<>();
String jsonPreferences1 = sharedPref.getString("TAG1", "");
Type type1 = new TypeToken<List<String>>() {
}.getType();
productFromShared1 = gson.fromJson(jsonPreferences1, type1);
if (productFromShared1 != null)
MainActivity.xmlList.addAll(productFromShared1);
Log.e("tworzenie serwisu ", "tworzenie");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Dziełanie serwisu ", "Dziełanie");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.e("Dziełanie serwisu 1111", "Dziełanie 111");
if (!MainActivity.xmlList.isEmpty()) {
if (NetworkUtil.isNetworkAvailable(context)) {
if (!running) {
sendXMLTask = new SendXMLTask();
sendXMLTask.execute();
}
}
}
}
}, 1000 * 60 * 2);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if (running) {
timer.cancel();
sendXMLTask = new SendXMLTask();
sendXMLTask.cancel(true);
running = false;
}
Log.e("service ", "nie działa");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
class SendXMLTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
Log.e("xml ", MainActivity.xmlList.size() +"");
running = true;
HttpClient httpclient = HttpClientUtil.getHttpClient(getApplicationContext());
HttpPost httppost = new HttpPost(Util.getServerUrl(getApplicationContext()) + "/SetData");
ArrayList<NameValuePair> namevaluepairs = new ArrayList<>(2);
namevaluepairs.add(new BasicNameValuePair("token", String.valueOf(E_Gps.TOKEN)));
namevaluepairs.add(new BasicNameValuePair("xml", MainActivity.xmlList.get(0)));
if (MainActivity.xmlList.size() > 0) {
MainActivity.btTransfer.setBackgroundColor(Color.YELLOW);
}
try {
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
return null;
}
InputStream responseInputStream = null;
try {
responseInputStream = new BufferedInputStream(response.getEntity().getContent());
try {
int tt = ResponseParser.getResponseType(responseInputStream);
if (tt == 0) {
return null;
}
} catch (EmptyResponseException | UnknownAnswerName | XmlPullParserException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
Log.e("xml", MainActivity.xmlList.get(0));
Log.e("xml wys ", convertStreamToString(responseInputStream));
return convertStreamToString(responseInputStream);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
MainActivity.xmlList.remove(0);
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(MainActivity.xmlList);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TAG1", jsonCurProduct);
editor.apply();
}
if (!MainActivity.xmlList.isEmpty()) {
sendXMLTask = new SendXMLTask();
sendXMLTask.execute();
} else {
MainActivity.btTransfer.setBackgroundColor(Color.GREEN);
}
running = false;
}
}
}
您是否尝试过使用警报管理器定期启动您的 Intent 服务? 如果您还没有尝试过,可以按照此 link 进行操作 Alarm Manager Example
您可以使用警报管理器定期启动您的 Intent 服务。
当您在 Activity
中调用 startService()
时,将创建 Service
(如果它尚不存在)并调用 onStartCommand()
。除非您再次调用 startService()
,否则不会再次调用 onStartCommand()
。
由于您是在 onStartCommand()
中发布 Runnable
,您应该让 Runnable
在一段时间后将自己重新发布到 运行(如果您想要这到 运行 连续)。
确保在用完后停止 Service
。