Saturday, 9 January 2016

push notification

01:08

(1)first of  all go to parse.com & sign up  & then  after login  create new project inside dashboard & then  install the Sdk ..

step 1: click on Get Started with Parse Users.

step 2: click on   Hello  (push)


step 3:then  click on Android


step 4: then click on  Native (Java):


Step 5: Then Click on New Project


Step  6: then install the SDK

(2)Connect your app to Parse
·         Before continuing, select your Parse app from the menu at the right. These steps are for your "om" app.
Add your keys to your project:
public void onCreate() {
  Parse.initialize(this, "HpEfwqoy1etvFHbUyfWnVCXMY6x1776XYVF34y9v", "kCFAIXZlwjpzvCqaSeZUPXlCcQO1xPmyHclur608");
  ParseInstallation.getCurrentInstallation().saveInBackground();
}
·         Add the following service and broadcast receiver definitions to AndroidManifest.xml immediately before the closing</application> tag:
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParsePushBroadcastReceiver"
    android:exported="false">
  <intent-filter>
    <action android:name="com.parse.push.intent.RECEIVE" />
    <action android:name="com.parse.push.intent.DELETE" />
    <action android:name="com.parse.push.intent.OPEN" />
    </intent-filter>
</receiver>
<receiver android:name="com.parse.GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND">
  <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

    <!--
      IMPORTANT: Change "com.parse.starter" to match your app's package name.
    -->
    <category android:name="com.parse.starter" />
  </intent-filter>
</receiver>
·         Change the android:name attribute of <category> element above to match your application's package name.
·         Also add the permissions below, typically immediately before the opening <application> tag:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<!--
  IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
  to match your app's package name + ".permission.C2D_MESSAGE".
-->
<permission android:protectionLevel="signature"
    android:name="com.parse.starter.permission.C2D_MESSAGE" />
<uses-permission android:name="com.parse.starter.permission.C2D_MESSAGE" />
·         Change the android:name attribute in the last two lines of the snippet above to match your application's package name.
·         Compile and run!





(1)write code for   Androidmanifest.xml   file :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.parse.starter" >

    <
uses-permission android:name="android.permission.INTERNET" />
    <
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <
uses-permission android:name="android.permission.INTERNET" />
    <
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <
uses-permission android:name="android.permission.WAKE_LOCK" />
    <
uses-permission android:name="android.permission.VIBRATE" />
    <
uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <
uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

   
<!--
      IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
      to match your app's package name + ".permission.C2D_MESSAGE".
    -->
   
<permission android:protectionLevel="signature"
       
android:name="com.parse.starter.permission.C2D_MESSAGE" />
    <
uses-permission android:name="com.parse.starter.permission.C2D_MESSAGE" />

    <
application
       
android:name=".StarterApplication"
        
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:theme="@style/AppTheme" >
        <
meta-data
           
android:name="com.parse.APPLICATION_ID"
           
android:value="@string/parse_app_id" />
        <
meta-data
           
android:name="com.parse.CLIENT_KEY"
           
android:value="@string/parse_client_key" />

        <
activity
           
android:name=".MainActivity"
           
android:label="@string/app_name" >
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
        <
service android:name="com.parse.PushService" />
        <
receiver android:name="com.parse.ParsePushBroadcastReceiver"
           
android:exported="false">
            <
intent-filter>
                <
action android:name="com.parse.push.intent.RECEIVE" />
                <
action android:name="com.parse.push.intent.DELETE" />
                <
action android:name="com.parse.push.intent.OPEN" />
            </
intent-filter>
        </
receiver>
        <
receiver android:name="com.parse.GcmBroadcastReceiver"
           
android:permission="com.google.android.c2dm.permission.SEND">
            <
intent-filter>
                <
action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <
action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                
<!--
                  IMPORTANT: Change "com.parse.starter" to match your app's package name.
                -->
               
<category android:name="com.parse.starter" />
            </
intent-filter>
        </
receiver>
    </
application>

</
manifest>


(2)write code for   StarterApplication.java  file:
/*

 * Copyright (c) 2015-present, Parse, LLC.

 * All rights reserved.

 *

 * This source code is licensed under the BSD-style license found in the

 * LICENSE file in the root directory of this source tree. An additional grant

 * of patent rights can be found in the PATENTS file in the same directory.

 */

package com.parse.starter;



import android.app.Application;



import com.parse.Parse;

import com.parse.ParseACL;

import com.parse.ParseInstallation;

import com.parse.ParseUser;





public class StarterApplication extends Application {



  @Override

  public void onCreate() {

    super.onCreate();



    // Enable Local Datastore.

    Parse.enableLocalDatastore(this);



    // Add your initialization code here

    Parse.initialize(this, "HpEfwqoy1etvFHbUyfWnVCXMY6x1776XYVF34y9v", "kCFAIXZlwjpzvCqaSeZUPXlCcQO1xPmyHclur608");

    ParseInstallation.getCurrentInstallation().saveInBackground();



    ParseUser.enableAutomaticUser();

    ParseACL defaultACL = new ParseACL();

    // Optionally enable public read access.

    // defaultACL.setPublicReadAccess(true);

    ParseACL.setDefaultACL(defaultACL, true);

  }

}

(3)write  code for  MainActivity.java  file:
/*

 * Copyright (c) 2015-present, Parse, LLC.

 * All rights reserved.

 *

 * This source code is licensed under the BSD-style license found in the

 * LICENSE file in the root directory of this source tree. An additional grant

 * of patent rights can be found in the PATENTS file in the same directory.

 */

package com.parse.starter;



import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;



import com.parse.ParseAnalytics;





public class MainActivity extends AppCompatActivity {



  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);





    ParseAnalytics.trackAppOpenedInBackground(getIntent());

  }



  @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 boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will

    // automatically handle clicks on the Home/Up button, so long

    // as you specify a parent activity in AndroidManifest.xml.

    int id = item.getItemId();



    //noinspection SimplifiableIfStatement

    if (id == R.id.action_settings) {

      return true;

    }



    return super.onOptionsItemSelected(item);

  }

}


(4)write  code for activity_main.xml file :
<!--

  ~ Copyright (c) 2015-present, Parse, LLC.

  ~ All rights reserved.

  ~

  ~ This source code is licensed under the BSD-style license found in the

  ~ LICENSE file in the root directory of this source tree. An additional grant

  ~ of patent rights can be found in the PATENTS file in the same directory.

  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

                xmlns:tools="http://schemas.android.com/tools"

                android:layout_width="match_parent"

                android:layout_height="match_parent"

                android:paddingLeft="@dimen/activity_horizontal_margin"

                android:paddingRight="@dimen/activity_horizontal_margin"

                android:paddingTop="@dimen/activity_vertical_margin"

                android:paddingBottom="@dimen/activity_vertical_margin"

                tools:context=".MainActivity">



    <TextView

        android:text="@string/hello_world"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"/>



</RelativeLayout>

& finally test your android  apps  click on test sdk :

========================================================================================================================================================================================================================Now start  to how you can  make user registered .....

First of all  Get  Parse Applciation ID, Client Key & parse-x.x.x.jar
To integrate parse in your app, you need Application ID, Client Key and parse jar library. Follow the below steps to get your app keys.
1. Sign Up by entering the details required.
2. Create a new parse app.
3. Once the app is created, go to Settings of the app and grab the Application ID and Client Key.
4. Download latest version of parse-1.9.2.jar. This library contains necessary functions to interact with parse API.
 see below directory structure and proceed for coding part...



(1)step   one: create  activity package :
Now write code for   LoginActivity.java file:
package info.androidhive.parsenotifications.activity;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import info.androidhive.parsenotifications.R;
import info.androidhive.parsenotifications.app.AppConfig;
import info.androidhive.parsenotifications.helper.ParseUtils;
import info.androidhive.parsenotifications.helper.PrefManager;

public class LoginActivity extends ActionBarActivity implements View.OnClickListener {

   
private EditText inputEmail;
   
private Button btnLogin;
   
private PrefManager pref;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);

       
// Verifying parse configuration. This is method is for developers only.
       
ParseUtils.verifyParseConfiguration(this);

       
pref = new PrefManager(getApplicationContext());
       
if (pref.isLoggedIn()) {
            Intent intent =
new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);

            finish();
        }

        setContentView(R.layout.
activity_login);

       
inputEmail = (EditText) findViewById(R.id.email);
       
btnLogin = (Button) findViewById(R.id.btnLogin);

       
btnLogin.setOnClickListener(this);
    }


   
private void login() {
        String email =
inputEmail.getText().toString();

       
if (isValidEmail(email)) {

           
pref.createLoginSession(email);

            Intent intent =
new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);

            finish();
        }
else {
            Toast.makeText(getApplicationContext(),
"Please enter valid email address!", Toast.LENGTH_LONG).show();
        }
    }

   
public final static boolean isValidEmail(CharSequence target) {
       
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }

   
@Override
   
public void onClick(View v) {
       
switch (v.getId()) {
           
case R.id.btnLogin:
                login();
               
break;
           
default:
        }
    }
}

(2)write code for  MainActivity.java  file :
package info.androidhive.parsenotifications.activity;



import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.Toolbar;

import android.text.format.DateUtils;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ListView;

import android.widget.TextView;



import java.util.ArrayList;

import java.util.List;



import info.androidhive.parsenotifications.R;

import info.androidhive.parsenotifications.helper.ParseUtils;

import info.androidhive.parsenotifications.helper.PrefManager;

import info.androidhive.parsenotifications.model.Message;





public class MainActivity extends AppCompatActivity {



    private static String TAG = MainActivity.class.getSimpleName();



    private Toolbar mToolbar;

    private ListView listView;

    private List<Message> listMessages = new ArrayList<>();

    private MessageAdapter adapter;

    private PrefManager pref;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        listView = (ListView) findViewById(R.id.list_view);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);



        setSupportActionBar(mToolbar);

        getSupportActionBar().setDisplayShowHomeEnabled(true);



        adapter = new MessageAdapter(this);

        pref = new PrefManager(getApplicationContext());



        listView.setAdapter(adapter);



        Intent intent = getIntent();



        String email = pref.getEmail();



        if (email != null) {

            ParseUtils.subscribeWithEmail(pref.getEmail());

        }else{

            Log.e(TAG, "Email is null. Not subscribing to parse!");

        }

    }



    @Override

    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);

        String message = intent.getStringExtra("message");



        Message m = new Message(message, System.currentTimeMillis());

        listMessages.add(0, m);

        adapter.notifyDataSetChanged();

    }



    private class MessageAdapter extends BaseAdapter {



        LayoutInflater inflater;



        public MessageAdapter(Activity activity) {

            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }



        @Override

        public int getCount() {

            return listMessages.size();

        }



        @Override

        public Object getItem(int position) {

            return listMessages.get(position);

        }



        @Override

        public long getItemId(int position) {

            return position;

        }



        @Override

        public View getView(int position, View convertView, ViewGroup parent) {

            View view = convertView;

            if (view == null) {

                view = inflater.inflate(R.layout.list_row, null);

            }



            TextView txtMessage = (TextView) view.findViewById(R.id.message);

            TextView txtTimestamp = (TextView) view.findViewById(R.id.timestamp);



            Message message = listMessages.get(position);

            txtMessage.setText(message.getMessage());



            CharSequence ago = DateUtils.getRelativeTimeSpanString(message.getTimestamp(), System.currentTimeMillis(),

                    0L, DateUtils.FORMAT_ABBREV_ALL);



            txtTimestamp.setText(String.valueOf(ago));



            return view;

        }

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }



    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();



        //noinspection SimplifiableIfStatement

        if (id == R.id.action_logout) {

            pref.logout();

            Intent intent = new Intent(MainActivity.this, LoginActivity.class);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            startActivity(intent);

            finish();

            return true;

        }



        return super.onOptionsItemSelected(item);

    }

}


Step 2: create package  app:
(1)write code for  AppConfig.java file:
package info.androidhive.parsenotifications.app;



/**

 * Created by om on 01/06/16.

 */

public class AppConfig {

    public static final String PARSE_CHANNEL = "AndroidHive";

    public static final String PARSE_APPLICATION_ID = "HpEfwqoy1etvFHbUyfWnVCXMY6x1776XYVF34y9v";

    public static final String PARSE_CLIENT_KEY = "kCFAIXZlwjpzvCqaSeZUPXlCcQO1xPmyHclur608";

    public static final int NOTIFICATION_ID = 100;

}

(2)write code for  MyApplication.java :
package info.androidhive.parsenotifications.app;





import android.app.Application;



import info.androidhive.parsenotifications.helper.ParseUtils;



public class MyApplication extends Application {



    private static MyApplication mInstance;



    @Override

    public void onCreate() {

        super.onCreate();

        mInstance = this;



        // register with parse

        ParseUtils.registerParse(this);

    }





    public static synchronized MyApplication getInstance() {

        return mInstance;

    }

}

Step 3: now create package  helper:
(1)now write code for  NotificationUtils.java :

package info.androidhive.parsenotifications.helper;



import android.app.ActivityManager;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.graphics.BitmapFactory;

import android.media.RingtoneManager;

import android.os.Build;

import android.support.v4.app.NotificationCompat;

import android.text.TextUtils;

import android.widget.Toast;



import java.util.List;



import info.androidhive.parsenotifications.R;

import info.androidhive.parsenotifications.activity.MainActivity;

import info.androidhive.parsenotifications.app.AppConfig;



/**

 * Created by om on 01/06/16.

 */

public class NotificationUtils {



    private String TAG = NotificationUtils.class.getSimpleName();



    private Context mContext;



    public NotificationUtils() {

    }



    public NotificationUtils(Context mContext) {

        this.mContext = mContext;

    }



    public void showNotificationMessage(String title, String message, Intent intent) {



        // Check for empty push message

        if (TextUtils.isEmpty(message))

            return;



        if (isAppIsInBackground(mContext)) {

            // notification icon

            int icon = R.mipmap.ic_launcher;



            int smallIcon = R.drawable.ic_push;



            int mNotificationId = AppConfig.NOTIFICATION_ID;



            PendingIntent resultPendingIntent =

                    PendingIntent.getActivity(

                            mContext,

                            0,

                            intent,

                            PendingIntent.FLAG_CANCEL_CURRENT

                    );



            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();



            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(

                    mContext);

            Notification notification = mBuilder.setSmallIcon(smallIcon).setTicker(title).setWhen(0)

                    .setAutoCancel(true)

                    .setContentTitle(title)

                    .setStyle(inboxStyle)

                    .setContentIntent(resultPendingIntent)

                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))

                    .setContentText(message)

                    .build();



            NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(mNotificationId, notification);

        } else {

            intent.putExtra("title", title);

            intent.putExtra("message", message);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            mContext.startActivity(intent);

        }

    }



    /**

     * Method checks if the app is in background or not

     *

     * @param context

     * @return

     */

    public static boolean isAppIsInBackground(Context context) {

        boolean isInBackground = true;

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {

            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();

            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {

                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {

                    for (String activeProcess : processInfo.pkgList) {

                        if (activeProcess.equals(context.getPackageName())) {

                            isInBackground = false;

                        }

                    }

                }

            }

        } else {

            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

            ComponentName componentInfo = taskInfo.get(0).topActivity;

            if (componentInfo.getPackageName().equals(context.getPackageName())) {

                isInBackground = false;

            }

        }



        return isInBackground;

    }

}

(2)now write code for  ParseUtils.java:

package info.androidhive.parsenotifications.helper;



import android.app.Activity;

import android.content.Context;

import android.text.TextUtils;

import android.util.Log;

import android.widget.Toast;



import com.parse.Parse;

import com.parse.ParseException;

import com.parse.ParseInstallation;

import com.parse.ParsePush;

import com.parse.SaveCallback;



import info.androidhive.parsenotifications.app.AppConfig;



/**

 * Created by om on 01/06/16.

 */

public class ParseUtils {



    private static String TAG = ParseUtils.class.getSimpleName();



    public static void verifyParseConfiguration(Context context) {

        if (TextUtils.isEmpty(AppConfig.PARSE_APPLICATION_ID) || TextUtils.isEmpty(AppConfig.PARSE_CLIENT_KEY)) {

            Toast.makeText(context, "Please configure your Parse Application ID and Client Key in AppConfig.java", Toast.LENGTH_LONG).show();

            ((Activity) context).finish();

        }

    }



    public static void registerParse(Context context) {

        // initializing parse library

        Parse.initialize(context, AppConfig.PARSE_APPLICATION_ID, AppConfig.PARSE_CLIENT_KEY);

        ParseInstallation.getCurrentInstallation().saveInBackground();



        ParsePush.subscribeInBackground(AppConfig.PARSE_CHANNEL, new SaveCallback() {

            @Override

            public void done(ParseException e) {

                Log.e(TAG, "Successfully subscribed to Parse!");

            }

        });

    }



    public static void subscribeWithEmail(String email) {

        ParseInstallation installation = ParseInstallation.getCurrentInstallation();



        installation.put("email", email);



        installation.saveInBackground();



        Log.e(TAG, "Subscribed with email: " + email);

    }

}

(3)now write code for  PrefManager.java file:
package info.androidhive.parsenotifications.helper;



import android.content.Context;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;



/**

 * Created by om on 01/06/16..

 */

public class PrefManager {

    // Shared Preferences

    SharedPreferences pref;



    // Editor for Shared preferences

    Editor editor;



    // Context

    Context _context;



    // Shared pref mode

    int PRIVATE_MODE = 0;



    // Shared pref file name

    private static final String PREF_NAME = "AndroidHive";



    // All Shared Preferences Keys

    private static final String IS_LOGIN = "IsLoggedIn";



    // Email address (make variable public to access from outside)

    public static final String KEY_EMAIL = "email";



    // Constructor

    public PrefManager(Context context) {

        this._context = context;

        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

        editor = pref.edit();

    }



    /**

     * Create login session

     */

    public void createLoginSession(String email) {

        // Storing login value as TRUE

        editor.putBoolean(IS_LOGIN, true);



        // Storing email in pref

        editor.putString(KEY_EMAIL, email);



        // commit changes

        editor.commit();

    }



    public String getEmail() {

        return pref.getString(KEY_EMAIL, null);

    }



    public boolean isLoggedIn() {

        return pref.getBoolean(IS_LOGIN, false);

    }



    public void logout() {

        editor.clear();

        editor.commit();

    }

}


step 4: now create package  model:
(1)write code for  Message.java file:
package info.androidhive.parsenotifications.model;



/**

 * Created by om on 01/06/16.

 */

public class Message {

    private String message;

    private long timestamp;



    public Message() {

    }



    public Message(String message, long timestamp) {

        this.message = message;

        this.timestamp = timestamp;

    }



    public String getMessage() {

        return message;

    }



    public void setMessage(String message) {

        this.message = message;

    }



    public long getTimestamp() {

        return timestamp;

    }



    public void setTimestamp(long timestamp) {

        this.timestamp = timestamp;

    }

}

step   5: now create package  receiver   
(1)    Now write code for CustomPushReceiver.java file:
package info.androidhive.parsenotifications.receiver;



import android.content.Context;

import android.content.Intent;

import android.util.Log;



import com.parse.ParsePushBroadcastReceiver;



import org.json.JSONException;

import org.json.JSONObject;



import info.androidhive.parsenotifications.activity.MainActivity;

import info.androidhive.parsenotifications.helper.NotificationUtils;



/**

 * Created by om on 01/06/16.

 */

public class CustomPushReceiver extends ParsePushBroadcastReceiver {

    private final String TAG = CustomPushReceiver.class.getSimpleName();



    private NotificationUtils notificationUtils;



    private Intent parseIntent;



    public CustomPushReceiver() {

        super();

    }



    @Override

    protected void onPushReceive(Context context, Intent intent) {

        super.onPushReceive(context, intent);



        if (intent == null)

            return;



        try {

            JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));



            Log.e(TAG, "Push received: " + json);



            parseIntent = intent;



            parsePushJson(context, json);



        } catch (JSONException e) {

            Log.e(TAG, "Push message json exception: " + e.getMessage());

        }

    }



    @Override

    protected void onPushDismiss(Context context, Intent intent) {

        super.onPushDismiss(context, intent);

    }



    @Override

    protected void onPushOpen(Context context, Intent intent) {

        super.onPushOpen(context, intent);

    }



    /**

     * Parses the push notification json

     *

     * @param context

     * @param json

     */

    private void parsePushJson(Context context, JSONObject json) {

        try {

            boolean isBackground = json.getBoolean("is_background");

            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");

            String message = data.getString("message");



            if (!isBackground) {

                Intent resultIntent = new Intent(context, MainActivity.class);

                showNotificationMessage(context, title, message, resultIntent);

            }



        } catch (JSONException e) {

            Log.e(TAG, "Push message json exception: " + e.getMessage());

        }

    }





    /**

     * Shows the notification message in the notification bar

     * If the app is in background, launches the app

     *

     * @param context

     * @param title

     * @param message

     * @param intent

     */

    private void showNotificationMessage(Context context, String title, String message, Intent intent) {



        notificationUtils = new NotificationUtils(context);



        intent.putExtras(parseIntent.getExtras());



        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);



        notificationUtils.showNotificationMessage(title, message, intent);

    }

}


now   under  res/layout folder:
(1)write code for activity_main.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">



    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:orientation="vertical">



        <include

            android:id="@+id/toolbar"

            layout="@layout/toolbar" />

    </LinearLayout>



    <ListView

        android:id="@+id/list_view"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"></ListView>



</LinearLayout>


(2)write  code for  activity_login.xml   file  :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#ffffff"

    tools:context="info.androidhive.parsenotifications.activity.LoginActivity">



    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:gravity="center"

        android:orientation="vertical"

        android:paddingBottom="10dp"

        android:paddingTop="10dp">



        <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:fontFamily="sans-serif-light"

            android:gravity="center_horizontal"

            android:text="Parse Notifications"

            android:textColor="#218eed"

            android:textSize="24dp" />



        <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_marginBottom="20dp"

            android:fontFamily="sans-serif-light"

            android:gravity="center_horizontal"

            android:paddingLeft="20dp"

            android:paddingRight="20dp"

            android:text="Enter your email address to subscribe to parse channel!"

            android:textColor="#9d9d9d"

            android:textSize="16dp" />



        <EditText

            android:id="@+id/email"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_marginLeft="40dp"

            android:layout_marginRight="40dp"

            android:background="@android:color/white"

            android:hint="Your email address"

            android:gravity="center_horizontal"

            android:inputType="textEmailAddress"

            android:padding="10dp"

            android:textColor="#444444"

            android:textColorHint="#888888"

            android:textSize="18dp" />



        <View

            android:layout_width="fill_parent"

            android:layout_height="1dp"

            android:layout_marginLeft="40dp"

            android:layout_marginRight="40dp"

            android:background="#dedede"/>



        <Button

            android:id="@+id/btnLogin"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_marginLeft="40dp"

            android:layout_marginRight="40dp"

            android:layout_marginTop="20dp"

            android:background="#218eed"

            android:text="Login"

            android:textColor="@android:color/white" />

    </LinearLayout>





</RelativeLayout>

(3)write code for list_row.xml file:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">



    <TextView

        android:id="@+id/message"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:paddingBottom="5dp"

        android:paddingLeft="10dp"

        android:paddingRight="10dp"

        android:paddingTop="10dp"

        android:textSize="16dp" />



    <TextView

        android:id="@+id/timestamp"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:paddingBottom="15dp"

        android:paddingLeft="10dp"

        android:paddingRight="10dp"

        android:textColor="#666666" />



</LinearLayout>

(4)Now   write   code   for  toolbar.xml file:
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:local="http://schemas.android.com/apk/res-auto"

    android:id="@+id/toolbar"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="?attr/colorPrimary"

    android:minHeight="?attr/actionBarSize"

    local:popupTheme="@style/ThemeOverlay.AppCompat.Light"

    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

 output :


Download  the whole code  from  ParseNotifications.zip 

Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 ANDROID TRAINING IN MUMBAI BY OM SIR. All rights resevered. Designed by Templateism

Back To Top