无论如何在没有GCM的情况下向Android发送推送通知?

时间:2015-03-23 11:59:11

标签: java android push-notification

有没有其他方法可以在不使用GCM的情况下从服务器向Android设备发送推送通知?我不想与Google等第三方分享我的设备数据或任何内容?那么还有其他方式吗?

3 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码进行简单的推送通知,而无需使用GCM或FCM。

更新onCreateView方法中的更改..

@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();

        }
    });

然后按一个按钮生成通知。点击通知后再显示一个活动。

答案 1 :(得分:0)

我使用ftp库连接到我的服务器。在我的通知服务中,我扫描一个保存纯文本文件的目录。每个代表一个通知。如果添加了新文本文件,则服务将获取将文件添加到服务器的日期。如果是今天,它会读取文件,返回内容,然后将其放入通知中。

以下是一个服务示例,该服务查找以今天的日期为标题的文本文件。如果存在,它将解析数据并将其放入通知

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();
}
}

答案 2 :(得分:0)

如果您的意思是定位设备但没有直接连接,则没有其他方法。如果它只是一个文本,你可以发送一个简单的短信,但如果你想要一个可点击的通知GCMS是目前唯一的方法。