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

Anyway to send push notification to android without GCM?

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

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

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

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

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

您可以在不使用 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();

        }
    });

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