I have app, in which i am refreshing that app in particular amount of time.
Each time the call is given to webservice and all the messages in database are loaded to listview.
Its done as follows:
public class Messages extends Activity {
protected Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String id = intent.getStringExtra(MainActivity.EXTRA_ID);
String[] lst = null;
ListView lm=(ListView)findViewById(R.id.listView1);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome " + message);
handler.postDelayed(new UpdateTask(),750);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.messages, menu);
return true;
}
class UpdateTask implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
setContentView(R.layout.activity_messages);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String id = intent.getStringExtra(MainActivity.EXTRA_ID);
String[] lst = null;
ListView lm=(ListView)findViewById(R.id.listView1);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome " + message);
CallSoap cs=new CallSoap();
lst=cs.GetMessage(id);
ArrayAdapter<String> adpt = new ArrayAdapter<String>(Messages.this, android.R.layout.simple_list_item_1,lst);
lm.setAdapter(adpt);
handler.postDelayed(this, 500);
}
}
}
Now, i am just unable to detect (highlight) new messages in my app, because each time when call is given to webservice it retrieves all messages.
How should i detect that this is new message(or can say as data in listview ) for this particular interval of time.
Please help me.
Add one field(i.e. Status) in database. And when you call your service and its return all message from database then status need to change with 1 (0 means still webservice not fetch, 1 means its fetch at android side). So after new records inserted your service only fetch the records which status have 0.
I hope this will help you.
Related
I'm trying to implement a notification function into my app, which will set a notification to a specific, user entered, date. I tried to implement the method of this site: http://blog.blundell-apps.com/notification-for-a-user-chosen-time/, only it does not work! I tried to understand the problem, but I just can't figure out how I can fix this. It seems something goes wrong in the ScheduleClient class, since LogCat tells me that the service binds when the ProductsAdd class is opened, but when it tries to set an alarm if I click the save button, a Nullpointerexception is given at line 62 of ClientService (mBoundService.setAlarm(c);). So the service is bound but won't connect. Can someone please tell me what I'm doing wrong here?
ProductsAdd class:
public class ProductsAdd extends Activity implements OnClickListener{
Button bSave, bDelete, bCancel;
EditText etName, etAmount , etDate;
Spinner sUnit;
Time today = new Time(Time.getCurrentTimezone());
// This is a handle so that we can call methods on our service
private ScheduleClient scheduleClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setContentView(R.layout.products_add);
Log.d("WTF", "ProductsAdd.java opened");
initiate();
// Create a new service client and bind our activity to this service
scheduleClient = new ScheduleClient(this);
scheduleClient.doBindService();
// Create an ArrayAdapter using the string array and default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.units_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);;
// Apply the adapter to the spinner
sUnit.setAdapter(adapter);
// Set product name which is passed from an activity
Intent getProductFeatures = getIntent();
String productName = getProductFeatures.getStringExtra("productName");
String productUnit = getProductFeatures.getStringExtra("productUnit");
etName.setText(productName);
//Set spinner to right value:
int spinnerPosition = adapter.getPosition(productUnit);
sUnit.setSelection(spinnerPosition);
today.setToNow();
String timestamp = today.format("%d-%m-%Y");
etDate.setText(timestamp);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bSave:
Log.d("WTF", "ProductsAdd: Save button pressed");
try{
//Get info from edittexts
String name = etName.getText().toString();
String amount = etAmount.getText().toString();
String unit = sUnit.getSelectedItem().toString();
String date = etDate.getText().toString();
Log.d("WTF", "Extracted unit from ProductsAdd is: " + unit);
//Set date alarm
//Get day, month and year in separate integers
String sDay = date.substring(0, 2);
String sMonth = date.substring(3, 5);
String sYear = date.substring(6, 10);
int month = Integer.parseInt(sMonth);
int day = Integer.parseInt(sDay);
int year = Integer.parseInt(sYear);
//Create new calendar to set date chosen
Calendar c = Calendar.getInstance();
c.set(day,month,year);
//Set time to midnight
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND, 0);
//Ask service to set alarm for date
scheduleClient.setAlarmForNotification(c);
//Notify user of alarm
Toast.makeText(this, "Notification set for: "+ day +"-"+ (month+1), 5);
//Create new database entry
DatabaseCustom entry = new DatabaseCustom(ProductsAdd.this);
entry.open();
entry.createEntry(name, amount, unit, date);
entry.close();
Log.d("WTF", "ProductsAdd: Save product in database successfull");
} catch(Exception e){
e.printStackTrace();
Log.d("WTF", "ProductsAdd error: Failed to save product in database: " + e);
}
//Go to product list
Intent sOpenProducts = new Intent(ProductsAdd.this,
Products.class);
startActivity(sOpenProducts);
finish();
break;
case R.id.bCancel:
Log.d("WTF", "ProductsAdd: Cancel button pressed");
Intent cOpenProducts = new Intent(ProductsAdd.this,
Products.class);
startActivity(cOpenProducts);
finish();
break;
}
}
private void initiate(){
//Link java variables to the corresponding xml elements
bSave = (Button)findViewById(R.id.bSave);
bCancel = (Button)findViewById(R.id.bCancel);
etName = (EditText)findViewById(R.id.etName);
etAmount = (EditText)findViewById(R.id.etAmount);
etDate = (EditText)findViewById(R.id.etDate);
sUnit = (Spinner)findViewById(R.id.sUnit);
//Set button OnClickListeners
bSave.setOnClickListener(this);
bCancel.setOnClickListener(this);
}
}
ScheduleClient class:
public class ScheduleClient {
// The hook into our service
private ScheduleService mBoundService;
// The context to start the service in
private Context mContext;
// A flag if we are connected to the service or not
private boolean mIsBound;
public ScheduleClient(Context context) {
mContext = context;
}
/**
* Call this to connect your activity to your service
*/
public void doBindService() {
Log.d("WTF", "ScheduleClient: service bound");
// Establish a connection with our service
mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
/**
* When you attempt to connect to the service, this connection will be called with the result.
* If we have successfully connected we instantiate our service object so that we can call methods on it.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
Log.d("WTF", "ScheduleClient: service connected");
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
Log.d("WTF", "ScheduleClient: service disconnected");
}
};
/**
* Tell our service to set an alarm for the given date
* #param c a date to set the notification for
*/
public void setAlarmForNotification(Calendar c){
mBoundService.setAlarm(c);
Log.d("WTF", "ScheduleClient: alarm set");
}
/**
* When you have finished with the service call this method to stop it
* releasing your connection and resources
*/
public void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
mContext.unbindService(mConnection);
mIsBound = false;
Log.d("WTF", "ScheduleClient: service unbound");
}
}
}
I can add the ScheduleService, AlarmTask en NotifyService which are used by the ScheduleClient class if needed!
Ok, I have no Idea how to do this, I need some help.
I need to send a Ping in JSON format into a server, I've already have it with all the information that I need... timestamp, location, device_id, etc... But.. how can I send it each 5 minutes automatically ?? I'm still looking for something useful but I have no succes.. I'm kind of new on this..
here's an example of my code, feel free to use it if it is useful for you :) ...
package com.example.hugo.ping03;
// imports....
public class MainActivity extends ActionBarActivity {
//HTTP
private AsyncHttpClient client;//crear cliente
private AsyncHttpResponseHandler handler;//crear handler
private Button send;
//JSON
JSONObject json; //objeto json
Context context = this; //context element
private StringEntity entity; //entity
//Battery
private IntentFilter batIntentFilter;
private Intent battery;
private int nivelBateria;
//device_id
private String id;
//timestamp
private int time;
private Timestamp tsTemp;
private Long tsLong;
private String ts;
//GPS (this one comes from another class.java)
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping03);
client = new AsyncHttpClient();
String password = "pass";
client.setBasicAuth("hugo", password);
send = (Button) findViewById(R.id.send);
//battery level:
batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
battery = this.registerReceiver(null, batIntentFilter);
nivelBateria = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
//device_id:
id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
//timestamp
time = (int) (System.currentTimeMillis());
tsTemp = new Timestamp(time);
tsLong = System.currentTimeMillis()/1000;
ts = tsLong.toString();
handler = new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
Log.d("onSuccess","ping exitoso !!!!");
Log.d("Nivel de Bateria:",String.valueOf(nivelBateria));
Log.d("Id de Dispositivo",id);
Log.d("Timesatmp:",ts);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
String statuscode = String.valueOf(statusCode);
Log.d("onFailure","ping nulo a causa de: ");
Log.d("Server statusCode",statuscode);
}
};
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mensaje a Log para indicar clic en botón
Log.d("onPressButton","Click exitoso");
String klientourl = "server url";
//Strings to Post JSON :
String status = "1";
String device_id = id;
String timestamp =ts;
String battery = String.valueOf(nivelBateria);
json = new JSONObject();
gps = new GPSTracker(Ping03.this);//creamos objeto de clase
//if GPS is Enabled...
if (gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.d("Location is:", "Lat: "+latitude+" Long: "+longitude);
String IamHere = "Lat: "+latitude+" Long: "+longitude;
try {
json.put("geo", IamHere);
json.put("status", status);
json.put("device_id", device_id);
json.put("timeStamp", timestamp);
json.put("battery", battery);
}catch (JSONException e){
Log.e("Json", "unexpected JSON exception", e);
}
try {
entity = new StringEntity(json.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(context, klientourl, entity, "application/json", handler);
}catch (Exception e){}
}else {
//if we can
gps.showSettingsAlert();
Log.d("Geoloc: ", "Disabled?");
}
}// ./ end onClick
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_ping03, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
Any ideas? thanks a lot!
If you want to perform some periodically repeating tasks, I'd suggest you make use of a AlarmManager component of the Android SDK.Alarm manager is a system service, thus you can access it by using the following line of code.
AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().
You will then receive the alarm in an AlarmReceiver.
AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone.
Here is an article from Android Developers that describes how to use AlarmManager and AlarmReceiver : http://developer.android.com/training/scheduling/alarms.html. After you are successful of setting an alarm with AlarmManager (for every 5 minutes) and intercepting it in your AlarmReceiver, you can start an IntentService that will send the ping json to your server.
I hope this helps. Cheers!
If you want to hit you server from android app after a fix time you should create a background service.and this service class will call server on a specific delay frequently.
public class MyService extends Service{
Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0){
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate(){
Log.e(TAG, "onCreate");
mHandler.postDelayed(mRun,300000);
}
Runnable mRun = new Runnable() {
#Override
public void run() {
// TODO call your service here
mHandler.postDelayed(mRun,300000);
}
};
}
start service from your activity like below -
private void startService(){
Handler mStartServicehandler = new Handler();
mStartServicehandler.post(new Runnable() {
#Override
public void run() {
startService(new Intent(mContext,MyService.class));
}
});
}
do something like this.
It will ping your server after every 5 min.
I have also posted in android Enthusiasts, not sure if its the correct place..
We have created an app to scan for wifi hotspots / AP so we can read the SSID and RSSI. We have some test phones with hotspot turned on and hard coded the SSID into the app. When the APP launches for the first time all works OK, we click the AP (checkbox) and hit start (button).When we close the app and launch it again, as soon as we click the AP (checkbox) it start scanning even though we haven't click the start button. we need to reinstall the app on the phone every time. Can anyone help us with this BUG/ unwanted feature as its slowing us up.
here is the code for the main Activity.
your help is greatly appreciated.
public class RssiMyActivity extends Activity{
// Declare global variables
private WifiManager mainWifiObj;
private WifiScanReceiver wifiReciever;
private ListView list;
private ArrayAdapter<String> adapter;
private List<String> ap_details = new ArrayList<String>();
private static String ssid;
private int testCount;
private CheckBox a1, a2, a3, a4, a5, a6;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssi_my);
list = (ListView) findViewById(R.id.listView1);
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
// Get make a connection to database to get test count
ReceiveFromDB receiver = new ReceiveFromDB();
receiver.execute();
// Update the test count
testCount = ReceiveFromDB.getCount();
testCount += 1;
// Check to see what value testCount is
Log.e("Values for testCount", String.valueOf(testCount));
Button start;
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Timer added to get new scan result once every 2 seconds
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 0, 4000);
}
});
Button pause;
pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onPause();
}
});
Button resume;
resume = (Button) findViewById(R.id.resume);
resume.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onResume();
}
});
a1 = (CheckBox) findViewById(R.id.AP1);
a2 = (CheckBox) findViewById(R.id.AP2);
a3 = (CheckBox) findViewById(R.id.AP3);
a4 = (CheckBox) findViewById(R.id.AP4);
a5 = (CheckBox) findViewById(R.id.AP5);
a6 = (CheckBox) findViewById(R.id.AP6);
}
protected void onPause()
{
unregisterReceiver(wifiReciever);
super.onPause();
}
protected void onResume()
{
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
// Timer method to run at the same time as the main activity
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
/*
* Runnable method add code to here to refresh at specified time
*/
private Runnable Timer_Tick = new Runnable()
{
#Override
public void run()
{
try
{
// start a scan of ap's
mainWifiObj.startScan();
}
catch (Exception e)
{
e.getStackTrace();
}
}
};
class WifiScanReceiver extends BroadcastReceiver
{
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent)
{
// Clear details to refresh the screen for each new scan
if (ap_details.size() > 0)
{
try
{
ap_details.clear();
adapter.clear();
adapter.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
try
{
// Get all Objects from the scan
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
List<ScanResult> temp = new ArrayList<ScanResult>();
// Run through each signal and retrieve the mac ssid rssi
for (ScanResult aWifiScanList : wifiScanList)
{
StringBuilder sb = new StringBuilder();
// Pull out the info we need
ssid = aWifiScanList.SSID;
// Check which ap's are selected
if (checkDisplay())
{
// Add info to StringBuilder
sb.append(aWifiScanList.SSID).append("\n");
sb.append(String.valueOf(aWifiScanList.level)).append("\n");
sb.append("Test: ").append(String.valueOf(testCount)).append("\n");
// Add to List that will be displayed to user
ap_details.add(sb.toString());
// Also add to a temporary ScanResult List to use later
temp.add(aWifiScanList);
}
}
// Create an String Array twice the size of the temporary
// ScanResult
// this will be the Array to use as the parameters for sending
// to the database
String[] items = new String[temp.size() + temp.size() + 1];
int num1 = 0;
int num2 = 1;
// Add the ssid and rssi of each object to the Array
for (ScanResult aTemp : temp)
{
items[num1] = aTemp.SSID;
items[num2] = String.valueOf(aTemp.level);
num1 += 2;
num2 += 2;
}
// Add the test value
items[num1] = String.valueOf(testCount);
// Pass Array to the Async method use executeOnExecutor this
// allows for the use
// of the Looper.prepare() method to stop app from crashing
new ConnectToDB().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, items);
// Display the list of all the signals on the device
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, ap_details);
list.setAdapter(adapter);
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
/*
* Method to check which AP's are been used
*/
public boolean checkDisplay()
{
if (a1.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone1"))
{
return true;
}
}
if (a2.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone2"))
{
return true;
}
}
if (a3.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone3"))
{
return true;
}
}
if (a4.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone4"))
{
return true;
}
}
if (a5.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone5"))
{
return true;
}
}
if (a6.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone6"))
{
return true;
}
}
return false;
}
You never call cancel() on your timer task to remove it from the Timer scheduler. Try inserting that in a button you use to stop it from scanning.
If that doesn't work, try calling cancel() on the timer itself.
ok got it working, not sure if its the right way but its working ok. I just unregister the reciecer and register it again by calling the two methods "onPause() and onResume()" one after the other and just before the startScan() method. see code:
private Runnable Timer_Tick = new Runnable()
{
#Override
public void run()
{
try
{
// unRegister Receiver wifiReciever
onPause();
// register Receiver wifiReciever
onResume();
// start a scan of ap's
mainWifiObj.startScan();
}
catch (Exception e)
{
e.getStackTrace();
}
}
};
would love to know if this is correct way to do it.
I have an app which has a main activity and two fragments running on top of it, One of the fragment is related to Google Cloud Notification registration and receiving of push notifications from gcm . Now the issue is the first time user launches the app and clicks on the notification fragment then only the process of registration with gcm starts and then he starts receiving the notifications . But I want to automatically start the registration process from the main acitvity without the wating for switching to notification fragment . How do I achieve this? I tried to make a new function in notification fragment and put all code regarding gcm registration into that function and then I tried calling that function from MainActivity but it gets the null pointer exception .. Please take a look at my code
public class NotificationFragment extends Fragment {
TextView lblMessage;
private AppPreferences _appPrefs;
public AsyncTask<Void, Void, Void> mRegisterTask;
AlertDialogManager alert = new AlertDialogManager();
ConnectionDetector cd;
public static String name;
public static String email;
public View rootView;
public NotificationFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.gcm_activity_main, container, false);
return rootView;
}
#Override
public void onStart (){
super.onStart();
autoRegistrationForNotification();
}
public void autoRegistrationForNotification()
{
_appPrefs = new AppPreferences(rootView.getContext());
_appPrefs.setToZero();
cd = new ConnectionDetector(getActivity().getApplicationContext());
name = " ";
email = " ";
// Make sure the device has the proper dependencies.
//if(cd.isConnectingToInternet())
try{
GCMRegistrar.checkDevice(getActivity().getApplicationContext());
}catch(Exception e){}
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
//if(cd.isConnectingToInternet())
try{
GCMRegistrar.checkManifest(getActivity().getApplicationContext());
}catch(Exception e){}
lblMessage = (TextView) rootView.findViewById(R.id.lblMessage);
lblMessage.setText(_appPrefs.getMessageFromArchive());
getActivity().getApplicationContext().registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
//if(cd.isConnectingToInternet()){
final String regId = GCMRegistrar.getRegistrationId(getActivity().getApplicationContext());
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
// if(cd.isConnectingToInternet())
try{
GCMRegistrar.register(getActivity().getApplicationContext(), SENDER_ID);}
catch(Exception e){}
} else {
// Device is already registered on GCM
//if(cd.isConnectingToInternet())
if (GCMRegistrar.isRegisteredOnServer(getActivity().getApplicationContext())) {
// Skips registration.
// Toast.makeText(getActivity().getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = getActivity().getApplicationContext();
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
// if(cd.isConnectingToInternet())
try{
ServerUtilities.register(context, name, email, regId);}
catch(Exception e){}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
try{
// if(cd.isConnectingToInternet())
try{
mRegisterTask.execute(null, null, null);}catch(Exception e){}
}catch(Exception e){}
}
}//else ends
}
/**
* Receiving push messages
* */
public final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// _appPrefs = new AppPreferences(getActivity());
_appPrefs = new AppPreferences(rootView.getContext());
String newMessage = "";
try{
_appPrefs.incrementNotificationCount();
newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
}catch(Exception e)
{
}
try{
WakeLocker.acquire(getActivity().getApplicationContext());
}catch(Exception e)
{
}
if(_appPrefs.getMessageFromArchive().length() > 800){
_appPrefs.saveMessageToArchive(" ");
}
Time now = new Time();
now.setToNow();
int month = now.month;
int day = now.monthDay;
int year = now.year;
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
//lblMessage.append("\n"+String.valueOf(day)+" " +months[month - 1] + " "+String.valueOf(year)+"\n"+newMessage.toString());
try{
if(newMessage!=null)
{
_appPrefs.saveMessageToArchive(_appPrefs.getMessageFromArchive().toString()+"\n _____________________ \n"+String.valueOf(day)+" " +months[month - 1] + " "+String.valueOf(year)+"\n"+newMessage.toString());
lblMessage.setText(_appPrefs.getMessageFromArchive());
}else{}
}
catch(Exception e){}
Toast.makeText(getActivity().getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
try{
// Releasing wake lock
WakeLocker.release();}catch(Exception e){}
}
};
}
But I want to automatically start the registration process from the main acitvity without the wating for switching to notification fragment
If you wish to register to GCM from the main activity, even before the fragment is created, you should move the registration code to onCreate method of the activity.
I'm fairly new to programming for android and programming in general. I searched the web and stackoverflow for a solution, but can't seem to find one.
I have an app with different tabs handled in fragments. One of my fragments contains a listview. However, the listview won't updat or refresh. It should refresh when I get an incoming sms. Here is the fragment code:
public class SmsSectionFragment extends Fragment {
#SuppressWarnings("null")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View listView = inflater.inflate(R.layout.fragment_section_sms, container, false);
ListView mListData = (ListView) listView.findViewById(R.id.lvData);
TextView aantalSms = (TextView) listView.findViewById(R.id.aantalSms);
ArrayList<SmsInfo> listSms = getIntent().getParcelableArrayListExtra("ListSMS");
// check condition
if(listSms != null && listSms.size() > 0) {
// set data to list
SmsInfoAdapter adapter = new SmsInfoAdapter(getActivity(), listSms);
mListData.setAdapter(adapter);
adapter.setNotifyOnChange(true);
int count = listSms.size();
aantalSms.setText(String.valueOf(count));
}
return listView;
}
The receiving of sms is handled in three other classes, the Receiver code is:
package com.example.android.effectivenavigation;
import... etc
public class SmsReceiver extends BroadcastReceiver {
static ArrayList<SmsInfo> listSms = new ArrayList<SmsInfo>();
#Override
public void onReceive(Context context, Intent intent) {
// get SMS map from intent
Bundle extras = intent.getExtras();
// a notification message
String messages = "";
if ( extras != null ) {
// get array data from SMS
Object[] smsExtra = (Object[]) extras.get( "pdus" ); // "pdus" is the key
for ( int i = 0; i < smsExtra.length; ++i ) {
// get sms message
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
// get content and number
String body = sms.getMessageBody();
String adition = " SMS:: ";
String einde = " ::SMS";
String sendme = adition + body + einde;
String address = sms.getOriginatingAddress();
// create display message
messages += "SMS from " + address + " :\n";
messages += body + "\n";
//Send to Arduino
Amarino.sendDataToArduino(context, DEVICE_ADDRESS, 'T', sendme);
// store in the list
listSms.add(new SmsInfo(address, body));
}
// better check size before continue
if(listSms.size() > 0) {
// notify new arriving message
//Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
// set data to send
Intent data = new Intent(context, MainActivity.class);
// new activity
data.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
data.putParcelableArrayListExtra("ListSMS", listSms);
// start
context.startActivity(data);
}
}
}
Could someone shine some light on my problem?
Many thanks in advance!
It looks to me like you have nothing that actually updates the fragment. Your broadcast receiver is receiving information but you never add this to the fragment.
Do something like in your fragment declaration add:
private SMSReceiver receiver;
private IntentFilter filter;
In your onCreateView add:
receiver = new SMSReceiver();
filter = new IntentFilter(SMSReceiver.YOUR_STRING_FILTER);
registerReceiver(receiver, filter);
And then in your onReceive in the SMSReceiver class add something like:
adapter = new SmsInfoAdapter (this, yourData);
list.setAdapter(adapter);
Having this all in the Fragment class is what I do.