gpt4 book ai didi

java - 如何将字符串值从 Activity 发送到异步任务?

转载 作者:行者123 更新时间:2023-12-02 04:34:50 25 4
gpt4 key购买 nike

我有 IzborKategorija.java Activity ,根据用户的复选框选择创建 STRING,我需要将其发送到 asyncTask 作为我用来创建 GET 方法的 url 的最后一部分。因此,我创建如下字符串:3,6,7,9,我需要将此字符串附加到“http://www.example.com/push/?device_token=”+regid+“&channels_ids=”+STRINGFROMACTIVITY。我的 AsyncTask 已经在等待 GCM 注册,如何在那里再添加一个参数?

我的 Activity IzborKategorija.java:

import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class IzborKategorija extends Activity{
ListView myList;
Button getChoice, clearAll;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice" ;
ArrayList<String> selectedItems = new ArrayList<String>();
private static final String TAG = "KATARINA";
String savedItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView)findViewById(R.id.list);
getChoice = (Button)findViewById(R.id.getchoice);
clearAll = (Button)findViewById(R.id.clearall);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.Mobile_OS));
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences.contains(MyPREFERENCES)){
LoadSelections();
}

getChoice.setOnClickListener(new Button.OnClickListener(){


@Override
public void onClick(View v) {

String selected = "";
int cntChoice = myList.getCount();

SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++){
if(sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString() + "\n";
System.out.println("Checking list while adding:" + myList.getItemAtPosition(i).toString());
SaveSelections();
}

}


Toast.makeText(IzborKategorija.this, selected, Toast.LENGTH_LONG).show();

}});

clearAll.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});


}

private void SaveSelections() {
// save the selections in the shared preference in private mode for the user

SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}

private String getSavedItems() {
String savedItems = "";
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}

savedItems = savedItems.replaceAll("[^0-9,]", "");
Log.i(TAG, "SPISAK ODABRANIH: " + savedItems);
return savedItems;


}


private void LoadSelections() {
// if the selections were previously saved load them

if (sharedpreferences.contains(MyPREFERENCES.toString())) {

String savedItems = sharedpreferences.getString(MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));

int count = this.myList.getAdapter().getCount();

for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter()
.getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Curren Item: " + currentItem,
Toast.LENGTH_LONG).show();
} else {
myList.setItemChecked(i, false);
}

}
}
}

private void ClearSelections() {
// user has clicked clear button so uncheck all the items
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myList.setItemChecked(i, false);
}
// also clear the saved selections
SaveSelections();
}

}

我的AsyncTask RegisterApp.java:

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;


public class RegisterApp extends AsyncTask<Void, Void, String> {

private static final String TAG = "GCMRelated";
Context ctx;
GoogleCloudMessaging gcm;
String SENDER_ID = "980800840437";
String regid = null;
private int appVersion;
public RegisterApp(Context ctx, GoogleCloudMessaging gcm, int appVersion){
this.ctx = ctx;
this.gcm = gcm;
this.appVersion = appVersion;
}


@Override
protected void onPreExecute() {
super.onPreExecute();
}


@Override
protected String doInBackground(Void... arg0) {


String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(ctx);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;

// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();

// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.

// Persist the regID - no need to register again.
storeRegistrationId(ctx, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;

}


private void storeRegistrationId(Context ctx, String regid) {
final SharedPreferences prefs = ctx.getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("registration_id", regid);
editor.putInt("appVersion", appVersion);
editor.commit();

}




private void sendRegistrationIdToBackend() throws IOException {

URL obj = new URL("http://www.example.com/push/?device_token="+regid+"&channels_id="+STRINGFROMACTIVITY);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// print result
System.out.println(response.toString());

Log.i(TAG, "OVO SAM POSLAO " + savedItems);

} else {
System.out.println("GET request not worked");
}

}



@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(ctx, "Registration Completed. Now you can see the notifications", Toast.LENGTH_SHORT).show();
Log.v(TAG, result);
}
}

最佳答案

您可以在构造函数中将 STRINGFROMACTIVITY 从 Activity 传递到 AsyncTask。例如:在您的 Activity 中,

new RegisterApp(STRINGFROMACTIVITY).execute();

在 AsycnTask(RegisterApp) 构造函数中,

String STRINGFROMACTIVITY;  //create string variable in RegisterApp
......
......

public RegisterApp(String STRINGFROMACTIVITY){
this.STRINGFROMACTIVITY= STRINGFROMACTIVITY;
}

查看您的代码,我发现您已经有 3 个参数从 Activity 传递到 Asyctask,例如 Context ctx、GoogleCloudMessaging gcm、int appVersion,现在字符串值应该是要传递的第四个参数。另外,您的 AsyncTask 应该传递这 4 个参数。

关于java - 如何将字符串值从 Activity 发送到异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30969290/

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