【问题标题】:Anyway to send push notification to android without GCM?无论如何要在没有 GCM 的情况下向 android 发送推送通知?
【发布时间】:2015-03-23 11:59:10
【问题描述】:

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

【问题讨论】:

  • 题外话:谷歌控制着操作系统:P 他们已经拥有了你的所有数据
  • 用样本重新编辑了我的文章
  • 试试 Pushy (pushy.me),这是一个可靠的推送通知服务器,可以在您自己的私有网络中自行托管,以避免与任何第三方共享数据。全面披露——我创立了 Pushy。

标签: java android push-notification


【解决方案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();

        }
    });

并放置一个按钮以生成通知。并在单击通知时再显示一个 Activity。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如何通知设备?
    • 如果您必须定期从客户端检查服务器数据是否已更改,这并不是真正的 push 通知。这称为轮询
    • 是的,这叫轮询。这就是为什么异步任务被命名为 PollTask​​。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2015-04-24
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      相关资源
      最近更新 更多