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

时间:2017-08-29 11:08:31

标签: android android-intent service broadcastreceiver

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

以下是代码段

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>

任何人都可以帮我解决这个问题。 提前致谢

3 个答案:

答案 0 :(得分:2)

您应该将最后一个响应保存在持久存储(文件,共享优先)中,并在应用程序打开后阅读它并显示最后一个响应。

答案 1 :(得分:0)

将您的回复存储到SharedPreferences,当活动未打开时,如果活动在关闭时活动将不会接收广播,则其视图将无法从服务中更新。另一方面,如果您在共享首选项中存储了最新响应,则可以读取所创建活动的值并在视图中设置该值。 这将确保您获得视图的最新响应。

答案 2 :(得分:0)

当您的应用未关闭时,您无法知道数据是否已更新。当用户看不到应用的UI时,没有必要更新它。您需要的是每次打开应用程序时都应该更新它。 在您的服务中,您可以存储数据并通过活动的onCreate(Bundle savedInstanceState)方法获取数据。

享受编码。!!