Android Handheld and Wear Communication is not consistent - java

We have an Android mobile app, where you can purchase parking tickets for a period. Now, we are planning to integrate it with Android wear.
What we are doing here is:
We want the user to get notified 15 before of the expiry of ticket.
To do this, we create a local notification and schedule it using Alarm Manger.
This scheduled notification is received by Android Broadcast receiver and display this notification on mobile device in Android notification section.
Further, this receiver calls the intent service to send the notification to wear. In this step, we create googleApiClient and onConnected callback, we send the data to wear to show the notification.
On wear, user can check the notification and on tap, user can extend the time of purchased ticket. This flow contains 3-4 views after notification tapping.
We have issue in step 4. Most of the time, on a very first connection (notification), wear does not show the notification and on second connection (notification), wear show both first and second notification and after that it works fine.
We tried to figure out the problem, but no success. Below is the code snippet of Receiver, Intent Service and wear side ListnerServices for understanding.
public class WearNotificationService extends IntentService {
private static final String TAG = "PhoneActivity";
private GoogleApiClient mGoogleApiClient;
public static String title;
public static String desc;
public static String data;
public WearNotificationService() {
super("WearNotificationService");
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, title +"--"+ desc , Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
sendNotification(title,desc,data);
Log.d(TAG, "onConnected: " + connectionHint);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
}).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
protected void onHandleIntent(Intent intent) {
}
private void sendNotification(String title,String desc,String data) {
Log.e(TAG, "i am onConnectiond: ");
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(Constants.PATH_NOTIFICATION);
dataMapRequest.getDataMap().putDouble(Constants.NOTIFICATION_TIMESTAMP, System.currentTimeMillis());
dataMapRequest.getDataMap().putString(Constants.KEY_TITLE, title);
dataMapRequest.getDataMap().putString(Constants.KEY_DESC, desc);
dataMapRequest.getDataMap().putString(Constants.KEY_DATA, data);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null != intent) {
String action = intent.getAction();
if (Constants.ACTION_DISMISS.equals(action)) {
dismissNotification();
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent dataEvent : dataEvents) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
if (Constants.PATH_NOTIFICATION.equals(dataEvent.getDataItem().getUri().getPath())) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(dataEvent.getDataItem());
String title = dataMapItem.getDataMap().getString(Constants.KEY_TITLE);
String content = dataMapItem.getDataMap().getString(Constants.KEY_DESC);
String data = dataMapItem.getDataMap().getString(Constants.KEY_DATA);
String id = null;
try {
JSONObject obj = new JSONObject(data);
id = (String) obj.get("id");
} catch (JSONException e) {
e.printStackTrace();
}
sendNotification(title, content, data,id);
}
}
}
}
private void sendNotification(String title, String content, String data,String id) {
Intent notificationIntent = new Intent(this, HoursExtension.class);
Log.e("data1111", data);
HoursExtension.data = data;
HoursExtension.id = id;
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(notificationPendingIntent)
.extend(new NotificationCompat.WearableExtender().setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.rtabg)))
;
Notification notification = builder.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(Integer.parseInt(id), notification);
}

I solved it by sending a dummy request on app installation . Which is send once the app is installed and handled in wear by eating that first request this solved my problem . :)

Related

Arraylist being assigned correctly inside a constructor but is null when it is outside in a Android Studio Service

I cannot seem to figure out as to why whenever I try to assign an arraylist I recieved from the MainActivity to a public arraylist of a background service SensorService in the service's constructor.
This is my constructor
public SensorService(ArrayList<String> contactListNumber) {
contactNumbers=contactListNumber;
Log.d(TAG, "Inside Constructor");
Log.d(TAG, "SensorService: Phone Numbers = "+contactListNumber);
Log.d(TAG, "SensorService: Input Arraylist Size = "+contactListNumber.size());
Log.d(TAG, "SensorService: Assigned Arraylist Size = "+contactNumbers.size());
setPhoneNumberArray(contactListNumber);
}
I even tried invoking a method but it still gives me the same results where it assigns the contactNumbers correctly but when I try to invoke it inside onCreate I get an NullPointerException.
This is the MainActivity Intent where I create the service
SensorService sensorService = new SensorService(Contact_Number);
Intent intent = new Intent(this, sensorService.getClass());
if(!isMyServiceRunning(sensorService.getClass())){
startService(intent);
//intent.putExtra("ContactNumberList", Contact_Number);
Toast.makeText(this, "Starting Service", Toast.LENGTH_SHORT).show();
}
And this is my complete SensorService.
public class SensorService extends Service {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
public ArrayList<String> contactNumbers;
public SensorService() {
}
public SensorService(ArrayList<String> contactListNumber) {
contactNumbers=contactListNumber;
Log.d(TAG, "Inside Constructor");
Log.d(TAG, "SensorService: Phone Numbers = "+contactListNumber);
Log.d(TAG, "SensorService: Input Arraylist Size = "+contactListNumber.size());
Log.d(TAG, "SensorService: Assigned Arraylist Size = "+contactNumbers.size());
setPhoneNumberArray(contactListNumber);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
//contactNumbers=MainActivity.Contact_Numbers;
super.onCreate();
// start the foreground service
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
Log.d(TAG, "SensorService: Assigned Arraylist Size Outside Constructor = "+contactNumbers.size());
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
#SuppressLint("MissingPermission")
#Override
public void onShake(int count) {
// check if the user has shacked
// the phone for 3 time in a row
//if (count == 3)
if (count == 1) {
// vibrate the phone
vibrate();
Log.d(TAG, "onShake: Vibrate Activated");
// create FusedLocationProviderClient to get the user location
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
Log.d("Check: ", "Sending Message");
// use the PRIORITY_BALANCED_POWER_ACCURACY
// so that the service doesn't use unnecessary power via GPS
// it will only use GPS at this very moment
fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() {
#Override
public boolean isCancellationRequested() {
return false;
}
#NonNull
#Override
public CancellationToken onCanceledRequested(#NonNull OnTokenCanceledListener onTokenCanceledListener) {
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// check if location is null
// for both the cases we will
// create different messages
Log.d("Check: ", "MESSAGE SENT");
if (location != null) {
// get the SMSManager
SmsManager smsManager = SmsManager.getDefault();
// get the list of all the contacts in Database
DatabaseHelper db = new DatabaseHelper(SensorService.this);
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
ArrayList<String> phonenumber = new ArrayList<String>();
Log.d(TAG, "onSuccess: contactlistnumber size = "+contactNumbers.size());
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
Log.d(TAG, "onSuccess: Item 1 = "+phoneNumberList[0]);
for(int i = 0; i < phoneNumberList.length ; i++){
Log.d("Number is",(String)phoneNumberList[i]);
}
//phonenumber = (ArrayList<String>)getIntent().getSerializableExtra("ContactNumberList");
// send SMS to each contact
for (String c : phoneNumberList) {
String message = "Hey, I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + "http://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude();
smsManager.sendTextMessage(c, null, message, null, null);
}
} else {
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DatabaseHelper db = new DatabaseHelper(SensorService.this);
List<ContactInfo> list = (List<ContactInfo>) db.getEveryone();
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
for (String c : phoneNumberList) {
smsManager.sendTextMessage(c, null, message, null, null);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("Check: ", "OnFailure");
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DatabaseHelper db = new DatabaseHelper(SensorService.this);
List<ContactInfo> list = (List<ContactInfo>) db.getEveryone();
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
for (String c : phoneNumberList){
smsManager.sendTextMessage(c, null, message, null, null);
}
}
});
}
}
});
// register the listener
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
// method to vibrate the phone
public void vibrate() {
final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
VibrationEffect vibEff;
// Android Q and above have some predefined vibrating patterns
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK);
vibrator.cancel();
vibrator.vibrate(vibEff);
} else {
vibrator.vibrate(500);
}
}
// For Build versions higher than Android Oreo, we launch
// a foreground service in a different way. This is due to the newly
// implemented strict notification rules, which require us to identify
// our own notification channel in order to view them correctly.
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("You are protected.")
.setContentText("We are there for you")
// this is important, otherwise the notification will show the way
// you want i.e. it will show some default notification
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public void onDestroy() {
// create an Intent to call the Broadcast receiver
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
public void setPhoneNumberArray(ArrayList numbers) {
contactNumbers=numbers;
//Log.d(TAG, "setPhoneNumberArray: contactnumbers size = "+contactNumbers.size());
}
}
would really appreciate if anyone could tell me why this is happening.
I found my mistake.
For anyone else trying to do this.
I made the very shortsighted mistake of not declaring the Arraylist contactNumbers as static.
This is what it looked like before.
public ArrayList<String> contactNumbers;
In the end when I added the static keyword. such that it looks like
static public ArrayList<String> contactNumbers;.
Everything else seems to work corrrectly. Since I could now get the value of contactNumbers inside of the service.

Send data to activity when Firebase notification is clicked in Android

In my application I want use fireBase for notification.
I want when click on notification (when app is closed, my mean is app is background) send data with putExtra to mainActivity.
I write below codes, but when click on notification (in app is background) but show me null for getStringExtra !
MyNotificationManager class :
public class MyNotificationManager {
private Context mCtx;
private Uri soundUri;
private static MyNotificationManager mInstance;
public MyNotificationManager(Context context) {
mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body) {
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(mCtx, MainActivity.class);
intent.putExtra("fcm_notification", "Y");
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setContentText(body)
.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mNotifyMgr.notify(1, mBuilder.build());
}
}
}
MyFirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotify(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
}
private void showNotify(String title, String body) {
MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
//myNotificationManager.displayNotification(title, body);
myNotificationManager.displayNotification(title, body);
}
}
MainActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkIntent()) return;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
checkIntent();
}
}, 1000);
}
private boolean checkIntent() {
String value = getIntent().getStringExtra("fcm_notification");
Toast.makeText(context, "" + value, Toast.LENGTH_SHORT).show();
if (value == null) return false;
if (value.equals("Y")) {
startActivity(new Intent(this, LandingActivity.class));
// open one activity.
} else if (value.equals("another thing")) {
// open another activity.
}
finish();
return true;
}
When click on notification (on app is background) , show me null message in Toast for this line String value = getIntent().getStringExtra("fcm_notification");
How can i fix it?
When sending notification from console, add the custom data from 'Advanced options':
For some reason, firebase doesn't allow the key to start with fcm. You cannot use fcm_notification. Use a different key.
For above image, receive the key as follows:
String value = getIntent().getStringExtra("test_key");
Try this:
Intent intent = new Intent(mCtx, MainActivity.class);
intent.putExtra("EXTRA_DATA", title);
And to get:
String value = getIntent().getStringExtra("EXTRA_DATA");
Better to change the key. Also, it seems like you'll need to send a data from console and then, sending the data to the another Activity.
I've used the current notification title to check if it returns the title or not.If it returned the value, so, try sending data from the console.

The first transition is always the same - Activity Recognition API - Activity Transition

I use activity recognition api and activity transitions. When I first run the app, the first transition is always the. In this app it's WALKING-ENTER. When I tried with only IN_VEHICLE-ENTER and IN_VEHICLE-EXIT in transitions, it was IN_VEHICLE-ENTER. I thought about ignoring the first transition but a device I've tested on didn't have such a problem. The devices that had these problem were Android 8.1, and the device didn't have the problem was 6.0.
MainActivity extends AppCompatActivity
private static Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
if(!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
Button button = findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
serviceIntent = new Intent(MainActivity.this, ServiceS.class);
MainActivity.this.startService(serviceIntent);
}
});
}
public static boolean hasPermissions(Context context, String... permissions) {
if (permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
ServiceS extends Service
public ServiceS() {
super();
}
public static void locationArrived(Context context, Location location) {
Log.d("hmm: ", location.toString());
}
#SuppressLint("MissingPermission")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
initActivityTransition();
super.onCreate();
}
#Override
public void onDestroy() {
Log.d("hmm: ", "Updates stopped!");
Task task = ActivityRecognition.getClient(this)
.removeActivityTransitionUpdates(activityPendingIntent);
super.onDestroy();
}
// ACTIVITY TRANSITION BLOCK START
private static List<ActivityTransition> transitions = new ArrayList<>();
private static PendingIntent activityPendingIntent;
private static ActivityTransitionRequest transitionRequest;
void initActivityTransition(){
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.WALKING)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.WALKING)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.STILL)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.STILL)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build());
Intent activityIntentService = new Intent(this, TransitionReceiver.class);
activityPendingIntent = PendingIntent.getBroadcast(this, 1, activityIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d("hmm: ","DriveBuddyService - initActivityTransition");
}
static void transitionArrived(final ActivityTransitionEvent event, final Context context){
Log.d("hmm: ", event.toString());
Toast.makeText(context, event.getActivityType() + "-" + event.getTransitionType(), Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
if(transitionRequest==null) {
transitionRequest = new ActivityTransitionRequest(transitions);
}
Task task = ActivityRecognition.getClient(this)
.requestActivityTransitionUpdates(transitionRequest, activityPendingIntent);
super.onStart(intent, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
TransitionReceiver extends BroadcastReceiver.
public void onReceive(final Context context, Intent intent) {
Log.d("hmm: ","DriveBuddyTransitionReceiver - Enter");
if (ActivityTransitionResult.hasResult(intent)) {
ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
for (ActivityTransitionEvent event : result.getTransitionEvents()) {
ServiceS.transitionArrived(event, context);
}
}
}
I observed the same thing too. It seems that the last activity is kept in cache or something like that. I saw this happening on Android 7.1 and Android 8.1.
To counter this I check the elapsed time of when the transition happened. I ignore the callback if the transition happened over 30 seconds ago.
This is what my code looks like:
#Override
public void onReceive(Context context, Intent i) {
if (ActivityTransitionResult.hasResult(i)) {
ActivityTransitionResult result = ActivityTransitionResult.extractResult(i);
for (ActivityTransitionEvent event : result.getTransitionEvents()) {
//continue only if the activity happened in the last 30 seconds
//for some reason callbacks are received for old activities when the receiver is registered
if(((SystemClock.elapsedRealtime()-(event.getElapsedRealTimeNanos()/1000000))/1000) <= 30) {
//activity transition is legit. Do stuff here..
}
}
}
}
I've typically seen callbacks arrive 0-10 seconds of them occurring.

USB Host Android Cannot Send String

I wanted my Android to communicate with an Arduino using an USB host. I've tried many references but can't seem to send any char to my Arduino. I can detect my Arduino but sending char or string to it is frustrating. Here are my codes:
MainActivity.java
public class MainActivity extends AppCompatActivity {
UsbDevice device=null;
UsbManager manager=null;
PendingIntent mPermissionIntent;
UsbInterface intf;
UsbEndpoint endpoint;
UsbDeviceConnection connection;
Button find;
Button send;
TextView hello;
UsbManager mUsbManager;
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find = (Button) findViewById(R.id.Find);
send = (Button) findViewById(R.id.Send);
hello = (TextView) findViewById(R.id.hello);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hello.setText("");
checkInfo();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(device!=null) {
intf = device.getInterface(0);
endpoint = intf.getEndpoint(0);
connection = mUsbManager.openDevice(device);
hello.setText("Kirim");
String kirim = "a";
bytes = kirim.getBytes();
connection.claimInterface(intf, forceClaim);
connection.bulkTransfer(endpoint, bytes, bytes.length, 0);
}
else{
Toast.makeText(MainActivity.this,"Device ==
null",Toast.LENGTH_SHORT);
}
}
});
private void checkInfo(){
manager=(UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this,0,new
Intent(ACTION_USB_PERMISSION),0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver,filter);
HashMap<String,UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String i="";
int j=0;
while(deviceIterator.hasNext()){
device = deviceIterator.next();
manager.requestPermission(device,mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
j++;
}
hello.setText(i);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " +
device);
}
}
}
}
};
}
I iterate using a find button and send using a send button. The iteration went just fine, but the sending didn't work. I needed to send just a character to the Arduino. My phone supports OTG and had been tested using other serial communication application to send char to Arduino and it works just fine.
Thanks in advance
using the usb serial lib in releases section at: https://github.com/felHR85/UsbSerial then import the lib and install dependencies as shown in the url. For solving the problem you can create a service class that handles usb related stuff (look at usb host android documentation for details: https://developer.android.com/guide/topics/connectivity/usb/host.html
as follows:
public class UsbService extends Service {
public static final String TAG = "UsbService";
public static final String ACTION_USB_READY = "com.felhr.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 = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
public static final int CTS_CHANGE = 1;
public static final int DSR_CHANGE = 2;
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 UsbService 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.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
/*
* State changes in the CTS line will be received here
*/
private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
#Override
public void onCTSChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(CTS_CHANGE).sendToTarget();
}
};
/*
* State changes in the DSR line will be received here
*/
private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
#Override
public void onDSRChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(DSR_CHANGE).sendToTarget();
}
};
/*
* Different notifications from OS will be received here (USB attached, detached, permission responses...)
* About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
*/
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);
new ConnectionThread().start();
} 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);
if (serialPortConnected) {
serialPort.close();
}
serialPortConnected = false;
}
}
};
/*
* 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();
serialPort.close();
unregisterReceiver(usbReceiver);
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();
if (!usbDevices.isEmpty()) {
// first, dump the hashmap for diagnostic purposes
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
Log.d(TAG, String.format("USBDevice.HashMap (vid:pid) (%X:%X)-%b class:%X:%X name:%s",
device.getVendorId(), device.getProductId(),
UsbSerialDevice.isSupported(device),
device.getDeviceClass(), device.getDeviceSubclass(),
device.getDeviceName()));
}
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
// if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003) && deviceVID != 0x5c6 && devicePID != 0x904c) {
if (UsbSerialDevice.isSupported(device)) {
// There is a supported device connected - request permission to access it.
requestUserPermission();
break;
} else {
connection = null;
device = null;
}
}
if (device==null) {
// There are no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
Log.d(TAG, "findSerialPortDevice() usbManager returned empty device list." );
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
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);
}
/*
* Request user permission. The response will be received in the BroadcastReceiver
*/
private void requestUserPermission() {
Log.d(TAG, String.format("requestUserPermission(%X:%X)", device.getVendorId(), device.getProductId() ) );
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;
}
}
/*
* A simple thread to open a serial port.
* Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
*/
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPortConnected = true;
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
/**
* Current flow control Options:
* UsbSerialInterface.FLOW_CONTROL_OFF
* UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
* UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
*/
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
serialPort.getCTS(ctsCallback);
serialPort.getDSR(dsrCallback);
//
// Some Arduinos would need some sleep because firmware wait some time to know whether a new sketch is going
// to be uploaded or not
//Thread.sleep(2000); // sleep some. YMMV with different chips.
// Everything went as expected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
// Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
// Send an Intent to Main Activity
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 {
// No driver for given device, even generic CDC driver could not be loaded
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
then in your main activity put this snippets:
java
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
public TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
// Toast.makeText(getApplicationContext(),"dentro on service connected " + usbService, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.operacion);
mHandler = new MyHandler(this);
// your stuff here
#Override
public void onResume() {
super.onResume();
// Toast.makeText(getApplicationContext(),"on resume ", Toast.LENGTH_SHORT).show();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
// Toast.makeText(getApplicationContext(),"despues de start y weas ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
// Toast.makeText(getApplicationContext(),"start1", Toast.LENGTH_SHORT).show();
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);
// Toast.makeText(getApplicationContext(),"dp metodo start", Toast.LENGTH_SHORT).show();
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public void getCurrentTimeUsingDate(){
String currentDateTimeString2 = DateFormat.getDateInstance().format(new Date());
TextView txtView3 = (TextView) findViewById(R.id.textView4);
txtView3.setText(""+currentDateTimeString2);
}
private static class MyHandler extends Handler {
private final WeakReference<Pag4> mActivity;
public MyHandler(Pag4 activity) {
mActivity = new WeakReference<>(activity);
}
Integer conta = 0;
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
conta++;
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE",Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE",Toast.LENGTH_LONG).show();
break;
}
}
}
}
you make a button (btn3 in the example) and then add the listener as follows:
java
bt3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String auxi2="1"; // put whatever you need to send here
if (!auxi2.equals("")) {
String data = auxi2;
if (usbService != null) { // if UsbService was correctly binded, Send data
usbService.write(data.getBytes());
// Toast.makeText(getApplicationContext(),"auxi2 escrito"+ auxi2, Toast.LENGTH_SHORT).show();
}
}
}
});
Hope is clear, I assume you know how to import libs, and make a button, put the permission in manifiest, dependencies. Details about this in android doc link already posted upper in my answer.

I can't refresh my webview when I open push notification

I want to create Android app of my web site using WebView and gcm, I am about to finish my project. My application can receive push notifications, WebView is working properly but I have a problem. The problem is that I can't refresh my WebView when I open push notification. When the app is on background mood it can't be refreshed. It shows old view.
My MainActivity.java:
public class MainActivity extends Activity {
// label to display gcm messages
TextView lblMessage;
Controller aController;
private WebView webView;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
private Intent notificationIntent;
public static String name;
public static String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://admob.adnet.az/main/index.php");
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
aController = (Controller) getApplicationContext();
// Check if Internet present
if (!aController.isConnectingToInternet()) {
// Internet Connection is not present
aController.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest permissions was properly set
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
// Register custom Broadcast receiver to show messages on activity
registerReceiver(mHandleMessageReceiver, new IntentFilter(
Config.DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
final String email = i.getStringExtra("email");
// Check if regid already presents
if (regId.equals("")) {
// Register with GCM
GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);
} else {
// Device is already registered on GCM Server
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM Server", Toast.LENGTH_LONG).show();
String url = "http://admob.adnet.az/main/index.php?email="+email+"&regid="+regId;
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
// public void onLoadResource (WebView view, String url) {
// if (progressDialog == null) {
// in standard case YourActivity.this
// progressDialog = new ProgressDialog(ShowWebView.this);
// progressDialog.setMessage("Loading...");
// progressDialog.show();
// }
// }
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
//new ReloadWebView(this, 5, webView);
} 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 = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
aController.register(context, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
// execute AsyncTask
mRegisterTask.execute(null, null, null);
}
}
}
private void post(String serverUrl, Map<String, String> params) {
// TODO Auto-generated method stub
}
private void startWebView(String string) {
// TODO Auto-generated method stub
}
// Create a broadcast receiver to get message and show on screen
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
aController.acquireWakeLock(getApplicationContext());
// Display message on the screen
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "Got Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
aController.releaseWakeLock();
}
};
#Override
protected void onDestroy() {
// Cancel AsyncTask
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
// Unregister Broadcast Receiver
unregisterReceiver(mHandleMessageReceiver);
//Clear internal resources.
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
}
My GCMIntentService.java:
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
private Controller aController = null;
public GCMIntentService() {
// Call extended class Constructor GCMBaseIntentService
super(Config.GOOGLE_SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device registered: regId = " + registrationId);
aController.displayMessageOnScreen(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
aController.register(context, MainActivity.name, MainActivity.email, registrationId);
}
/**
* Method called on device unregistred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device unregistered");
aController.displayMessageOnScreen(context, getString(R.string.gcm_unregistered));
aController.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message from GCM server
* */
#Override
protected void onMessage(Context context, Intent intent) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Create a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Thanks in Advance
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
** notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); **
PendingIntent intent =PendingIntent.getActivity(context, 0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
OR Add in manifest
<activity
android:name = "MainActivity"
android:noHistory="true"
android:launchMode = "singleTop"/>

Categories

Resources