How Properly run a background service? - java

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..

Related

Insert Event to Calendar With Async Task

I have below code which is working fine to insert event in calendar. It is class extended to activity so when this is called , a blank activity is opened. I want to perform this through Async Task.
Activity Class:
private static final Level LOGGING_LEVEL = Level.OFF;
private static final String PREF_ACCOUNT_NAME = "accountName";
static final String TAG = "CalendarAuth";
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
private final static int ADD_OR_EDIT_CALENDAR_REQUEST = 3;
com.google.api.services.calendar.Calendar service;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
GoogleAccountCredential credential;
Event event;
CalendarModel model = new CalendarModel();
String title, description;
com.google.api.services.calendar.Calendar client;
int numAsyncTasks;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smspayremin);
reset = (Button) findViewById(R.id.rest);
final SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
final SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
// Initialize credentials and service object.
credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CalendarScopes.CALENDAR));
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// Calendar client
client = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential).setApplicationName("Google-CalendarAndroidSample/1.0")
.build();
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putBoolean(getString(R.string.smartrem), true).apply();
}
});
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.containsKey("remtitle")) {
title = bundle.getString("remtitle");
description = bundle.getString("remdesc");
button.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
haveGooglePlayServices();
} else {
checkGooglePlayServicesAvailable();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
// AsyncLoadCalendars.run(this);
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
// AsyncLoadCalendars.run(this);
}
}
break;
}
}
public void createEvent(GoogleAccountCredential mCredential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
service = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, mCredential)
.setApplicationName("Created By Mini4Me")
.build();
event = new Event()
.setSummary(title)
/*.setLocation("Dhaka")*/
.setDescription(description);
TimeZone timeZone = TimeZone.getDefault();
DateTime startDateTime = new DateTime(new Date());
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone(timeZone.getID());
event.setStart(start);
DateTime endDateTime = new DateTime(addDays(new Date(), 10));
Log.e("start D ", startDateTime + "End Date " + endDateTime + timeZone.getID());
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime).setTimeZone(timeZone.getID());
event.setEnd(end);
String[] recurrence = new String[]{"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));
/* EventAttendee[] attendees = new EventAttendee[]{
new EventAttendee().setEmail("abir#aksdj.com"),
new EventAttendee().setEmail("asdasd#andlk.com"),
};
event.setAttendees(Arrays.asList(attendees));*/
EventReminder[] reminderOverrides = new EventReminder[]{
//new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
final String calendarId = "primary";
new Thread(new Runnable() {
#Override
public void run() {
try {
event = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());
if (title != null) {
title = null;
finish();
finish();
//System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static Date addDays(Date date, int days) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(java.util.Calendar.DATE, days);
return cal.getTime();
}
public boolean checkGooglePlayServicesAvailable() {
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
}
return true;
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
runOnUiThread(new Runnable() {
public void run() {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
connectionStatusCode, SMSDataFetch.this, REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
public void haveGooglePlayServices() {
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
// ask user to choose account
chooseAccount();
} else {
if (title != null && description != null) {
createEvent(credential);
}
}
}
private void chooseAccount() {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
editor.putBoolean(getString(R.string.smartrem), true).apply();
button.setText("Disable Smart Reminder");
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
#Override
protected void onResume() {
super.onResume();
if (checkGooglePlayServicesAvailable()) {
haveGooglePlayServices();
}
}
}
TO insert event I made below AsyncTask class but it is not working and giving me NPE at various points like credential, event.
public class BGTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "BGTask";
Event event;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
private com.google.api.services.calendar.Calendar mService = null;
private String title, message;
private Context context;
GoogleAccountCredential credential;
com.google.api.services.calendar.Calendar client;
public BGTask(Context context, String title, String message) {
this.title = title;
this.message = message;
this.context = context;
}
#Override
protected void onPreExecute() {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(CalendarScopes.CALENDAR));
credential.setSelectedAccountName(settings.getString("accountName", null));
credential.setSelectedAccountName("ankurjain30#gmail.com");
// Calendar client
client = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential).setApplicationName("Google-CalendarAndroidSample/1.0")
.build();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
if (checkGooglePlayServicesAvailable()) {
haveGooglePlayServices();
}
return null;
}
public boolean checkGooglePlayServicesAvailable() {
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
return false;
}
return true;
}
private void haveGooglePlayServices() {
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
// ask user to choose account
} else {
cre();
}
}
public void cre() {
event = new Event()
.setSummary(title)
/*.setLocation("Dhaka")*/
.setDescription(message);
TimeZone timeZone = TimeZone.getDefault();
DateTime startDateTime = new DateTime(new Date());
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone(timeZone.getID());
event.setStart(start);
DateTime endDateTime = new DateTime(new Date());
Log.e("start D ", startDateTime + "End Date " + endDateTime + timeZone.getID());
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime).setTimeZone(timeZone.getID());
event.setEnd(end);
String[] recurrence = new String[]{"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));
/* EventAttendee[] attendees = new EventAttendee[]{
new EventAttendee().setEmail("abir#aksdj.com"),
new EventAttendee().setEmail("asdasd#andlk.com"),
};
event.setAttendees(Arrays.asList(attendees));*/
EventReminder[] reminderOverrides = new EventReminder[]{
//new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
final String calendarId = "primary";
try {
event = mService.events().insert(calendarId, event).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can some one help me in fixing it.

Display notifications over activity when app is starting

At this moment i use push notifications in my app. when i start my app they go into the notification drawer like this
1
but i need them to be over the main activity. i cant find the solution anywhere... Which type of notifications can i use ?(without losing the functionality) and how to dublicate the info from push notifications into that type? also is there a way to display push notifications on the whole screen ? fullscreen ? thats what i want: 2
Can someone give me a solution and its code as an example?
my code:
private static int sNotificationId = 1;
public static int showsId = -1;
...
Utils.GetAuthToken(this);
Bundle intent_extras = getIntent().getExtras();
showsId = -1;
if (intent_extras != null && intent_extras.containsKey("com.example.romanchuk.appisode.show_id")) {
if (intent_extras.containsKey("com.example.romanchuk.appisode.notifyId")) {
int notification_id = intent_extras.getInt("com.example.romanchuk.appisode.notifyId", -1);
new ReadNotification(notification_id).execute();
}
showsId = intent_extras.getInt("com.example.romanchuk.appisode.show_id", -1);
} else {
try {
ArrayList<NotificationItem> list = new LoadNotifications().execute().get();
for (int jIndex = 0; jIndex < list.size(); jIndex++) {
new sendNotification(this, list.get(jIndex).getId(),
list.get(jIndex).getShow_id(),
list.get(jIndex).getMessage(),
"Appisode",
list.get(jIndex).getImage()).execute();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
...
private void handleDataMessage(int id, String title, String message) {
try {
String imageUrl = "";
Log.e(TAG, "title: " + title);
Log.e(TAG, "message: " + message);
Log.e(TAG, "imageUrl: " + imageUrl);
if (!true) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.putExtra("com.example.romanchuk.appisode.notifyId", id);
resultIntent.putExtra("message", message);
NotificationUtils notificationUtils = new NotificationUtils(this);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, resultIntent);
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
private class sendNotification extends AsyncTask<String, Void, Bitmap> {
Context ctx;
int id, show_id;
String message;
String title;
String icon;
public sendNotification(Context context, int id, int show_id, String message, String title, String icon) {
super();
this.ctx = context;
this.id = id;
this.show_id = show_id;
this.message = message;
this.title = title;
this.icon = icon;
}
...
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
Intent intent = new Intent(ctx, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("com.example.romanchuk.appisode.notifyId", id);
intent.putExtra("com.example.romanchuk.appisode.show_id", show_id);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, sNotificationId , intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(message);
bigText.setBigContentTitle(getString(R.string.app_name));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
Notification notification = null;
notification = builder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.color_accent))
.setContentTitle("Appisode")
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(inboxStyle)
.setSmallIcon(R.drawable.small_icon)
.setWhen(System.currentTimeMillis())
.setSound(defaultSoundUri).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(sNotificationId++, notification);
}
}

I need to update list adapter in background auto refresh listview and notify user if there new data from database

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

Android Notification Service from JSON

How do I make a notification service, that will notify user about some new news storeis?
I get news from a JSON API (https://newsapi.org/) to my app, and want show user notification if he there are any new stories he hasn't seen.
yes it is easy to create Push notifications in android using FireBase services.Follow my steps here:
https://firebase.google.com/docs/notifications/android/console-audience go here create your first project in firebase console. you will get a file downloaded and paste it in your app module and perform instructions provided by the site
create these files in your project.copy and paste 1.https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseInstanceIDService.java 2.https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java
add necessary permissions and gradle plugins.call this String token = FirebaseInstanceId.getInstance().getToken(); in Activity class.
To test this by giving required parameters in this site: http://apns-gcm.bryantan.info/
Look at my code
Thats beta..
`public class Notification extends Service {
String datanews;
String titlenotif;
String destnotif;
MyAsynk asynk;
#Override
public void onCreate() {
super.onCreate();
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 0, 1800000); //тикаем каждые 30 мinute без задержки 1800000
}
//задача для таймера
//Проверяем на новую запись.
class UpdateTimeTask extends TimerTask {
public void run() {
asynk = new MyAsynk();
asynk.execute();
createNotification(getApplicationContext());//пушим уведомление
}
}
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
#Override
//работа в бекграунде
protected StringBuilder doInBackground(Void... voids) {
StringBuilder stringBuilder = new StringBuilder();
String key = "YOUR_KEY";
try {
URL url = new URL("YOUR_URL_HERE" + key);
URLConnection uc = url.openConnection();
uc.connect();
BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
int ch;
while ((ch = in.read()) != -1) {
stringBuilder.append((char) ch);
}
} catch (Exception e) {
}
return stringBuilder;
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String newsdata = object.getString("publishedAt");
datanews = newsdata;
titlenotif = title;
destnotif = desc;
}
}
catch (Exception e){
}
}
}
private void createNotification(Context context) {
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncBuilder = new NotificationCompat.Builder(context);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
ncBuilder.setVibrate(new long[]{500});
ncBuilder.setLights(Color.WHITE, 3000, 3000);
ncBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
ncBuilder.setContentIntent(pIntent);
ncBuilder.setContentTitle(titlenotif + "");
ncBuilder.setContentText(destnotif + "");
ncBuilder.setTicker("You have news!");
ncBuilder.setSmallIcon(R.drawable.news_icon);
ncBuilder.setAutoCancel(true);
manager.notify((int)System.currentTimeMillis(),ncBuilder.build());
}
public IBinder onBind(Intent arg0) {
return null;
}
}`

How to Use AlarmManager in android?

I want to implement a schedule function in my android project. So I Googled for an Alarm manager program but I can`t Resolve Problem.
I want set alarm with custom time that users Determine. I wrote 2 class for service and BroadcastReciver. But alarm is inccorect for example i set 2 min for alarm.but app Arbitrary is work .eg 2 min or 3 or 5 or 1min....
mainActivity:
SharedPreferences preferences1 = getSharedPreferences("min", 0);
String min1 = preferences1.getString("minute", "");
if (min1.length() <= 0) {
s = 120000;
} else {
s = Long.parseLong(min1);
s = s * 60000;
}
t = new Timer();
// Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Called each time when 1000 milliseconds (1 second)
// (the period parameter)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(CategoryListActivity.this,
Service_class.class);
PendingIntent pintent = PendingIntent.getService(
CategoryListActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), s, pintent);
Log.e("Timer", t.toString());
}
},
// Set how long before to start calling the TimerTask (in
// milliseconds)
0,
// Set the amount of time between each execution (in
// milliseconds)
s);
service_class.java :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
dbflash = new DatabaseFlashCard(getApplicationContext());
db = dbflash.getReadableDatabase();
SharedPreferences preferences_notify = getSharedPreferences("notify", 0);
Calendar c = Calendar.getInstance();
String time_one = preferences_notify.getString("time_first", "");
String time_two = preferences_notify.getString("time_second", "");
int hour = c.get(Calendar.HOUR_OF_DAY);
if (time_one.length() <= 0) {
time_one = "21";
}
if (time_two.length() <= 0) {
time_two = "5";
}
int timeFirst = Integer.parseInt(time_one);
int timeSecond = Integer.parseInt(time_two);
if (hour < timeFirst && hour > timeSecond) {
// nothing
} else {
// notify and alert
preferences_language = getSharedPreferences("language_sql", 0);
editor_language = preferences_language.edit();
String language = preferences_language.getString("language", "");
String sql="SELECT * FROM " + dbflash.TABLE
+ " where hide='0' ORDER BY RANDOM() LIMIT 1";
if(language.length()>0)
{
if(language.equalsIgnoreCase("0"))
{
sql="SELECT * FROM " + dbflash.TABLE
+ " where hide='0' ORDER BY RANDOM() LIMIT 1";
}
else
{
sql="SELECT * FROM " + dbflash.TABLE
+ " where ids="+language+" and hide='0' ORDER BY RANDOM() LIMIT 1";
}
Cursor cursors = db.rawQuery(sql, null);
for (int i = 0; i < cursors.getCount(); i++) {
cursors.moveToNext();
ID = cursors.getString(cursors.getColumnIndex("ID"));
farsi = cursors.getString(cursors.getColumnIndex("farsi"));
english = cursors.getString(cursors.getColumnIndex("english"));
question = cursors
.getString(cursors.getColumnIndex("question"));
count = cursors.getString(cursors.getColumnIndex("count"));
}
preferences_status = getSharedPreferences("notify_status", 0);
String status = preferences_status.getString("status", "");
SharedPreferences.Editor editor_status;
editor_status = preferences_status.edit();
if (status.length() <= 0) {
status="1";
editor_status.putString("status", "1");
editor_status.commit();
Log.e("Notification Status ", "Enable Now..for First");
} else if(status.equalsIgnoreCase("0")) {
Log.e("Notification Status ", "disable");
}
else
{
Log.e("Notification Status ", "enable");
if (english==null || english=="") {
} else {
SharedPreferences preferences = getSharedPreferences("music", 0);
String address=preferences.getString("address", "");
if(address.length()<=0)
{
mp = MediaPlayer.create(getApplicationContext(), R.raw.ring);
mp.start();
}
else
{
mp = MediaPlayer.create(getApplicationContext(),Uri.parse(address));
mp.start();
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent contentIntent = new Intent(this,
QuestionActivity.class);
contentIntent.putExtra("ID", ID);
contentIntent.putExtra("english", english);
contentIntent.putExtra("farsi", farsi);
contentIntent.putExtra("count", count);
contentIntent.putExtra("question", question);
Notification notification = new Notification(
R.drawable.icon, "یاد آوری",
System.currentTimeMillis());
notification.setLatestEventInfo(this, english, "",
PendingIntent.getActivity(this.getBaseContext(), 0,
contentIntent,
PendingIntent.FLAG_CANCEL_CURRENT));
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(SIMPLE_NOTFICATION_ID,
notification);
}
}
}
}
return START_STICKY;
}
and Myreceiver
public class Myreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent serviceLauncher = new Intent(context, Service_class.class);
context.startService(serviceLauncher);
}
Android Manifest :
<service android:name=".Service_class" />
<receiver
android:name="com.pttat.flashcard.services.Myreceiver"
android:process=":remote" />
how to change my code for Resolve my Problem?
Do I need to change calling alarm manager in Oncreate?
thanks

Categories

Resources