gpt4 book ai didi

android - 即使应用程序关闭,也可以从后台服务更新 Activity 中的 textview

转载 作者:行者123 更新时间:2023-11-29 19:09:18 25 4
gpt4 key购买 nike

即使应用已关闭,我也想在调用网络服务后每 5 秒更新一次 UI。我创建了一个服务并使用广播接收器从服务器获取数据,但是当应用程序关闭时,服务器的最后响应应该更新,但是当我打开应用程序时,最后响应数据没有更新。

下面是代码 fragment

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>

谁能帮我解决这个问题。提前致谢

最佳答案

您可能应该将最后一个响应保存在持久性存储(文件、共享首选项)中,并在应用程序打开后简单地读取它并显示最后一个响应。

关于android - 即使应用程序关闭,也可以从后台服务更新 Activity 中的 textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com