Android服务没有及时更新变量

时间:2014-06-10 11:20:24

标签: java android service httprequest


我只是想知道为什么我的Activity中声明的静态变量在我的服务中没有及时为getTimeStamp()方法调用更新。这是因为服务是同时运行的,如果是这样的话,我可以给它一个令牌,确保它在代码运行之前完成。您可以在验证方法中看到这一点。该服务首先被激活,例如将更新'类型'变量。但是当程序到达getTimeStamp()时键入'即使它现在应该等于"登录"仍然是null。 谢谢,

这是我的主要活动

public class MainActivity extends Activity {

//TAG.
public static final String TAG = "BOE_TEST";

//UI elements.
Button TestNow;
ListView listView;
ArrayAdapter<String> adapter;

//Timer.
Timer repeatTask = new Timer();

//Global variables and data structures.
int repeatInterval = 10000 * 1; // 10 sec
static Boolean success = true;
static String type;
ArrayList<String> values = new ArrayList<String>();
static int count;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.list);
    adapter = new ArrayAdapter<String>(this,
            R.layout.listview_each_item, android.R.id.text1, values);

    // Assign adapter to ListView
    listView.setAdapter(adapter);

    TestNow = (Button) findViewById(R.id.button_test);
    repeatTask.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    validation("Login");
                }
            });
        }
    }, 0, repeatInterval);


    TestNow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    validation("Login");
                }
            });

        }
    });


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


public void validation(String validate) {
    Intent i;
    i = new Intent(MainActivity.this, LoginService.class);
    MainActivity.this.startService(i);
    MainActivity.this.stopService(i);

    values.add(0, getTimeStamp());
    adapter.notifyDataSetChanged();

    try {
        if (success == true) {
            listView.getChildAt(count).setBackgroundColor(Color.parseColor("#009900"));
            count++;
        } else {
            listView.getChildAt(count).setBackgroundColor(Color.parseColor("#cc0000"));
            count++;
        }
    } catch (NullPointerException e) {

    }
}


public static String getTimeStamp() {
    String s = "";
    String whiteSpaces = "         ";
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");//Date
    s += "\n" + "Time: " + sdf.format(new Date()) + whiteSpaces ;
    sdf = new SimpleDateFormat("dd.MM.yyyy");//Time
    Date date = new Date();
    s += "Date: " + sdf.format(date) + whiteSpaces+ "/*" + type + "*/";
    return s;
}


}

这是我的服务

public class LoginService extends Service {

//TAG
private static final String TAG = "loginService";


//final variables
private static final String email = "xxxxxxxxxx";
private static final String password = "xxxxxxxxxxx";
private static final String login = "login";
private static final String BOE_LOGIN = "http://thebookofeveryone.com/account/";


@Override

public void onDestroy() {
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}


public int onStartCommand(Intent intent, int flags, int startId) {

    Login task = new Login();
    task.execute();

    return START_STICKY;
}





 public class Login extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... strings) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(BOE_LOGIN);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("email", email));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        nameValuePairs.add(new BasicNameValuePair("action", login));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // Execute HTTP Post Request
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (response.getStatusLine().getStatusCode() < 400) {
        } else {
            Log.d(TAG, "Response error: "
                    + response.getStatusLine().getStatusCode());
        }


        HttpEntity entity = response.getEntity();
        String responseString = null;
        try {
            responseString = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseString;

    }


    @Override
    protected void onPostExecute(String s) {
       MainActivity.type="Login";

        if(s.contains("We could not find a matching account")){
            Log.i(TAG,"Login Failed");
            createNotification("Login Failed");
            MainActivity.success = false;


        }else{
            Log.i(TAG,"Login Successfull");
            MainActivity.success = true;


        }


}

}

public void createNotification(String s) {

    Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
            R.drawable.boelogo);
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.boelogo)
                    .setLargeIcon(icon)
                    .setContentTitle( getResources().getString(R.string.app_name))
                    .setContentText(s);


    // Add as notification
    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(001,builder.build());


   }
} 

1 个答案:

答案 0 :(得分:0)

我在服务中使用LocalBroadcastManager解决了这个问题,当我完成了服务后,我解雇了广播并在我的Activity中使用了方法来监听它

服务

@Override
public void onCreate() {
    super.onCreate();
    broadcaster = LocalBroadcastManager.getInstance(this);

}

   private void sendResult() {
    Intent intent = new Intent("sendResult");
    sendLocationBroadcast(intent);
}

private void sendLocationBroadcast(Intent intent){
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

活动

//在onCreate()

  LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter("sendResult"));

}


  private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
       validation();
    }
};