天天看點

Bmob 推送功能Demo

這個Demo使用Bmob實作了一個小的推送功能 ,順便整理下學過的知識.

初始化Bmob請看這篇文章

Bmob的簡單應用 — HelloWorld

Bmob推送功能簡介

通過雲推送,你可以随時随地的向應用程式的使用者推送通知或消息,與使用者保持積極互動提升使用者留存率,活躍度和使用者體驗度。

Bmob配置

  • 先下載下傳推送SDK,後将jar包放在libs目錄下,然後添加到項目,ADT和AS配置過程一樣.
  • 添權重限
<!-- BmobSDK所需的權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!--推送所需的權限-->
    <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
           
  • 配置Bmob的Service和BroadCast
<service
       android:label="PushService"
    android:name="cn.bmob.push.lib.service.PushService"
    android:process="cn.bmob.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><!--優先級加最高-->
          <!-- 系統啟動完成後會調用 -->
          <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>
           

這些都是文檔上的内容,可以從官網上檢視,Bmob使用一種心跳機制維持Socket的長連接配接,即每次定時會發送自定義結構體進行保活.

初始化Bmob及推送

/**
 * Created by yangtianrui on 16-6-10.
 * 初始化Bmob
 */
public class BaseActivity extends AppCompatActivity {
    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        // 初始化BmobSDK
        Bmob.initialize(this, "887fb8cdafa392424a938a99673a1388");
        // 使用推送服務時的初始化操作
        BmobInstallation.getCurrentInstallation(this).save();
        // 啟動推送服務
        BmobPush.startWork(this);
        // 向服務端發送推送請求,手動進行推送
//        BmobPushManager manager = new BmobPushManager(this);
//        manager.pushMessage("test");
        return super.onCreateView(name, context, attrs);
    }
}
           

自定義廣播接收Bmob推送

/**
 * Created by yangtianrui on 16-6-10.
 * 接收Bmob發出的推送
 */
public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
            // 收到廣播時,發送一個通知
            String jsonStr = intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING);
            String content = null;
            try {
                // 處理JSON
                JSONObject jsonObject = new JSONObject(jsonStr);
                content = jsonObject.getString("alert");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            Notification notify = new Notification.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("收到一條推送")
                    .setContentText(content)
                    .build();
            manager.notify(, notify);
        }
    }
}
           

此處intent.getAction().equals(PushConstants.ACTION_MESSAGE即為收到的通知,使用廣播對收到的資訊進行過濾,解析出推送的消息.

ManiFest檔案中配置

<!-- 自定義消息接收器,對收到的消息進行處理 -->
        <receiver android:name=".MyReceiver">
            <intent-filter >
                <action android:name="cn.bmob.push.action.MESSAGE"/>
            </intent-filter>
        </receiver>
           

現在就可以在背景進行推送了

Bmob 推送功能Demo

模拟機上看到的結果

Bmob 推送功能Demo

順便整理下Notification的知識吧

  • API 16 以上使用Notification.Builder構造通知對象
  • 使用NotificationManager發送通知,該對象從SystemService中擷取
  • 構造Notification對象
  • 使用PendingIntent建立點選時響應

一個簡單的通知DEMO

public void text_notify(View view) {
        // 擷取系統通知對象
        // 用于推送通知
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 使用PendingIntent延時執行Intent
        PendingIntent intent = PendingIntent.getActivity(this, , new Intent(this, MainActivity.class), );
        // 使用Builder構造通知對象
        Notification notify = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher) // 必須設定圖檔,否則無法正常推送
                .setContentInfo("Message Content")
                .setTicker("This is Ticker") // 直接在标題欄裡顯示的通知
                .setContentTitle("Content Title")
                .setContentIntent(intent)  // 點選事件
                .setOngoing(false) // 允許使用者删除
//                .setNumber(1)
                .build();
        // 不會自動消失
        // notify.flags |= Notification.FLAG_NO_CLEAR;
        // FLAG的一些熟悉
        //FLAG_AUTO_CANCEL   該通知能被狀态欄的清除按鈕給清除掉
        //FLAG_NO_CLEAR      該通知不能被狀态欄的清除按鈕給清除掉
        //FLAG_ONGOING_EVENT 通知放置在正在運作
        //FLAG_INSISTENT     是否一直進行,比如音樂一直播放,知道使用者響應
        // 點選通知時,自動清除
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        notify.defaults = Notification.DEFAULT_ALL;
        manager.notify(, notify);
    }
           

Builder的一些其它屬性

//              .setContent(RemoteViews)//自定義的remoteviews  
//              .setFullScreenIntent(p, true)//不會再通知欄直接顯示,但拉下後可以顯示内容 Only for use with extremely high-priority notifications demanding the user's immediate attention, such as an incoming phone call or alarm clock that the user has explicitly set to a particular time.  
//              .setDeleteIntent(null)// 通知消失時的動作  
//              .setContentIntent(p)//點選的動作 相當于點選button  
//              .setLights(new Color().BLACK, 1000, 1000)//俺的手機不支援..無反應  
//              .setNumber(22)//   
//              .setOngoing(true)//不能被使用者x掉,會一直顯示,如音樂播放等  
//              .setPriority(2)//優先級  
//              .setProgress(max, progress, indeterminate)//進度條    
//              .setSound(uri)//聲音提示  
//              .setSound(sound, streamType)//科設定 streamtype  
//              .setStyle(style)//style設定 http://developer.android.com/reference/android/app/Notification.Style.html  
//              .setVibrate(long[])//設定震動  
           

就先介紹這麼多了,随後講解其他功能