我有IzborKategorija.java活动,在用户的复选框选项中创建STRING,我需要发送到asyncTask作为我用来制作GET方法的url的最后一部分。所以,我创建了STRING,如:3,6,7,9,我需要将此字符串附加到" http://www.example.com/push/?device_token=" + regid +"& channels_ids =" + STRINGFROMACTIVITY。 我的AsyncTask已经在等待GCM的注册,以及如何在那里再添加一个参数?
我的活动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);
}
}
答案 0 :(得分:2)
您可以将 public Boolean SaveToFile(String text)
{
final String textEx = text;
return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run()
{
File file = new File("c:\\myFile.txt");
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
file.setReadable(true);
file.setWritable(true);
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( textEx );
bw.close( );
return true;
} }
});
从Activity传递给构造函数中的AsyncTask。
例如:
在您的活动中,
STRINGFROMACTIVITY
在AsycnTask(RegisterApp)构造函数中,
new RegisterApp(STRINGFROMACTIVITY).execute();
查看您的代码,我发现您已经有3个参数从Activity传递到Asyctask,如String STRINGFROMACTIVITY; //create string variable in RegisterApp
......
......
public RegisterApp(String STRINGFROMACTIVITY){
this.STRINGFROMACTIVITY= STRINGFROMACTIVITY;
}
,现在字符串值应该是要传递的第四个参数。
您的Context ctx, GoogleCloudMessaging gcm, int appVersion
也应该传递这4个参数。