RSS

Android Push Notifications when app is closed

By: Charuක

 

Yes, it is possible ‘to receive notifications from google cloud message when the application is fully closed’.

Infact, A broadcast receiver is the mechanism GCM uses to deliver messages. You need to have implement a BroadcastReceiver and declare it in the AndroidManifest.xml.

Please refer to the following code snippet.

AndroidManifest.xml

<receiver
    android:name=".GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <!-- Receives the actual messages. -->
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.google.android.gcm.demo.app" />
    </intent-filter>
</receiver>
<service android:name=".GcmIntentService" />

Java code

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

When GCM delivers a message to your device, BroadcastReceiver will receive the message and call the onReceive() function, wherein you may start a service to actually perform the intended task for you.

The above Code example uses a specialized BroadcastReceiver called WakefulBroadcastReceiver, which makes sure that the device doesn’t go to sleep, while the service is doing its work.

Refer to the Official Android Page for the same: https://developer.android.com/google/gcm/client.html

 

 

 

Copy from: https://stackoverflow.com/questions/24313539/push-notifications-when-app-is-closed

Advertisements
 
Leave a comment

Posted by on September 15, 2017 in Android, Mobile Development

 

Auto start pm2 when reboot Windows

install pm2:

$ npm install pm2 -g

install mp2 start for windows

$ npm install pm2-windows-startup -g

 

install pm2 window service

$ npm i pm2-windows-service -g

$ pm2-service-install [-n <service name>]

and go to this install path: C:\Users\Administrator\AppData\Roaming\npm\node_modules\pm2-windows-service\src\daemon\ and find file

is called “mp2node” and edit at <argument>[js file].js</argument> to path of your javascript file and save and reboot service in “Service.msc”

 

 

 

 

 
Leave a comment

Posted by on September 7, 2017 in NodeJs, pm2

 

Adding Badge count on menu items like cart , notification etc

By: mobikul.com

In every application, we decorate our MenuItem placed on ActionBar. Displaying of badge count not only decorate the ActionBar beautifully but also displays useful information like showing the number of items currently available in your cart or update you with unread notification.

We can create badge count using either a custom view or by adding a distinct drawable to display the each state of MenuItem.

Both the options have its pros and cons.

There is another approach using LayerDrawable which is more flexible and efficient than the former approaches.

Here’s what we’re going to do:

  1. Create a LayerDrawable to display MenuItem with a badge.
  2. Create a custom drawable let us called BadgeDrawable.
  3. Set badge on the menu item from our Activity.

LayerDrawable

A Drawable that manages an array of other Drawables. These are drawn in array order, so the element with the largest index will be drawn on top.It can be defined in an XML file with the

It can be defined in an XML file with the <layer-list> element. Each Drawable in the layer is defined in a nested<item>

i. Creating a layer drawable to display menu item on layer one and badge on top of it.

ic_menu_cart.xml

ii. Creating menu for our activity to display the count on the menu items.

main.xml

iii. Creating a flexible and efficient custom BagdeDrawable class to draw a view that looks like a count

BagdeDrawable.java

 

Setting up altogether

We can get the icon of the menu using getIcon() method.

Here is our method setBadgeCount(). We can pass LayerDrawable which we get from meniItem and setBadge from anywhere from the application.

Sample source code

 

Copy from: https://mobikul.com/adding-badge-count-on-menu-items-like-cart-notification-etc/

 

 

 
Leave a comment

Posted by on June 7, 2017 in Android, Mobile Development

 

Package Manager in Xcode

By: 

$ update_xcode_plugins

This tool adds the missing UUIDs into the installed Xcode plugins so that they can be loaded by newer versions of Xcode.

You can choose to run it once or install a launch agent that will trigger the tool every time any of your installed plugins are modified or Xcode/Xcode-beta gets updated.

This tool also allows you to unsign Xcode in order to run plugins on Xcode 8 and later. For more information on why this is needed, see alcatraz/Alcatraz#475.

When unsigning Xcode, you will also be prompted to unsign xcodebuild; Doing so will allow xcodebuild to load plugins and silence the library validation warnings. More info at #8.

If you are having any issues, please check common issues before creating an issue.

Install

$ gem install update_xcode_plugins

(if using system ruby: sudo gem install update_xcode_plugins)

(if still having problems: sudo gem install -n /usr/local/bin update_xcode_plugins #10)

Usage

In Terminal:

$ update_xcode_plugins

To use plugins on Xcode 8 and later, unsign Xcode with:

$ update_xcode_plugins --unsign

If you need to restore Xcode, use the command:

$ update_xcode_plugins --restore
Other options

For a dry run to see which plugins will be updated,

$ update_xcode_plugins --dry-run

To install the launch agent for automatically updating plugins,

$ update_xcode_plugins --install-launch-agent

or to uninstall the launch agent,

$ update_xcode_plugins --uninstall-launch-agent
Common Issues
Xcode crashes:

One or more of the plugins you are using are incompatible with your version of Xcode and are causing it to crash. The crash report will generally include the name of the responsible plugin. If unsure, start removing your plugins one by one until you find the culprit.

 

Copy from: https://github.com/inket/update_xcode_plugins

 
Leave a comment

Posted by on February 24, 2017 in iOS, Mobile Development

 

Install RabbitMQ on Windows

 

  1. Download rabbitmq at:
  2. Install
  3. Config Manangement
    • Open cmd
    • go to this path: C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.4\sbin
    • input rabbitmq-plugins.bat enable rabbitmq_management and press enter key
    • rabbitmq-service.bat stop
    • rabbitmq-service.bat install
    • rabbitmq-service.bat start
  4. Start use: http://localhost:15672
    • User: guest
    • Password: guest
  5. Crate User:
    • Add a new/fresh user, say user ‘test’ and password ‘test’
      rabbitmqctl add_user test test
    • Give administrative access to the new access
      rabbitmqctl set_user_tags test administrator
    • Set permission to newly created user
      rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
  6. How to allow Guest login via IP
    • C:\Users\[User Name]\AppData\Roaming\RabbitMQ\rabbitmq.config
    • And add: [{rabbit, [{loopback_users, []}]}]. 
 
Leave a comment

Posted by on February 14, 2017 in RabbitMQ

 

Get started with RabbitMQ on Android (Android Studio)

By: LOVISA JOHANSSON (cloudamqp)

This guide explains how to create a simple chat application in Android using Android Studio and RabbitMQ. Everyone that has the application will be able to send and receive messages from all other users that are using the same application.

If you are using Eclipse, check out this blog post instead.

In the code given, messages will first be added to an internal queue and the publisher will send messages from the internal queue to RabbitMQ when there is a connection established. The message will be added back to the queue if the connection is broken.

RabbitMQ Android

This guide assumes that you have downloaded, installed and set up everything correct for Android Studio.

Start by creating a new Android project, open Android Studio and go to File -> New -> New Project..

1. Configure your new project

  1. Enter project information as specified below.create new android project
  2. Select the form factor your app will run onandroid studio
  3. Select if you like to add an activity to your app or not. In this example we choose Blank Activity to get autogenerated files for the project.add android activity
  4. Customize the Activitycustomize android activity

2. Add Java AMQP library to project

RabbitMQ has developed an excellent Java AMQP library. The full API documentation for the library can be found here.

We need to include the RabbitMQ Java Client Library and reference the jar files into the project. In Android Studio you can create a libs folder in the same level as the app. Copy and past the jars in to this libs folder. Mark all the jar files and press “Add As Library…” as seen in the image below.

add rabbitmq library

You can confirm that the libs has been added as library by opening build.gradle and check under dependencies, all files should seen be there.

dependencies {
  ...
  compile files('libs/rabbitmq-client.jar')
  ...
}

NOTE: Only if you are using Android Gradle plugin 0.7.0 and do get the error “Duplicate files copied in APK” when you later run your application, you need to add packagingOptions to your build.gradle file as specified in here.

android {
  packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
  }
}

3. Android Manifest, internet permission

We need to tell the Android system that this app is allowed to access internet. Open the AndroidManifest.xml file, located in the root of the project. Add the user permission android.permission.INTERNET just before the closing /manifest tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cloudamqp.rabbitmq"
     android:versionCode="1"
     android:versionName="1.0">
     ......
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

4. Start coding

Layout

Create the view for the application. The .xml layout file can be found under res->layout. What we have here is a root ScrollView containing a

EditText a Button and a TextView The EditText will be used as an input field for the text that will be sent. The text will be published when the button is pressed and all messages received by the subscriber will be printed to the TextView.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  ...
  <EditText
  android:id="@+id/text"
  android:layout_width="fill_parent"
  android:background="#ffffff"
  android:hint="Enter a message" />

  <Button
  android:id="@+id/publish"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/text"
  android:text="Publish message" />

  <TextView
  android:id="@+id/textView"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/publish"
  android:textColor="#000000" />
  ...
</ScrollView>

Publish

Create an internal message queue. In this case is a BlockingDeque used. Blockingqueues implementations are designed to be used primarily for producer-consumer queues.

private BlockingDeque<String> queue = new LinkedBlockingDeque>String>();
void publishMessage(String message) {
  try {
    Log.d("","[q] " + message);
    queue.putLast(message);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}

Create a setup function for the ConnectionFactory The connection factory encapsulates a set of connection configuration parameters, in this case the CLOUDAMQP_URL. The URL can be found in the control panel for your instance.

ConnectionFactory factory = new ConnectionFactory();
private void setupConnectionFactory() {
  String uri = "IP";
  try {
    factory.setAutomaticRecoveryEnabled(false);
    //factory.setUri(uri);
    factory.setHost(uri);

  } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException e1) {
    e1.printStackTrace();
}

Create a publisher that publish messages from the internal queue. Messages are added back to the queue if an exception is catched. The publisher will try to reconnect every 5 seconds if the connection is broken.

A thread (“background” or “worker” threads or use of the AsyncTask class) is needed when we have operations to perform that are not instantaneous, such as network access when connecting to rabbitMQ.

We will use a fanout exchange. A fanout exchange routes messages to all of the queues that are bound to it and the routing key is ignored. If N queues are bound to a fanout exchange, will a new message that is published to that exchange, be copied and delivered to all N queues. Fanout exchanges are ideal for the broadcast routing of messages.

public void publishToAMQP()
{
  publishThread = new Thread(new Runnable() {
    @Override
    public void run() {
      while(true) {
        try {
          Connection connection = factory.newConnection();
          Channel ch = connection.createChannel();
          ch.confirmSelect();

          while (true) {
            String message = queue.takeFirst();
            try{
              ch.basicPublish("amq.fanout", "chat", null, message.getBytes());
              Log.d("", "[s] " + message);
              ch.waitForConfirmsOrDie();
            } catch (Exception e){
              Log.d("","[f] " + message);
              queue.putFirst(message);
              throw e;
           }
         }
       } catch (InterruptedException e) {
         break;
       } catch (Exception e) {
         Log.d("", "Connection broken: " + e.getClass().getName());
         try {
           Thread.sleep(5000); //sleep and then try again
         } catch (InterruptedException e1) {
           break;
         }
       }
     }
   }
  });
  publishThread.start();
}

Subscriber

We have now created the publisher, and it is time to create the subscriber. The subscriber will take a handler as parameter. The handler will print the messages to the screen when the messages arrives. The subscribe thread will try to reconnect every 5 seconds when the connection gets broken.

void subscribe(final Handler handler)
{
  subscribeThread = new Thread(new Runnable() {
    @Override
    public void run() {
      while(true) {
        try {
          Connection connection = factory.newConnection();
          Channel channel = connection.createChannel();
          channel.basicQos(1);
          DeclareOk q = channel.queueDeclare();
          channel.queueBind(q.getQueue(), "amq.fanout", "chat");
          QueueingConsumer consumer = new QueueingConsumer(channel);
          channel.basicConsume(q.getQueue(), true, consumer);

          while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            Log.d("","[r] " + message);
            Message msg = handler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("msg", message);
            msg.setData(bundle);
            handler.sendMessage(msg);
          }
        } catch (InterruptedException e) {
          break;
        } catch (Exception e1) {
          Log.d("", "Connection broken: " + e1.getClass().getName());
          try {
            Thread.sleep(5000); //sleep and then try again
          } catch (InterruptedException e) {
            break;
          }
        }
      }
    }
  });
  subscribeThread.start();
}

Call all functions listed above from function onCreate The handler used by the subscribe functions is also created in onCreate. A handler has to be used because it is only possible to write to the GUI from the main tread.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  setupConnectionFactory();
  publishToAMQP();
  setupPubButton();

  final Handler incomingMessageHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      String message = msg.getData().getString("msg");
      TextView tv = (TextView) findViewById(R.id.textView);
      Date now = new Date();
      SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
      tv.append(ft.format(now) + ' ' + message + '\n');
    }
  };
  subscribe(incomingMessageHandler);
}

void setupPubButton() {
  Button button = (Button) findViewById(R.id.publish);
  button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
      EditText et = (EditText) findViewById(R.id.text);
      publishMessage(et.getText().toString());
      et.setText("");
   }
  });
}

The subscribe and the publish tread can both be interrupted when the application is destroyed by adding following code in onDestroy

Thread subscribeThread;
Thread publishThread;
@Override
protected void onDestroy() {
  super.onDestroy();
  publishThread.interrupt();
  subscribeThread.interrupt();
}

 

Copy from: https://www.cloudamqp.com/blog/2015-07-29-rabbitmq-on-android.html

 

How to enable GZip compression in XAMPP server

By: TarranJones

When we test our webiste by tools.pingdom.com and we get error:

The following publicly cacheable, compressible resources should have a “Vary: Accept-Encoding” header

 

Find apache\conf\httpd.conf

uncomment the following line(remove #)

LoadModule headers_module modules/mod_deflate.so

some versions may require you to comment out the following lines instead.

LoadModule headers_module modules/mod_headers.so
LoadModule deflate_module modules/mod_deflate.so

finally add this line to your .htaccess file.

SetOutputFilter DEFLATE

Copy from: http://stackoverflow.com/questions/6993320/how-to-enable-gzip-compression-in-xampp-server

 
Leave a comment

Posted by on August 1, 2016 in XAMPP