user4596833
user4596833

Reputation:

Anyway to send push notification to android without GCM?

Is there any other way to send push notifications to android device from server without using GCM? I don't want to share my device data or anything with 3rd party like Google? So any other way?

Upvotes: 2

Views: 3913

Answers (3)

Preetam Yadav
Preetam Yadav

Reputation: 11

You may try this code for simple push notification without using GCM or FCM.

Update the changes in onCreateView method..

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

   /* ed1=(EditText)findViewById(R.id.editText);
    ed2=(EditText)findViewById(R.id.editText2);
    ed3=(EditText)findViewById(R.id.editText3);*/
    Button b1=(Button)findViewById(R.id.button);

    b1.setOnClickListener(new View.OnClickListener() {
        public int mNotificationId;

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onClick(View v) {

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.msg)
                            .setContentTitle("My notification")
                            .setContentText("Hello Preetam! How are you");
            Intent resultIntent = new Intent(getApplicationContext(), Result_Activity.class);


            TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
            stackBuilder.addParentStack(Result_Activity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent =
                    stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

            mBuilder.setContentIntent(resultPendingIntent);
            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            mNotificationManager.notify(mNotificationId, mBuilder.build());
            Toast.makeText(getApplicationContext(),"Check your notification",Toast.LENGTH_SHORT).show();

        }
    });

And Put a button to generate the notification.And make one more Activity to be displayed on clicking the notification.

Upvotes: 1

jb15613
jb15613

Reputation: 359

I use a ftp library to connect to my server. in my notification service, I scan a directory where I keep plain text files. Each one represents a notification. If a new text file is added, the service gets the date the file was added to the server. If it was today, it reads the file, returns the contents, and I put it into a notification.

Here is an example of a service that looks for a text file with today's date as the title. If it exists, it will parse the data and put it into a notification

public class NotifyService extends Service {


private WakeLock mWakeLock;

/**
 * Simply return null, since our Service will not be communicating with
 * any other components. It just does its work silently.
 */
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@SuppressWarnings("deprecation")
private void handleIntent() {
    // obtain the wake lock
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Partial");
    mWakeLock.acquire();

    // check the global background data setting
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    if (!cm.getBackgroundDataSetting()) {
        stopSelf();
        return;
    }

    // do the actual work, in a separate thread
    new PollTask().execute();
}

private class PollTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... args) {
        // do stuff!
        String title = null;
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int year = c.get(Calendar.YEAR);
        String Month = (String.valueOf(month));
        String Day = (String.valueOf(day));
        String Year = (String.valueOf(year));
        String todaysDate = (Month + "-" + Day + "-" + Year);

            try {
                // Create a URL for the desired page
                URL updateURL = new URL("URL to your notification directory" + todaysDate + ".txt");

                // Read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(updateURL.openStream()));
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    total.append(line).append("\n");
                }
                title = total.toString();

                in.close();

            } catch (IOException e) {
                e.printStackTrace();
            }


        return title;

    }

    /**
     * In here you should interpret whatever you fetched in doInBackground
     * and push any notifications you need to the status bar, using the
     * NotificationManager. I will not cover this here, go check the docs on
     * NotificationManager.
     *
     * What you HAVE to do is call stopSelf() after you've pushed your
     * notification(s). This will:
     * 1) Kill the service so it doesn't waste precious resources
     * 2) Call onDestroy() which will release the wake lock, so the device
     *    can go to sleep again and save precious battery.
     */
    @Override
    protected void onPostExecute(String title) {
        int mId = 420;
        if (title == null) {
            stopSelf();
        }else{

            Intent notificationIntent = new Intent(getApplicationContext(), MapActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(NotifyService.this, 0, notificationIntent, 0);

            //Set up the notification

            Notification noti = new NotificationCompat.Builder(getApplicationContext()).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                    .setSmallIcon(R.drawable.ic_launcher_small)
                    .setTicker("New Notification ...")
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle("Your app name")
                    .setContentText(title)
                    .setContentIntent(contentIntent)
                            //At most three action buttons can be added
                            //.addAction(android.R.drawable.ic_menu_camera, "Action 1", contentIntent)
                            //.addAction(android.R.drawable.ic_menu_compass, "Action 2", contentIntent)
                            //.addAction(android.R.drawable.ic_menu_info_details, "Action 3", contentIntent)
                    .setAutoCancel(true).build();

            //Show the notification
            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(mId, noti);
            // handle your data
            stopSelf();
        }
    }
}

/**
 * This is deprecated, but you have to implement it if you're planning on
 * supporting devices with an API level lower than 5 (Android 2.0).
 */
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
    handleIntent();
}

/**
 * This is called on 2.0+ (API level 5 or higher). Returning
 * START_NOT_STICKY tells the system to not restart the service if it is
 * killed because of poor resource (memory/cpu) conditions.
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleIntent();
    return START_NOT_STICKY;
}

/**
 * In onDestroy() we release our wake lock. This ensures that whenever the
 * Service stops (killed for resources, stopSelf() called, etc.), the wake
 * lock will be released.
 */
public void onDestroy() {
    super.onDestroy();
    mWakeLock.release();
}
}

Upvotes: 0

breakline
breakline

Reputation: 6073

If you mean by targeting devices but without direct connection there is no really other way. If its just a text you can send a simple sms message but if you want a clickable notification GCMS is the only way for now.

Upvotes: 0

Related Questions