Ich möchte die Benutzeroberfläche alle 5 Sekunden nach dem Aufrufen eines Webdienstes aktualisieren, auch wenn die App geschlossen ist. Ich habe einen Dienst erstellt und Broadcast-Empfänger verwenden, ich bekomme die Daten vom Server, aber wenn die Anwendung geschlossen wird, sollte die letzte Antwort vom Server aktualisiert werden, aber wenn ich die App öffne, werden die letzten Antwortdaten nicht aktualisiert.Textansicht in einer Aktivität von einem Hintergrunddienst aktualisieren, selbst wenn die Anwendung geschlossen ist
Unten ist der Code-Schnipsel
MainActivity.java
import java.text.DateFormat;
import org.json.JSONArray;
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.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView name1, name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView)findViewById(R.id.name);
name1 = (TextView)findViewById(R.id.name1);
startService(new Intent(MainActivity.this, YourService.class));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String nameStr = intent.getStringExtra("name");
String name1Str = intent.getStringExtra("name1");
name.setText(nameStr);
name1.setText(name1Str);
}
};
@Override
protected void onResume()
{
super.onResume();
//registerReceiver(statusReceiver,mIntent);
LocalBroadcastManager.getInstance(MainActivity.this).registerReceiver(
mMessageReceiver, new IntentFilter("UIValues"));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="12dp"
android:hint="md5"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
<TextView
android:id="@+id/name1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="12dp"
android:hint="name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20sp" />
</LinearLayout>
YourService.java
import learn2crack.asynctask.library.JSONParser;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class YourService extends Service {
private static final String TAG = "Your Service";
private final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
new JSONParse().execute();
/// Any thing you want to do put the code here like web service procees it will run in ever 1 second
handler.postDelayed(this, 5000); // 5 seconds
}
};
@Override
public void onStart(Intent intent, int startid) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000);//1 second
Log.d(TAG, "onStart");
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url); // server url
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject reader = new JSONObject(json.toString());
String name = reader.getString("name");
String name1 = reader.getString("name1");
Intent intent = new Intent("UIValues");
intent.putExtra("name", name);
intent.putExtra("name1", name1);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asynctask"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.asynctask.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.asynctask.YourService"></service>
</application>
</manifest>
Kann mir jemand helfen, dieses Problem zu lösen. Vielen Dank im Voraus
Alle 5 Sekunden etwas zu tun ist schrecklich für die Akkulaufzeit. Nutzer haben sich sehr laut darüber beschwert ** und Google ergreift weiterhin Maßnahmen, um zu verhindern, dass Apps dies tun. Der Doze-Modus und die App-Standby-Funktion unter Android 6.0 und höher führen beispielsweise dazu, dass Ihre Jobs sehr selten in der Größenordnung von einer Stunde oder weniger ausgeführt werden. Und auf Android 8.0+ wird Ihr Dienst nach ~ 1 Minute gestoppt. – CommonsWare
Warum verwenden Sie Firebase nicht für dieses Problem, es wird Ihr Problem leicht lösen. Wenn ich Daten von Firebase erhalte und sie in textview einstelle, aktualisiere sie in Firebase, sie wird dann und dort aktualisieren. –
@ CommsWare-Dienst sollte alle 30 Sekunden aufgerufen werden, das ist die Voraussetzung –