Related
Hello I am creating a social network in android, I have fetching data from mysql data and put it in listview Adapter but I need auto refresh for listview and notification if there is new insert data, I am using Broadcast receiver and service but it there is nothing happen please help me
here is my code
Broadcast receiver
public class BraodcastReceiverNotif extends BroadcastReceiver {
static int noOfTimes = 0;
JSONObject data;
Exception exception;
SharedPreferences sharedpreferences;;
public static final String mypreference = "pkAppPrefs";
int pageNumber = 0;
public static final int REQUEST_CODE = 12345;
Intent intnt;
Context context;
#Override
public void onReceive(final Context context, Intent intent) {
sharedpreferences = context.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
noOfTimes++;
//Toast.makeText(context, "BC Service Running for " + noOfTimes + " times", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
noOfTimes++;
try {
startNetworkCalls ();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void startNetworkCalls () throws JSONException {
data = new JSONObject();
data.put("user_key", sharedpreferences.getString("userKey", ""));
data.put("city_id", sharedpreferences.getString("user_city_id", ""));
data.put("sector_id", sharedpreferences.getString("sector_id", ""));
data.put("page", pageNumber);
String URL = ".............................................";
getOnlinePosts onlinePosts = new getOnlinePosts();
onlinePosts.execute(URL);
}
private class getOnlinePosts extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG =getOnlinePosts.class.getSimpleName();
private Exception exception = null;
#Override
protected void onPreExecute() {
}
#Override
protected String[] doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String docsJson = null;
String JsonDATA = data.toString();
String JsonResponse = null;
Context context = null;
try {
Log.e(LOG_TAG, "Started Connecting to " + params[0] + " Sending " +JsonDATA);
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
writer.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
docsJson = buffer.toString();
Log.v(LOG_TAG, "My data is: " + docsJson);
} catch (Exception e) {
exception = e;
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
return getDocumentDataFromJson(docsJson);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// this will only happen if there is an error
return null;
}
#Override
protected void onPostExecute(String[] result) {
}
}
private String[] getDocumentDataFromJson(String documentJsonStrArr)
throws JSONException {
final String data_status = "status";
final String data_data = "data";
final String data_name = "fullname";
final String data_username = "community";
JSONObject documentJson = new JSONObject(documentJsonStrArr);
String status = documentJson.getString(data_status);
if (status.equals("success")) {
JSONArray docs = documentJson.getJSONArray(data_data);
if (docs.length() > 0) {
for (int i = 0; i < docs.length(); i++) {
JSONObject singleDoc = docs.getJSONObject(i);
// String success = singleDoc.getString(documentJson.getString(data_status));
String name = singleDoc.getString(data_name);
String username = singleDoc.getString(data_username);
intnt = new Intent(context, MyService.class);
// Set unsynced count in intent data
intnt.putExtra("success", "success");
intnt.putExtra("name", name);
// Call MyService
context.startService(intnt);
}
}
}
return null;
}
}
here is my service
public class MyService extends Service {
int numMessages = 0;
ArrayList<SinglePost> PostEntries = null;
public ArrayAdapter<SinglePost> mycardAdapter;
SharedPreferences sharedpreferences;;
public static final String mypreference = "pkAppPrefs";
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Intent resultIntent = new Intent(this, Community.class);
Toast.makeText(this, intent.getStringExtra("name"), Toast.LENGTH_LONG).show();
PostEntries.add(new SinglePost(intent.getStringExtra("post_key"),
intent.getStringExtra("name"),
intent.getStringExtra("username"), intent.getStringExtra("profile_image"),intent.getStringExtra("poster_key") ,
intent.getStringExtra("postdate"),intent.getStringExtra("message") ,intent.getStringExtra("likes") ,
intent.getStringExtra("liked"),intent.getStringExtra("comments") ,intent.getStringExtra("commented") ,
Boolean.parseBoolean(intent.getStringExtra("moderate")),intent.getStringExtra("sector") ,
intent.getStringExtra("district"),intent.getStringExtra("province") ,
intent.getStringExtra("city"),intent.getStringExtra("country") ,intent.getStringExtra("media") ,
Integer.parseInt(intent.getStringExtra("media_count") ),
Integer.parseInt(intent.getStringExtra("moderate_level")) ,
Boolean.parseBoolean( intent.getStringExtra("own_post")) ,intent.getStringExtra("online")));
//if (Integer.parseInt(intent.getStringExtra("count_data")) < Integer.parseInt(sharedpreferences.getString("count_data", ""))){
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 9001;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Alert")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_launcher);
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | android.app.Notification.DEFAULT_LIGHTS;
defaults = defaults | android.app.Notification.DEFAULT_VIBRATE;
defaults = defaults | android.app.Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText(intent.getStringExtra("success"));
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
// }
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
MainActivity class i am passing scheduleAlarm method to check every 10 second in database and refresh my listview
Setup a recurring alarm every 10 seconds
public void scheduleAlarm() {
BroadCase Receiver Intent Object
Intent alarmIntent = new Intent(getContext().getApplicationContext(), BraodcastReceiverNotif.class);
// Pending Intent Object
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext().getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Alarm Manager Object
AlarmManager alarmManager = (AlarmManager) getContext().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// Alarm Manager calls BroadCast for every Ten seconds (10 * 1000), BroadCase further calls service to check if new records are inserted in
// Remote MySQL DB
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 5000, 10 * 1000, pendingIntent);
}
fixed format
I really dont understand your question but I got some sense.
If I understand correctly, you want to fetch data from server, store in SQLite database and display the data in Listview
To achieve this functionality,
Create the Http class that gets data from the server.
Create IntentService to make HTTP request.
Once receive data from the server, insert into SQLite. And Broadcast
how you can broadcast is,
you register broadcast receiver in your activity that has the listview.
The broadcast only pass the message as the 'boolean' value that determines did data fetch from the server? If successfully fetched from the server then pass boolean true and after broadcast receive , make a local db call and fetch all changes. After that you can update the listview
I am uploading a file to Amazon S3 server into my BUCKET i am getting error, i am using the code from github https://github.com/jgilfelt/android-simpl3r i will post my code: i have found some information here about my error but i don not know to solve this error https://github.com/jgilfelt/android-simpl3r/issues/4
Status Code: 400, AWS Service: Amazon S3, AWS Request ID: D49EFFBB39B49EEA, AWS Error Code: MalformedXML, AWS Error Message: The XML you provided was not well-formed or did not validate against our published schema, S3 Extended Request ID: fpAsdF+sxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start file chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"Select a file to upload"),FILE_SELECT_CODE);
}
});
public class UploadService extends IntentService {
public static final String ARG_FILE_PATH = "file_path";
public static final String UPLOAD_STATE_CHANGED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_STATE_CHANGED_ACTION";
public static final String UPLOAD_CANCELLED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_CANCELLED_ACTION";
public static final String S3KEY_EXTRA = "s3key";
public static final String PERCENT_EXTRA = "percent";
public static final String MSG_EXTRA = "msg";
private static final int NOTIFY_ID_UPLOAD = 1337;
private AmazonS3Client s3Client;
private Uploader uploader;
private NotificationManager nm;
public UploadService() {
super("simpl3r-example-upload");
}
#Override
public void onCreate() {
super.onCreate();
s3Client = new AmazonS3Client(
new BasicAWSCredentials(getString(R.string.s3_access_key), getString(R.string.s3_secret)));
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
IntentFilter f = new IntentFilter();
f.addAction(UPLOAD_CANCELLED_ACTION);
registerReceiver(uploadCancelReceiver, f);
}
#Override
protected void onHandleIntent(Intent intent) {
String filePath = intent.getStringExtra(ARG_FILE_PATH);
File fileToUpload = new File(filePath);
Log.v("filePath", ""+filePath);
final String s3ObjectKey = md5(filePath);
Log.v("s3ObjectKey", ""+s3ObjectKey);
String s3BucketName = getString(R.string.s3_bucket);
final String msg = "Uploading " + s3ObjectKey + "...";
// create a new uploader for this file
uploader = new Uploader(this, s3Client, s3BucketName, s3ObjectKey, fileToUpload);
// listen for progress updates and broadcast/notify them appropriately
uploader.setProgressListener(new UploadProgressListener() {
#Override
public void progressChanged(ProgressEvent progressEvent,
long bytesUploaded, int percentUploaded) {
Notification notification = buildNotification(msg, percentUploaded);
nm.notify(NOTIFY_ID_UPLOAD, notification);
broadcastState(s3ObjectKey, percentUploaded, msg);
}
});
// broadcast/notify that our upload is starting
Notification notification = buildNotification(msg, 0);
nm.notify(NOTIFY_ID_UPLOAD, notification);
broadcastState(s3ObjectKey, 0, msg);
try {
String s3Location = uploader.start(); // initiate the upload
broadcastState(s3ObjectKey, -1, "File successfully uploaded to " + s3Location);
} catch (UploadIterruptedException uie) {
broadcastState(s3ObjectKey, -1, "User interrupted");
} catch (Exception e) {
e.printStackTrace();
broadcastState(s3ObjectKey, -1, "Error: " + e.getMessage());
}
}
#Override
public void onDestroy() {
nm.cancel(NOTIFY_ID_UPLOAD);
unregisterReceiver(uploadCancelReceiver);
super.onDestroy();
}
private void broadcastState(String s3key, int percent, String msg) {
Intent intent = new Intent(UPLOAD_STATE_CHANGED_ACTION);
Bundle b = new Bundle();
b.putString(S3KEY_EXTRA, s3key);
b.putInt(PERCENT_EXTRA, percent);
b.putString(MSG_EXTRA, msg);
intent.putExtras(b);
sendBroadcast(intent);
}
private Notification buildNotification(String msg, int progress) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setWhen(System.currentTimeMillis());
builder.setTicker(msg);
builder.setContentTitle(getString(R.string.app_name));
builder.setContentText(msg);
builder.setSmallIcon(R.drawable.ic_stat_uploading);
builder.setOngoing(true);
builder.setProgress(100, progress, false);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentIntent(contentIntent);
return builder.build();
}
private BroadcastReceiver uploadCancelReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (uploader != null) {
uploader.interrupt();
}
}
};
private String md5(String s) {
try {
// create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
I have been trying all day, but I can't seem to figure it out. I am trying to return a string from AsyncTask in BroadcastReceiver but I am not sure how to do it correctly (new at Java). I have an app that accesses the internet and reads a text file and this text file is a long string. I delimit the string into an array and use it contents that way. In the BroadcastReceiver I want to broadcast (update) the temperature from the weather station every 10-60 minutes depending on what the user sets-up on the notification bar.
Should I use a Thread instead of AsyncTask?
The error I get is with the following line:
String output = new GetWeatherValues().execute(weburi);
I also tried the following code that is commented out:
// GetWeatherValues clientraw = new GetWeatherValues();
// clientraw.doInBackground(weburi);
Below is my Class, please help, I have searched a lot and still no result.
public class UpdateFrequency extends BroadcastReceiver {
// Notification Text Elements
private final CharSequence tickerText = "Weather Updated";
private CharSequence contentTitle = "Weather at ";
private final CharSequence contentText = "Current Temperature is ";
final String http = "http://";
final String clientraw = "/clientraw.txt";
String weburi, webUrl;
// Notification Action Elements
private Intent notificationIntent;
private PendingIntent mContentIntent;
// Notification ID to allow for future updates
private static final int MY_NOTIFICATION_ID = 1;
final String PREFS_NAME = "SettingsFile";
SharedPreferences settings;
public String[] parts;
public static final String WebAddress = "webAddressKey";
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent) {
Log.e("log_etag", "Entered Update Frequency");
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(WebAddress)) {
webUrl = settings.getString(WebAddress, "");
weburi = http + webUrl + clientraw;
Log.e("log_etag", "WEB URL Frequency " + weburi);
}
// GetWeatherValues clientraw = new GetWeatherValues();
// clientraw.doInBackground(weburi);
String output = new GetWeatherValues().execute(weburi);
String[] parts = output.split(" ");
ArrayList<String> clientRawData = new ArrayList<String>();
clientRawData.addAll(Arrays.asList(parts));
//Time of last update from weather station.
contentTitle = contentTitle + parts[29] + ":" + parts[30];
Log.e("log_etag", "Content Title " + contentTitle);
// The Intent to be used when the user clicks on the Notification View
notificationIntent = new Intent(context, MainActivity.class);
// The PendingIntent that wraps the underlying Intent
mContentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Build the Notification
Notification.Builder notificationBuilder = new Notification.Builder(
context).setTicker(tickerText)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true).setContentTitle(contentTitle)
.setContentText(contentText).setContentIntent(mContentIntent);
// Get the NotificationManager
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Pass the Notification to the NotificationManager:
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
}
private class GetWeatherValues extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
// get url data
HttpPost httppost = new HttpPost(weburi);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
// convert response to string
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(webs, "iso-8859-1"),
8);
// read one line of code, file is one whole string.
try {
String returnData = reader.readLine();
webs.close();
return returnData;
} catch (Exception e) {
Log.e("log_tag",
"Error in displaying textview "
+ e.toString());
e.printStackTrace();
}
} catch (Exception e) {
Log.e("log_tag",
"Error converting string " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag",
"Error in http connection " + e.toString());
}
return null;
}
}
}
what you can do is to override onPostExecute() in Async Task have a look at this link for How to use AsyncTask correctly in Android
onPostExecute() allow to handle your things on UI Thread.
and here you can access your String (String returnData)
and you can also return value from async-task for that have look at this link How to handle return value from AsyncTask
but i will prefer for you not to that cos i will be a little bit complicated
a piece of code
private class ABC extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//here your code
return returnData;
}
#Override
protected void onPostExecute(String returnedData) {
//
String[] parts = returnedData.split(" ");
ArrayList<String> clientRawData = new ArrayList<String>();
clientRawData.addAll(Arrays.asList(parts));
//Time of last update from weather station.
contentTitle = contentTitle + parts[29] + ":" + parts[30];
Log.e("log_etag", "Content Title " + contentTitle);
// The Intent to be used when the user clicks on the Notification View
notificationIntent = new Intent(context, MainActivity.class);
// The PendingIntent that wraps the underlying Intent
mContentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Build the Notification
Notification.Builder notificationBuilder = new Notification.Builder(
context).setTicker(tickerText)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true).setContentTitle(contentTitle)
.setContentText(contentText).setContentIntent(mContentIntent);
// Get the NotificationManager
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Pass the Notification to the NotificationManager:
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
}
}
}
This is my problem : I want to add some background notification to my application.
So I thought to use alarmanager and a broadcast Receiver in the order to repeat the task.
But how can I start the broadcast in one activity for later on destroy it in a different activity without creating more than 1 broadcast?
Each activity should register a broadcast receiver in each of the activities' onResume method. Don't forget to unregister in onPause.
Here is my code for notification,
public class NotificationService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 30 * 1000; // 30 seconds
long current_times;
String c_time;
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
static HttpClient client = new DefaultHttpClient();
private Timer mTimer = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD) #SuppressLint("NewApi") #Override
public void onCreate() {
// cancel if already existed
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SharedPreferences.Editor editor = getSharedPreferences("notification_oldtime", MODE_PRIVATE).edit();
editor.putInt("old_trail_time", 0);
editor.putInt("old_sample_time", 0);
editor.putInt("old_neworder_time", 0);
editor.commit();
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
public long current_time_get(){
return current_times;
}
class TimeDisplayTimerTask extends TimerTask {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN) #Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
DBAdapter.init(getApplicationContext());
SharedPreferences prefs = getSharedPreferences("notification_oldtime", MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences("notification_oldtime", MODE_PRIVATE).edit();
int sample_order_new_count=0,trail_order_new_count=0,new_order_new_count=0,old_sample_order_count=0,old_trail_order_count=0,old_new_order_count=0;
String search_read_URL=DBAdapter.getUrlName()+"/web/dataset/search_read";
JSONArray sample_jsonarray,trail_jsonarray,new_jsonarray;
JSONObject jsonObj_sample,jsonObj_trail,jsonObj_newOrder;
StringEntity sample_entity,new_order_entity,trail_entity;
String responseBody_sample,responseBody_Trail,responseBody_NewOrder;
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
DBAdapter.init(getApplicationContext());
// notification for sample order
HttpPost sample_get = new HttpPost(search_read_URL);
HttpPost new_order_get = new HttpPost(search_read_URL);
HttpPost trail_get = new HttpPost(search_read_URL);
Log.d("service","start");
sample_entity = new StringEntity(" {\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"sale.sample.order\",\"fields\":[\"partner_id\",\"distributor_id\",\"marketing_person_id\",\"__last_update\"],\"domain\":[],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":"+Integer.valueOf(DBAdapter.getMarketPersonUid())+",\"params\":{\"page\":0,\"limit\":500,\"view_type\":\"list\",\"model\":\"sale.sample.order\",\"menu_id\":378,\"action\":446,\"_push_me\":false},\"bin_size\":true},\"offset\":0,\"limit\":500,\"sort\":\"\"},\"id\":780343122}");
new_order_entity=new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"new.order.log\",\"fields\":[\"name\",\"partner_id\",\"distributor_id\",\"marketing_person_id\",\"__last_update\"],\"domain\":[],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":"+Integer.valueOf(DBAdapter.getMarketPersonUid())+",\"params\":{\"page\":0,\"limit\":500,\"view_type\":\"list\",\"model\":\"new.order.log\",\"menu_id\":355,\"action\":418,\"_push_me\":false},\"bin_size\":true},\"offset\":0,\"limit\":500,\"sort\":\"\"},\"id\":674827326}");
trail_entity=new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"leather.trial.order\",\"fields\":[\"partner_id\",\"distributor_id\",\"marketing_person_id\",\"__last_update\"],\"domain\":[],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":"+Integer.valueOf(DBAdapter.getMarketPersonUid())+",\"params\":{\"page\":0,\"limit\":500,\"view_type\":\"list\",\"model\":\"leather.trial.order\",\"menu_id\":375,\"action\":442,\"_push_me\":false},\"bin_size\":true},\"offset\":0,\"limit\":500,\"sort\":\"\"},\"id\":455581058}");
sample_get.setHeader("Content-Type", "application/json");
sample_get.setHeader("Cookie:","session_id="+DBAdapter.getSessionId());
sample_get.setEntity(sample_entity);
new_order_get.setHeader("Content-Type", "application/json");
new_order_get.setHeader("Cookie:","session_id="+DBAdapter.getSessionId());
new_order_get.setEntity(new_order_entity);
trail_get.setHeader("Content-Type", "application/json");
trail_get.setHeader("Cookie:","session_id="+DBAdapter.getSessionId());
trail_get.setEntity(trail_entity);
responseBody_sample = client.execute(sample_get, responseHandler);
jsonObj_sample = new JSONObject(responseBody_sample);
JSONObject json=jsonObj_sample.getJSONObject("result");
sample_jsonarray = json.getJSONArray("records");
responseBody_Trail=client.execute(trail_get, responseHandler);
jsonObj_trail=new JSONObject(responseBody_Trail);
JSONObject json1=jsonObj_trail.getJSONObject("result");
trail_jsonarray = json1.getJSONArray("records");
responseBody_NewOrder=client.execute(new_order_get,responseHandler);
jsonObj_newOrder=new JSONObject(responseBody_NewOrder);
JSONObject json2=jsonObj_newOrder.getJSONObject("result");
new_jsonarray=json2.getJSONArray("records");
long server_Time = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String new_order_name="",trail_order_name="",sample_order_name="";
for (int m = 0; m <trail_jsonarray.length(); m++) {
JSONObject c = trail_jsonarray.getJSONObject(m);
JSONArray cus_json_array=c.getJSONArray( "partner_id");
JSONArray market_person_json_array=c.getJSONArray( "marketing_person_id");
Date date = format.parse(String.valueOf(c.getString("__last_update")));
server_Time = date.getTime();
DBAdapter.init(getApplicationContext());
long current_time=Long.parseLong(DBAdapter.getCurrentTime());
Log.d("trail ct"+current_time,"st"+server_Time);
if(server_Time>current_time){
trail_order_new_count++;
Log.d("trail_order cus name",cus_json_array.getString(1));
trail_order_name=trail_order_name+" "+"Customer="+cus_json_array.getString(1)+"\n"+"Marketing Person="+market_person_json_array.getString(1);
}
else{
m=trail_jsonarray.length();
}
}
for (int m = 0; m <sample_jsonarray.length(); m++) {
JSONObject c = sample_jsonarray.getJSONObject(m);
JSONArray cus_json_array=c.getJSONArray( "partner_id");
JSONArray market_person_json_array=c.getJSONArray( "marketing_person_id");
Date date = format.parse(String.valueOf(c.getString("__last_update")));
server_Time = date.getTime();
DBAdapter.init(getApplicationContext());
long current_time=Long.parseLong(DBAdapter.getCurrentTime());
Log.d("sample ct"+current_time,"st"+server_Time);
if(server_Time>current_time){
sample_order_new_count++;
Log.d("sample_order cus name",cus_json_array.getString(1));
sample_order_name=sample_order_name+" "+"Customer="+cus_json_array.getString(1)+"\nMarketing Person="+market_person_json_array.getString(1);
}
else{
m=trail_jsonarray.length();
}
}
for (int m = 0; m <new_jsonarray.length(); m++) {
JSONObject c = new_jsonarray.getJSONObject(m);
JSONArray cus_json_array=c.getJSONArray( "partner_id");
JSONArray market_person_json_array=c.getJSONArray( "marketing_person_id");
Date date = format.parse(String.valueOf(c.getString("__last_update")));
server_Time = date.getTime();
DBAdapter.init(getApplicationContext());
long current_time=Long.parseLong(DBAdapter.getCurrentTime());
Log.d("newOrder ct"+current_time,"st"+server_Time);
if(server_Time>current_time){
new_order_new_count++;
Log.d("new_order cus name",cus_json_array.getString(1));
new_order_name=new_order_name+" "+"Customer="+cus_json_array.getString(1)+"\nMarketing Person="+market_person_json_array.getString(1);
}
else{
m=trail_jsonarray.length();
}
}
int newOrder_ID=100,sampleOrder_ID=200,trailOrder_ID=300;
final NotificationManager mgr=
(NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent i2=PendingIntent.getActivity(getApplicationContext(), 1,
new Intent(getApplicationContext(),MainActivity.class),
0);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (new_order_new_count>prefs.getInt("old_neworder_time", 0)) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder .setStyle(new NotificationCompat.BigTextStyle().bigText(new_order_name));
mBuilder.setContentText(new_order_name);
mBuilder.setContentTitle(new_order_new_count+" New Orders");
mBuilder.setSmallIcon(R.drawable.bkg_new_logo);
//mBuilder.setNumber(++numMsg);
mBuilder.setContentIntent(i2);
Log.d(String.valueOf(old_new_order_count),String.valueOf(new_order_new_count));
if(old_new_order_count!=new_order_new_count){
mBuilder.setSound(alarmSound);
}
mgr.notify(newOrder_ID, mBuilder.build());
old_new_order_count=new_order_new_count;
editor.putInt("old_neworder_time", new_order_new_count);
editor.commit();
}
if (sample_order_new_count>prefs.getInt("old_sample_time", 0)) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder .setStyle(new NotificationCompat.BigTextStyle().bigText(sample_order_name));
mBuilder.setContentText(sample_order_name);
mBuilder.setContentTitle(sample_order_new_count+" Sample Orders");
mBuilder.setSmallIcon(R.drawable.bkg_new_logo);
//mBuilder.setNumber(++numMsg);
mBuilder.setContentIntent(i2);
if(old_sample_order_count!=sample_order_new_count){
mBuilder.setSound(alarmSound);
}
mgr.notify(sampleOrder_ID, mBuilder.build());
old_sample_order_count=sample_order_new_count;
editor.putInt("old_sample_time", sample_order_new_count);
editor.commit();
}
if (trail_order_new_count>prefs.getInt("old_trail_time", 0)) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder .setStyle(new NotificationCompat.BigTextStyle().bigText(trail_order_name));
mBuilder.setContentText(trail_order_name);
mBuilder.setContentTitle(trail_order_new_count+" Trail Orders");
mBuilder.setSmallIcon(R.drawable.bkg_new_logo);
//mBuilder.setNumber(++numMsg);
mBuilder.setContentIntent(i2);
if(old_trail_order_count!=trail_order_new_count){
mBuilder.setSound(alarmSound);
}
mgr.notify(trailOrder_ID, mBuilder.build());
old_trail_order_count=trail_order_new_count;
editor.putInt("old_trail_time", trail_order_new_count);
editor.commit();
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
}
You can set the periodic time using NOTIFY_INTERVAL.
In my code I use 30 seconds.
every 30 seconds my service run in background.
I hope this code help you..
I am using a PHP MySQL server model. I want to decode the JSON data that is sent to the server by this code. Any help would be appreciated. The app sends current GPS coordinates to inputed server as JSON array object. I would like to decode it to share with other android users. Thanks a lot. This is the Android code.
public class TrackerService extends Service {
private static final String TAG = "TripTracker/Service";
private final String updatesCache = "updates.cache";
public static TrackerService service;
private NotificationManager nm;
private Notification notification;
private static boolean isRunning = false;
private String freqString;
private int freqSeconds;
private String endpoint;
private final int MAX_RING_SIZE = 15;
private LocationListener locationListener;
private AlarmManager alarmManager;
private PendingIntent pendingAlarm;
private static volatile PowerManager.WakeLock wakeLock;
private AsyncTask httpPoster;
ArrayList<LogMessage> mLogRing = new ArrayList<LogMessage>();
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
ArrayList<List> mUpdates = new ArrayList<List>();
final ReentrantReadWriteLock updateLock = new ReentrantReadWriteLock();
final Messenger mMessenger = new Messenger(new IncomingHandler());
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_LOG = 3;
static final int MSG_LOG_RING = 4;
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
TrackerService.service = this;
endpoint = Prefs.getEndpoint(this);
freqSeconds = 0;
freqString = null;
freqString = Prefs.getUpdateFreq(this);
if (freqString != null && !freqString.equals("")) {
try {
Pattern p = Pattern.compile("(\\d+)(m|h|s)");
Matcher m = p.matcher(freqString);
m.find();
freqSeconds = Integer.parseInt(m.group(1));
if (m.group(2).equals("h"))
freqSeconds *= (60 * 60);
else if (m.group(2).equals("m"))
freqSeconds *= 60;
}
catch (Exception e) {
}
}
if (endpoint == null || endpoint.equals("")) {
logText("invalid endpoint, stopping service");
stopSelf();
}
if (freqSeconds < 1) {
logText("invalid frequency (" + freqSeconds + "), stopping " +
"service");
stopSelf();
}
readCache();
showNotification();
isRunning = true;
/* we're not registered yet, so this will just log to our ring buffer,
* but as soon as the client connects we send the log buffer anyway */
logText("service started, requesting location update every " +
freqString);
/* findAndSendLocation() will callback to this */
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendLocation(location);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
/* we don't need to be exact in our frequency, try to conserve at least
* a little battery */
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, AlarmBroadcast.class);
pendingAlarm = PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), freqSeconds * 1000, pendingAlarm);
}
#Override
public void onDestroy() {
super.onDestroy();
if (httpPoster != null)
httpPoster.cancel(true);
try {
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
catch (Exception e) {
}
/* kill persistent notification */
nm.cancelAll();
if (pendingAlarm != null)
alarmManager.cancel(pendingAlarm);
isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
/* must be done inside of updateLock */
public void cacheUpdates() {
OutputStreamWriter cacheStream = null;
try {
FileOutputStream cacheFile = TrackerService.this.openFileOutput(
updatesCache, Activity.MODE_PRIVATE);
cacheStream = new OutputStreamWriter(cacheFile, "UTF-8");
/* would be nice to just serialize mUpdates but it's not
* serializable. create a json array of json objects, each object
* having each key/value pair of one location update. */
JSONArray ja = new JSONArray();
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
JSONObject jo = new JSONObject();
for (int j = 0; j < pair.size(); j++) {
try {
jo.put(((NameValuePair)pair.get(j)).getName(),
pair.get(j).getValue());
}
catch (JSONException e) {
}
}
ja.put(jo);
}
cacheStream.write(ja.toString());
cacheFile.getFD().sync();
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
}
/* read json cache into mUpdates */
public void readCache() {
updateLock.writeLock().lock();
InputStreamReader cacheStream = null;
try {
FileInputStream cacheFile = TrackerService.this.openFileInput(
updatesCache);
StringBuffer buf = new StringBuffer("");
byte[] bbuf = new byte[1024];
int len;
while ((len = cacheFile.read(bbuf)) != -1)
buf.append(new String(bbuf));
JSONArray ja = new JSONArray(new String(buf));
mUpdates = new ArrayList<List>();
for (int j = 0; j < ja.length(); j++) {
JSONObject jo = ja.getJSONObject(j);
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
Iterator<String> i = jo.keys();
while (i.hasNext()) {
String k = (String)i.next();
String v = jo.getString(k);
nvp.add(new BasicNameValuePair(k, v));
}
mUpdates.add(nvp);
}
if (mUpdates.size() > 0)
logText("read " + mUpdates.size() + " update" +
(mUpdates.size() == 1 ? "" : "s") + " from cache");
}
catch (JSONException e) {
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
updateLock.writeLock().unlock();
}
/* called within wake lock from broadcast receiver, but assert that we have
* it so we can keep it longer when we return (since the location request
* uses a callback) and then free it when we're done running through the
* queue */
public void findAndSendLocation() {
if (wakeLock == null) {
PowerManager pm = (PowerManager)this.getSystemService(
Context.POWER_SERVICE);
/* we don't need the screen on */
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"triptracker");
wakeLock.setReferenceCounted(true);
}
if (!wakeLock.isHeld())
wakeLock.acquire();
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
locationListener, null);
}
public static boolean isRunning() {
return isRunning;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.icon,
"Trip Tracker Started", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker",
"Sending location every " + freqString, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
nm.notify(1, notification);
}
private void updateNotification(String text) {
if (nm != null) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker", text,
contentIntent);
notification.when = System.currentTimeMillis();
nm.notify(1, notification);
}
}
public void logText(String log) {
LogMessage lm = new LogMessage(new Date(), log);
mLogRing.add(lm);
if (mLogRing.size() > MAX_RING_SIZE)
mLogRing.remove(0);
updateNotification(log);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Bundle b = new Bundle();
b.putString("log", log);
Message msg = Message.obtain(null, MSG_LOG);
msg.setData(b);
mClients.get(i).send(msg);
}
catch (RemoteException e) {
/* client is dead, how did this happen */
mClients.remove(i);
}
}
}
/* flatten an array of NameValuePairs into an array of
* locations[0]latitude, locations[1]latitude, etc. */
public List<NameValuePair> getUpdatesAsArray() {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
for (int j = 0; j < pair.size(); j++)
pairs.add(new BasicNameValuePair("locations[" + i + "][" +
((NameValuePair)pair.get(j)).getName() + "]",
pair.get(j).getValue()));
}
return pairs;
}
public int getUpdatesSize() {
return mUpdates.size();
}
public void removeUpdate(int i) {
mUpdates.remove(i);
}
private void sendLocation(Location location) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("time",
String.valueOf(location.getTime())));
pairs.add(new BasicNameValuePair("latitude",
String.valueOf(location.getLatitude())));
pairs.add(new BasicNameValuePair("longitude",
String.valueOf(location.getLongitude())));
pairs.add(new BasicNameValuePair("speed",
String.valueOf(location.getSpeed())));
/* push these pairs onto the queue, and only run the poster if another
* one isn't running already (if it is, it will keep running through
* the queue until it's empty) */
updateLock.writeLock().lock();
mUpdates.add(pairs);
int size = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
logText("location " +
(new DecimalFormat("#.######").format(location.getLatitude())) +
", " +
(new DecimalFormat("#.######").format(location.getLongitude())) +
(size <= 1 ? "" : " (" + size + " queued)"));
if (httpPoster == null ||
httpPoster.getStatus() == AsyncTask.Status.FINISHED)
(httpPoster = new HttpPoster()).execute();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
/* respond with our log ring to show what we've been up to */
try {
Message replyMsg = Message.obtain(null, MSG_LOG_RING);
replyMsg.obj = mLogRing;
msg.replyTo.send(replyMsg);
}
catch (RemoteException e) {
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
/* Void as first arg causes a crash, no idea why
E/AndroidRuntime(17157): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]
*/
class HttpPoster extends AsyncTask<Object, Void, Boolean> {
#Override
protected Boolean doInBackground(Object... o) {
TrackerService service = TrackerService.service;
int retried = 0;
int max_retries = 4;
while (true) {
if (isCancelled())
return false;
boolean failed = false;
updateLock.writeLock().lock();
List<NameValuePair> pairs = service.getUpdatesAsArray();
int pairSize = service.getUpdatesSize();
updateLock.writeLock().unlock();
AndroidHttpClient httpClient =
AndroidHttpClient.newInstance("TripTracker");
try {
HttpPost post = new HttpPost(endpoint);
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse resp = httpClient.execute(post);
int httpStatus = resp.getStatusLine().getStatusCode();
if (httpStatus == 200) {
/* all good, we can remove everything we've sent from
* the queue (but not just clear it, in case another
* one jumped onto the end while we were here) */
updateLock.writeLock().lock();
for (int i = pairSize - 1; i >= 0; i--)
service.removeUpdate(i);
updateLock.writeLock().unlock();
}
else {
logText("POST failed to " + endpoint + ": got " +
httpStatus + " status");
failed = true;
}
}
catch (Exception e) {
logText("POST failed to " + endpoint + ": " + e);
Log.w(TAG, e);
failed = true;
}
finally {
if (httpClient != null)
httpClient.close();
}
if (failed) {
/* if our initial request failed, snooze for a bit and try
* again, the server might not be reachable */
SystemClock.sleep(15 * 1000);
if (++retried > max_retries) {
/* give up since we're holding the wake lock open for
* too long. we'll get it next time, champ. */
logText("too many failures, retrying later (queue " +
"size " + service.getUpdatesSize() + ")");
break;
}
}
else
retried = 0;
int q = 0;
updateLock.writeLock().lock();
q = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
if (q == 0)
break;
/* otherwise, run through the rest of the queue */
}
return false;
}
protected void onPostExecute(Boolean b) {
if (wakeLock != null && wakeLock.isHeld())
wakeLock.release();
}
}
}
You can decode the data using json_decode()
<?php
$json = ""; // JSON data
$json_obj = json_decode($json); // As Object
$json_arr = json_decide($json,true) // As Array
var_dump($json_obj);
print_r($json_arr);
// Store Array to database using serialize function
$data = serialize($json_array); // Array will be converted into string
?>