人人均可以作推送

先來張圖先java

相信不少人想知道,相似微信,扣扣,或者網易新聞的消息推送是怎樣實現的,對於初學者來講,可能感受只能「遠觀而不可褻玩焉」,或者說,想作,可是不知道怎麼作、怎麼實現,那麼,在這裏,恭喜你,即便你是初學者,知道四大組件,那麼你也能夠作推送啦。有木有很激動~android

首先呢,推送咱們要用到第三方,那麼推送的第三方有不少,好比bmob推送啊,極光推送啊等等,在這裏就很少介紹第三方的推送包啦,那麼,在這裏我就選擇bmob推送來給你們講解怎麼實現推送,相對來講仍是比較簡單易懂的。web

首先咱們先去Bmob官網註冊一個賬號,註冊很簡單的,郵箱密碼就能夠了, 而後建立應用,固然,bmob有不少功能,好比移動雲數據庫、雲代碼,聊天組件和支付組件等等,這些我就不說了,有興趣的本身看相關內容或者文檔吧,咱們直接跳到推送這一塊。數據庫

首先,咱們新建一個安卓項目,將安卓的包名保存到你的bmob雲服務器上。json

對於初學者來講,可能包名不知道是哪一個,致使錯誤(不是初學者可跳過),就在AndroidManifest.xml中查看複製黏貼就好了。服務器

好的,目前,咱們的後臺開發工做搞定,沒啥的。下面就給你們看看我作的推送的效果微信

 

首先推送的數據是json數據,若是你看過代碼後,你就明白他的原理了,其實,就是經過廣播監聽,若是監聽到了廣播,就接受廣播出來的信息,而這個信息就是咱們要的json數據。網絡

那麼我首先把Bmob的sdk和Push的jar包下載拷貝到libs目錄中,而後,添加權限:app

     <permission android:protectionLevel="normal" android:name="cn.bmob.permission.push"></permission>
    <uses-permission android:name="cn.bmob.permission.push"/><!-- 添加自定義的權限-->
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />    
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />

 而後配置清單文件:ide

        <service
               android:label="PushService"
            android:name="cn.bmob.push.lib.service.PushService"
            android:process="cn.bmob.push"
            android:permission="cn.bmob.permission.push"
            android:exported="true">
             <intent-filter>
                 <action android:name="cn.bmob.push.lib.service.PushService"/>
             </intent-filter>
        </service>
        <receiver android:name="cn.bmob.push.PushReceiver" >
            <intent-filter android:priority="2147483647" ><!--優先級加最高-->
                <!-- 系統啓動完成後會調用 -->
                <action android:name="android.intent.action.BOOT_COMPLETED" />               
                <!-- 解鎖完成後會調用 -->
                <action android:name="android.intent.action.USER_PRESENT" />
                <!-- 監聽網絡連通性 -->
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />               
            </intent-filter>
        </receiver>
    
        <receiver android:name="cn.bmober.bmob_push_demo.MyPushMessageReceiver">
            <intent-filter >
                <action android:name="cn.bmob.push.action.MESSAGE"/>
            </intent-filter>
        </receiver>

 咱們在清單文件能夠看到cn.bmober.bmob_push_demo.MyPushMessageReceiver,這個是咱們本身寫的廣播接收者,用於廣播接收推送內容,這個類有個cn.bmob.push.action.MESSAGE內容的action屬性,這個是必定要定義的,這個廣播接收的匹配條件,沒有這個action是得不到json數據的。

而後咱們經過intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING)接受服務端發過來的推送數據,獲得數據後,我就定義通知Notification,通知用戶有新內容:

 public static final int ID = 1001;
 private NotificationManager mNotification;
 private Notification notification;
 private Map<String, String> myMap;
  public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
   
   myMap = parseJson(intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING));
   
   String alert = myMap.get("alert");
   String title = myMap.get("title");
   String message = myMap.get("message");
   String website = myMap.get("website");
   
   mNotification = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
   notification = new Notification();
   notification.icon = R.drawable.bmob;
   notification.tickerText = alert;
   notification.when = System.currentTimeMillis();
   Intent i = new Intent(context, NotificationAcitvity.class);
   i.putExtra("website", website);
   PendingIntent pIntent = PendingIntent.getActivity(context, 0, i,PendingIntent.FLAG_UPDATE_CURRENT);
   notification.setLatestEventInfo(context, title, message, pIntent);
   mNotification.notify(ID, notification);
  }

 在上面咱們有個parseJson(String json)的方法,這個本身寫的解析json數據的方法,也沒什麼技術含量,就直接上代碼了:

 /**
  * 解析推送過來的json數據
  * 
  * @param json
  * @return
  */
 private Map<String, String> parseJson(String json) {
  Map<String, String> map = new HashMap<String, String>();
  try {
   JSONObject jsonObject = new JSONObject(json);
   map.put("alert", jsonObject.getString("alert"));
   map.put("title", jsonObject.getString("title"));
   map.put("message", jsonObject.getString("message"));
   map.put("website", jsonObject.getString("website"));
  } catch (Exception e) {
   // TODO Auto-generated catch block
   throw new RuntimeException(e);
  }
  return map;
 }

好啦。如今咱們得定義NotificationAcitvity.java這個activity,在這個項目中,我就直接打開i推送發過來的網址了,沒有作太多複雜的功能。若是推送你公司的活動,就能夠發送該活動的網址,若是你的相似於下載助手那樣推薦遊戲或者app,那麼就能夠直接跳到app下載頁面了。若是你要實現更加有意思的功能,那麼就本身好好想一想啦。

 private NotificationManager notificationMan;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.notification);
  notificationMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  notificationMan.cancel(MyPushMessageReceiver.ID);
  Intent intent = getIntent();
  String website = intent.getStringExtra("website");  
  Uri uri = Uri.parse(website);
  startActivity(new Intent(Intent.ACTION_VIEW,uri));
  
 }

固然,bmob還能夠經過代碼實現推送任務,這樣的話,咱們就能夠作個手機服務器端,直接編寫json數據發送也能夠達到同樣的效果,就不須要必定要登陸bmob雲端服務器才能推送數據了,沒什麼好說的,直接上代碼把。

在oncreate中初始化bmob

     // 初始化BmobSDK
      Bmob.initialize(this, APPID);
     // 使用推送服務時的初始化操做
      MyInstallation.getCurrentInstallation(this).save();
     // 啓動推送服務
      BmobPush.startWork(this, APPID);     
     // 建立推送消息的對象
      bmobPushManager = new BmobPushManager(this);
  public void onClick(View v) {
  // TODO Auto-generated method stub
  String pushJsonStr = "{\"alert\":\"嚇到我了\",\"title\":\"好大的驚喜呀\",\"message\":\"分享bmob,贈送iPhone 6 plus\",\"website\":\"http://www.bmob.cn\"}";
  JSONObject jsonObject = null;
  try {
   jsonObject = new JSONObject(pushJsonStr);
  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  switch (v.getId()) {
  case R.id.btn_sendAll:
   // 推送一條消息給全部安裝此應用的設備
   bmobPushManager.pushMessageAll(jsonObject);
   break;
  case R.id.btn_sendMsgToAndroid:
   // 建立Installation表的BmobQuery對象
   BmobQuery<BmobInstallation> query = BmobInstallation.getQuery();
   // 並添加條件爲設備類型屬於android
   query.addWhereEqualTo("deviceType", "android");
   // 設置推送條件給bmobPushManager對象。
   bmobPushManager.setQuery(query);
   // 設置推送消息,服務端會根據上面的查詢條件,來進行推送這條消息
   bmobPushManager.pushMessage(jsonObject);
   break;
  default:
   break;
  }
 }

看完以後是否是以爲其實推送也不過如此呀?是的,其實推送這一塊沒什麼難點,基本知道四大組件就能夠作推送這個模塊了。至於想經過推送達到什麼樣的效果,那就得看你的想象和你的實現能力了。

好啦,最好但願寫的推送這邊文章對大家有幫助。

相關文章
相關標籤/搜索