Difficulty sending data on the Broadcast receiver through Intent - java

I have a Touch Mobile Computer with a barcode scanner.
I'm trying to write an application that scans a barcode and imports data from the DB into the device. In order to use the scanner I use a broadcast receiver.
On the scan activity screen, there are a few barcodes to scan. I set the intent to transfer information from which edittext the scan was performed (using putextra). The broadcast receiver receives the scan the action but the input of the putextra is not exist (The handle variable gets a null value [Attached picture]).
I would be happy to help with what I'm doing wrong.
Activity Class:
public class MoveItemActivity extends AppCompatActivity {
private EditText item;
private EditText to;
private boolean mIsRegisterReceiver = false;
private BroadcastReceiver mBarcodeReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move_item);
item = (EditText) this.findViewById(R.id.itemInEditText);
item.setOnFocusChangeListener(mEditText);
to = (EditText) this.findViewById(R.id.toInEditText);
to.setOnFocusChangeListener(mEditText);
this.registerReceiver();
}
EditText.OnFocusChangeListener mEditText = new EditText.OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
Intent intent = new Intent();
switch (v.getId()){
case R.id.itemInEditText:
if (!hasFocus){
new CheckItem(MoveItemActivity.this).execute(item.getText().toString());
break;
}
else {
intent.setAction(BarcodeControllerConstants.ACTION_BARCODE_OPEN);
intent.putExtra(BarcodeControllerConstants.EXTRA_HANDLE, "item");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
break;
}
case R.id.toInEditText:
if (!hasFocus){
new CheckLocation().execute(to.getText().toString());
break;
}
else
{
intent.setAction(BarcodeControllerConstants.ACTION_BARCODE_OPEN);
intent.putExtra(BarcodeControllerConstants.EXTRA_HANDLE, "to");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
break;
}
}
}
};
private void registerReceiver() {
if (mIsRegisterReceiver)
return;
IntentFilter filter = new IntentFilter();
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_DECODING_DATA);
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_SUCCESS);
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_FAILED);
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_GET_STATUS);
mBarcodeReceiver = new BarcodeController();
registerReceiver(mBarcodeReceiver, filter);
mIsRegisterReceiver = true;
}
BroadcastReceiver Class:
public class BarcodeController extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int mBarcodeHandle = -1;
if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_DECODING_DATA)) {
String handle = intent.getExtras().getString(BarcodeControllerConstants.EXTRA_HANDLE);
byte[] data = intent.getByteArrayExtra(BarcodeControllerConstants.EXTRA_BARCODE_DECODING_DATA);
String result = null;
if (data != null) {
result = new String(data);
Intent i = new Intent(context, MoveItemActivity.class);
i.putExtra(handle,result );
context.startActivity(i);
}
} else if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_SUCCESS)) {
mBarcodeHandle = intent.getIntExtra(BarcodeControllerConstants.EXTRA_HANDLE, 0);
System.out.println("ACTION_BARCODE_CALLBACK_REQUEST_SUCCESS:" + mBarcodeHandle);
} else if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_FAILED)) {
int result = intent.getIntExtra(BarcodeControllerConstants.EXTRA_INT_DATA2, 0);
System.out.println("ACTION_BARCODE_CALLBACK_REQUEST_FAILED:" + result);
} else if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_GET_STATUS)) {
int status = intent.getIntExtra(BarcodeControllerConstants.EXTRA_INT_DATA2, 0);
System.out.println("ACTION_BARCODE_CALLBACK_GET_STATUS:" + status);
}
}
}

The item that you're sending in broadcast has action:
intent.setAction(BarcodeControllerConstants.ACTION_BARCODE_OPEN);
But in onReceive() you're checking different action:
action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_DECODING_DATA)
Are you sure this is the same intent that the one you're putting extras to?
intent.putExtra(BarcodeControllerConstants.EXTRA_HANDLE, "item");
You don't even register BarcodeControllerConstants.ACTION_BARCODE_OPEN action in your BarcodeController broadcast, so I think it's not received.

Related

Android send data to broadcast receiver

I am creating an Android app that notify the users when they received a SMS from selected numbers using Foreground Service. The program only notify the user when the Service is running. My Main Activity has 3 buttons: Start Service, Stop Service and Setting which lead to another Activity that let the user change their information such as password and selected number. Currently the application can read and write data to JSON fine and the data get pass to other activities through Intent, also the Broadcast Receiver for detecting SMS also work when a message in received, and since I want it to work with Foreground Service, I register it in onStartCommand and unregister it in onDestroy in the Service and not register it in Manifest. My problem is on how to pass the user data to the Broadcast Receiver, since it is register to listen to android.provider.Telephony.SMS_RECEIVED and when I try to pass Intent to it through sentBroadcast() in my Service, it does not receive any value of the user. I tried to settle in making the user public static and it worked, but not sure if this the right way to do it. Here is my current code:
MainActivity.java
Button btnStartService, btnStopService;
TextView lblStatus;
JSONHandler jsonHandler;//for handling JSON file and data
public static User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartService = findViewById(R.id.buttonStartService);
btnStopService = findViewById(R.id.buttonStopService);
jsonHandler = new JSONHandler(this);
boolean isFilePresent = isFilePresent(this, "user.json");
if(isFilePresent) {
try {
user = jsonHandler.readFromFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
user = new User();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestSmsPermission();
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
}
else {
startService();
}
}
public boolean isFilePresent(Context context, String fileName) {
String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
public void setBtnStartService(View view)
{
startService();
}
public void setBtnStopService(View view)
{
stopService();
}
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Message Service is running");
serviceIntent.putExtra("user", user);
ContextCompat.startForegroundService(this, serviceIntent);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
public void setBtnSetting(View view) {
Intent intent = new Intent(this, AuthenticateActivity.class);
intent.putExtra("user", user);
intent.putExtra("action", "setting");
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
startService();
}
}
private void requestSmsPermission() {
String permission = Manifest.permission.RECEIVE_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if ( grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
ForegroundService.java
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
SMSReceiver smsListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
User user = (User) intent.getSerializableExtra("user");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
if(smsListener == null)
{
smsListener = new SMSReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
Intent i = new Intent(this, SMSReceiver.class);
i.putExtra("user", user);
sendBroadcast(i);
registerReceiver(smsListener, intentFilter);
}
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(null!=smsListener)
{
unregisterReceiver(smsListener);
smsListener = null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
SMSReceiver.java
public class SMSReceiver extends BroadcastReceiver {
private String msgBody;
private String text = "";
private SharedPreferences preferences;
private String sender = "";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// User user = (User) intent.getExtras().getSerializable("user"); not working
User user = MainActivity.user;
ArrayList<String> banks = user.getBankList();
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Toast.makeText(context, "message received", Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage smsMessage;
for (int i = 0; i < pdus.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i], bundle.getString("format"));
else smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgBody = smsMessage.getMessageBody();
sender = smsMessage.getOriginatingAddress();
if(banks.contains(sender)) {
if (msgBody.contains(user.getPattern())) {
String[] tokens = msgBody.split(" ");
for (int j = 0; j < tokens.length; j++) {
if (tokens[j].contains("API")) {
text = tokens[j];
break;
}
}
}
}
}
//MainActivity.message = msgBody;
if(!text.isEmpty()) {
Toast.makeText(context, "message is: " + text, Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
else {
Log.i("cs.fsu", "smsReceiver : NULL");
}
}
}
Is this the right way to maintain user data throughout the application lifecycle? By making public static for every class accessible? Or is there away to pass it through Intent? Please help me out

Java android killed service

How I can kill this service:
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
I try do this :
Intent intent = new Intent(MainMenu.this, UsbService.class);
stopService(intent);
But the service works all the time.''
And this is my service :
public class UsbService extends Service {
public static final String ACTION_USB_READY = "pl.gps.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "pl.gps.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "pl..gps.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "pl.gps.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "pl.gps.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "pl.gps.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "pl.gps.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "pl.gps.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 1;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private IBinder binder = new UsbBinder();
private Context context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
String date = "";
public static boolean check(String s) {
if (s.contains("$GNRMC")) {
return true;
}
return false;
}
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null) {
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
connection = usbManager.openDevice(device);
serialPortConnected = true;
new ConnectionThread().run();
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
serialPortConnected = false;
serialPort.close();
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
#Override
public void onCreate() {
this.context = this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
HashMap<String, UsbDevice> usbDevices1 = new HashMap<String, UsbDevice>();
usbDevices1.clear();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
if (deviceVID == 1659 && devicePID == 8963) {
// There is a device connected to our Android device. Try to open it as a Serial Port.
requestUserPermission();
keep = false;
if (!keep)
break;
}
}
if (!keep) {
// There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
public void unReg(){
// if(usbReceiver != null)
// unregisterReceiver(usbReceiver);
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
private void requestUserPermission() {
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort != null && serialPort.open()) {
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
But my intent service steal is working. I try did whis when I destroyed my activity in which I created this service but when this activity is destroyed in logs I see that all the time this intent service is steel working
Try this
use stopSelf();
Once requested to stop with stopSelf() the system destroys the service as soon as possible.
pass some action with intent
Intent intent = new Intent(MainMenu.this, UsbService.class);
intent.setAction(Constants.ACTION.STOPTFOREGROUND_ACTION);
stopService(intent);
in your Service onStartCommand()
if(intent.getAction()==Constants.ACTION.STOPTFOREGROUND_ACTION){
stopForeground(true);
stopSelf();
}
public class Constants {
public interface ACTION {
String STOPFOREGROUND_ACTION = "com.package.packageName.action.stopforeground";
}
}

service data reset after swiping away application

Purpose of program: I'm trying to make an app that will count how many times the user checked their phone by issuing a broadcast for Intent.ACTION_SCREEN_ON. it then increments a counter and updates the activity with the new counter.
The problem: This all works just fine but as soon as I swipe away the application from the apps tray, the counter goes back to zero.
obviously what is supposed to happen is the counter would continue.
I tried saving the counter value in the service onDestroy and then calling it again onCreate but onDestroy is never called.
Note that in the onCreate() for the activity it sends a broadcast to the service asking for the most recent value of counter and then updates it in the view. I couldn't find a better way to keep them in sync.
CounterService.java
public class CounterService extends Service {
public static boolean RERUN = true;
private int counter = 0;
private SharedPreferences SP;
private BroadcastReceiver mScreenStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
counter++;
System.out.println("************************************* \n \n " + counter);
}
sendCounterBroadcast();
}
};
public void sendCounterBroadcast() {
Intent i = new Intent();
i.setAction("com.inc.count");
i.putExtra("counterValue", counter);
sendBroadcast(i);
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("********************** CounterService.onCreate()");
// get counter value from SP -- this is useful for when the service gets recreated
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
counter = SP.getInt("counter", 0);
// wait for screen to be turned on or for the activity to ask you for the counter number
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction("send.counter.to.phonecounteractivity");
registerReceiver(mScreenStateBroadcastReceiver, intentFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************************************** CounterService.OnDestroy()");
unregisterReceiver(mScreenStateBroadcastReceiver);
// Save counter value for when we restart service
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
SharedPreferences.Editor SPE = SP.edit();
if (RERUN) {
SPE.putInt("counter", counter);
System.out.println("******************************** RESTARTING SERVICE ");
startService(new Intent(getApplicationContext(), CounterService.class));
} else
SPE.putInt("counter", 0);
SPE.apply();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PhoneCheckerCounter.Java
public class PhoneCheckerCounter extends AppCompatActivity {
private BroadcastReceiver changeCount;
private IntentFilter filter;
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_checker_counter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switcherOnClick();
assignValuesOnCreate();
System.out.println("**************************** onCreate()");
changeCounterText();
}
public void switcherOnClick() {
final Switch sCounter = findViewById(R.id.switchCounter);
sCounter.setOnClickListener(new View.OnClickListener() {
Intent intent = new Intent(getApplicationContext(), CounterService.class);
#Override
public void onClick(View v) {
if (sCounter.isChecked()) {
startService(intent);
CounterService.RERUN = true;
v.getContext().registerReceiver(changeCount, filter);
Toast.makeText(getApplicationContext(), "Counting has begun", Toast.LENGTH_SHORT).show();
} else {
TextView n = findViewById(R.id.counter);
n.setText("0");
CounterService.RERUN = false;
v.getContext().unregisterReceiver(changeCount);
stopService(intent);
Toast.makeText(getApplicationContext(), "The application stopped counting", Toast.LENGTH_SHORT).show();
}
}
});
}
public void changeCounterText() {
changeCount = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView n = findViewById(R.id.counter);
counter = intent.getIntExtra("counterValue", 0);
System.out.println("************************ RECEIVED!!!! value of: " + counter);
n.setText("" + counter);
}
};
filter = new IntentFilter();
filter.addAction("com.inc.count");
this.registerReceiver(changeCount, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(changeCount);
assignValuesOnDestroy();
System.out.println("**************************** onDestroy()");
}
public void assignValuesOnCreate() {
Switch s = findViewById(R.id.switchCounter);
if (getSwitchValueFromSP() == 1) s.setChecked(true);
else s.setChecked(false);
Intent f = new Intent();
f.setAction("send.counter.to.phonecounteractivity");
sendBroadcast(f);
}
public void assignValuesOnDestroy() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = SP.edit();
Switch s = findViewById(R.id.switchCounter);
if (s.isChecked()) edit.putInt("switch", 1);
else edit.putInt("switch", 0);
edit.apply();
}
public int getSwitchValueFromSP() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
int isOn = SP.getInt("switch", 0);
return isOn;
}
}
Sample of the activity

How to refresh the static value when activity executed again

Here there is an activity called groupchat. Here I am having the static object activeEventMO.
In this groupchat activity the chatting function is going on. If user1 send a message to user2 that message received by gcmIntent class. in this gcmIntent class I have added the code for notification. Here if user1 send a message for a particular event notification received for user2. If user2 clicks that notification it will take to the user to that chat window that means groupchat activity.
for that in gcmIntent class I used parcelable to send the eventMO to groupchat activity. if user1 send a message to user2 for event2 user2 receives a notification. if user2 clciks the notification it show the chatwindow of event1. because when first time I send the eventid1 by sing eventMO. So it holds the eventid1 forever. it cannot refreshed.
This is my groupchat activity code
public class GroupChatActivity extends Activity {
private static ListView listViewMessages;
private static List<ChatMO> listChatMessageObjectses = new ArrayList<ChatMO>();
private static MessagesListAdapter adapter;
private static Handler UIHandler;
private static int RESULT_LOAD_IMAGE = 1;
private EditText inputMsg;
private String formatDate;
private Context context;
private String dateResult;
private static EventMO activeEventMO = null;
private UserDelegate userDelegate = new UserDelegate();
private MediaDelegates mediaDelegates = new MediaDelegates();
private MessageDelegates messageDelegates = new MessageDelegates();
private SharedPreferences sharedpreferences;
private List<UserMO> eventUserMOs = new ArrayList<>();
private Gson gson = new Gson();
private UserMO userMO = new UserMO();
private MessageMO messageMO = new MessageMO();
private File imgFile;
private MediaMO mediaMO = new MediaMO();
// this method is for store the current event id to eventMO coz eventMO globally declared as static
public void getevent()
{
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
public static void messageHandler(final MessageMO messageMo) {
UIHandler = new Handler(Looper.getMainLooper());
UIHandler.post(new Runnable() {
public void run() {
Log.e("messageHandler", messageMo.getEventTitle());
ChatMO chatMO = new ChatMO();
chatMO.setMessage(messageMo.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMo.getfromUserName());
chatMO.setDate(messageMo.getDate());
Log.e("handler", "eventMO" + activeEventMO);
Log.e("handler", "messageMO" + messageMo);
if (activeEventMO.getEventId() == messageMo.getEventId()) {
listChatMessageObjectses.add(chatMO);
listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ChatMO chatMO = new ChatMO();
chatMO.setMessage_type(Constants.IS_TYPE_CHAT_IMAGE);
chatMO.setMessage(picturePath);
chatMO.setSelf(1);
chatMO.setIs_delete(0);
chatMO.setFromName("");
chatMO.setEvent_id(activeEventMO.getEventId());
messageMO.setMessage("");
messageMO.setRingeeUserId(userMO.getRingeeUserId());
// messageMO.setDate(messageMO.getDate());
messageMO.setMobileNumber(userMO.getMobileNumber());
messageMO.setEventId(activeEventMO.getEventId());
messageMO.setEventTitle(activeEventMO.getText());
Log.e("sendbutton", "eventtitle" + messageMO.getEventTitle());
messageMO.setfromUserName(userMO.getUserName());
messageMO.setMessageType(Constants.MESSAGE_TYPE_MSG);
mediaMO.setRingeeUserId(userMO.getRingeeUserId());
mediaMO.setIsType(Constants.IS_TYPE_CHAT_IMAGE);
imgFile = new File(picturePath);
listChatMessageObjectses.add(chatMO);
listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return mediaDelegates.insertChatFile(context, imgFile, messageMO, eventUserMOs, mediaMO);
}
#Override
protected void onPostExecute(String mediaBo) {
Toast.makeText(getApplicationContext(), "uploaded Status" + mediaBo, Toast.LENGTH_LONG).show();
if (!mediaBo.equals("null")) {
MediaMO mediaMO1 = gson.fromJson(mediaBo, new TypeToken<MediaMO>() {
}.getType());
}
}
}.execute(null, null, null);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.ic_menu_gallery) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
activeEventMO = new EventMO();
setContentView(R.layout.chat_main);
context = getApplicationContext();
String message = "";
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
Log.e("oncreate", "eventMO" +activeEventMO);
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
Log.e("oncreate", "chatMOs" + chatMOs);
for (ChatMO chatMO1 : chatMOs) {
message = chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
here i am passing the eventMO in gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
eventMO.setEventId(messageMO.getEventId());
Log.e("gcm","evetid"+eventMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Log.e("gcm","eventid"+messageMO.getEventId());
mNotificationManager.notify((int) (long) eventMO.getEventId(), mBuilder.build());
}
can you please tell me how to fix this issue thanks in advance
To refresh a variable after you activity or fragment has been destroyed you need to store in the saved bundled provided you in the method
public void onSavedInstanceState(final Bundle bundle)
And reset values with the bundle provided in the method
public void onCreate(final Bundle savedInstance)
Here is some good documentation
enter code here[Recreating an Activity - Android][1]

How to start service based on result from activity recognition

I am Trying to start a service if the DetectedActivity returned from Activity recognition returned is IN_VEHICLE. I have downloaded a code sample
from :
http://tutsberry.com/activity-recognition-implementation-on-android/
But i'm not sure where to put code in to start my service.
I am Trying to the check the user activity in the background using the Activity Recognition and then
start a service all in the background.
ActivityRecognitionIntentService Class
public class ActivityRecognitionIntentService extends IntentService {
//LogCat
private static final String TAG = ActivityRecognitionIntentService.class.getSimpleName();
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
//Extract the result from the Response
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity detectedActivity = result.getMostProbableActivity();
//Get the Confidence and Name of Activity
int confidence = detectedActivity.getConfidence();
String mostProbableName = getActivityName(detectedActivity.getType());
//Fire the intent with activity name & confidence
Intent i = new Intent("ImActive");
i.putExtra("activity", mostProbableName);
i.putExtra("confidence", confidence);
Log.d(TAG, "Most Probable Name : " + mostProbableName);
Log.d(TAG, "Confidence : " + confidence);
//Send Broadcast to be listen in MainActivity
this.sendBroadcast(i);
} else {
Log.d(TAG, "Intent had no data returned");
}
}
//Get the activity name
private String getActivityName(int type) {
switch (type) {
case DetectedActivity.IN_VEHICLE:
return "In Vehicle";
case DetectedActivity.ON_BICYCLE:
return "On Bicycle";
case DetectedActivity.ON_FOOT:
return "On Foot";
case DetectedActivity.WALKING:
return "Walking";
case DetectedActivity.STILL:
return "Still";
case DetectedActivity.TILTING:
return "Tilting";
case DetectedActivity.RUNNING:
return "Running";
case DetectedActivity.UNKNOWN:
return "Unknown";
}
return "N/A";
}
}
MainActivity Class
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
// LogCat
private static final String TAG = MainActivity.class.getSimpleName();
private Context mContext;
private GoogleApiClient mGApiClient;
private BroadcastReceiver receiver;
private TextView textView;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.msg);
textView.setMovementMethod(new ScrollingMovementMethod());
tv2 = (TextView) findViewById(R.id.text2);
//Set the context
mContext = this;
//Check Google Play Service Available
if (isPlayServiceAvailable()) {
mGApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//Connect to Google API
mGApiClient.connect();
} else {
Toast.makeText(mContext, "Google Play Service not Available", Toast.LENGTH_LONG).show();
}
//Broadcast receiver
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Add current time
Calendar rightNow = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
String strDate = sdf.format(rightNow.getTime());
;
String v = strDate + " " +
intent.getStringExtra("activity") + " " +
"Confidence : " + intent.getExtras().getInt("confidence") + "\n";
v = textView.getText() + v;
textView.setText(v);
}
};
//Filter the Intent and register broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction("ImActive");
registerReceiver(receiver, filter);
//Check for Google play services available on device
}
private boolean isPlayServiceAvailable() {
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS;
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#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_main, menu);
return true;
}
#Override
public void onConnected(Bundle bundle) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecongPendingIntent = PendingIntent
.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG, "connected to ActivityRecognition");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);
//Update the TextView
textView.setText("Connected to Google Play Services \nWaiting for Active Recognition... \n");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Suspended to ActivityRecognition");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Not connected to ActivityRecognition");
//Disconnect and detach the receiver
mGApiClient.disconnect();
unregisterReceiver(receiver);
}
}
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends Activity {
IntentFilter filter;
BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filter = new IntentFilter();
mReceiver = new MyReceiver();
filter.addAction("IN_VEHICLE"); //Name the action what ever you need to.
filter.addAction("OTHER_ACTION");
filter.addAction("YET_ANOTHER_ACTION)");
registerReceiver(mReceiver, filter); //Register the receiver you define with the actions you want.
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("IN_VEHICLE_RESPONSE".equals(intent.getAction())){
//Launch other activities here
Intent i = new Intent(getApplicationContext(), InVehicleActivity.class );
startActivity(i);
}else if("OTHER_ACTION_RESPONSE".equals(intent.getAction())){
//Launch desired activity
}else if("YET_ANOTHER_ACTION_RESPONSE".equals(intent.getAction())){
//Launch desired activity
}else{
//Handle unssuported actions
}
}
}
}
MyIntentService.java
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
public class MyIntentService extends IntentService {
Bundle extras;
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
extras = intent.getExtras();
if("IN_VEHICLE".equals(intent.getAction())){
inVehicle(extras);
return;
}
if("OTHER_ACTION".equals(intent.getAction())){
//otheraction method
return;
}
if("YET_ANOTHER_ACTION".equals(intent.getAction())){
//yetanotheraction method
return;
}
}
private void inVehicle(Bundle extras) {
//do work
//do work
Intent intent = new Intent();
intent.setAction("IN_VEHICLE_RESPONSE");
//put all other desired stuff in intent
getApplicationContext().sendBroadcast(intent);
}
}
Don't forget to add your receiver to your manifest.
I would suggest that you start Activities from Activity not Service layer.

Categories