1. 程式人生 > >android 用signalr 實現推送服務

android 用signalr 實現推送服務

我做的app需要實現signalr 推送服務 

有兩種方法

一種人家已經給我們集成了還有視訊教程

第二種自己整合  

  一共分兩步

     第一步我是在activity 裡面實現接收伺服器推送的資料

這兩個是準備工作,下面就是 生成自己需要的包jar 

1.Open Android Studio, click "Import Non-Android Studio Project" and select the cloned directory

Build the project.

The signalr-client-sdk.jar will be generated inside the /signalr-client-sdk/build/libs folder

The signalr-client-sdk-android.aar will be generated inside the /signalr-client-sdk-android/build/outputs/aar folder

2.這裡用eclipse的只有jar有用了,aar得自己重新做了,這裡我講一下怎麼做的

解壓aar 去除佈局部分重新打包.jar     Rename *.aar to *.zip and extract the jar.意思是先重新命名aar為zip解壓提取裡面的jar 


3。視訊中打包的longPolling。jar 我這邊不一樣所以打包不起來,選擇把用到的所有類全部加在一個包中 其實就相當於解壓打包的。當然eclipse裡面後期你可以重新打包了用。


4.程式設計階段 在activity裡面呼叫很簡單的

public class SignalrActivity extends Activity {


private ImageButton goback;
private TextView what;
private IHubProxy hub = null;
private HubConnection conn = null;
// private final static String
// HUB_URL="http://192.168.1.200:82/signalr/hubs";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signalr_layout);
goback = (ImageButton) findViewById(R.id.goback);
goback.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SignalrActivity.this.finish();
}
});
what = (TextView) findViewById(R.id.what);
conn = new HubConnection(Icons.HUB_URL, this,
new LongPollingTransport()) {
@Override
public void OnError(Exception exception) {
}
@Override
public void OnMessage(String message) {
what.setText(message);
}
@Override
public void OnStateChanged(StateBase oldState, StateBase newState) {
}
};
conn.getHeaders().put("Cookie",
"BearerToken=" + SharedPref.getToken(getApplicationContext()));
beginConnect();
}


private void beginConnect() {
// TODO Auto-generated method stub
try {
hub = conn.CreateHubProxy("clientHub");
} catch (OperationApplicationException e) {
e.printStackTrace();
}
hub.On("debug1", new HubOnDataCallback() {//addNewMessageToPage
@Override
public void OnReceived(JSONArray args) {
for (int i = 0; i < args.length(); i++) {
Toast.makeText(getApplicationContext(), "chen"+args, Toast.LENGTH_SHORT
).show();
}
}
});
conn.Start();
}
}

這裡就可以看到推送的訊息了。

第二步在你不執行程式的時候實現通知欄通知推送的訊息

那就是得自己先寫一個服務了其實很簡單,就是相當於把activity改成service

public class SignalrPushService extends Service {
private String message;
private boolean quit;
private MyBinder binder = new MyBinder();
private IHubProxy hub = null;
private HubConnection conn = null;
// 通知欄訊息 數量
private int messageNotificationID = 0;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@SuppressWarnings("deprecation")
public void handleMessage(Message msg) {
if(messageNotificationID<5){
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 構建一個通知物件(需要傳遞的引數有三個,分別是圖示,標題和 時間)
Notification notification = new Notification(
R.drawable.ic_launcher, "通知", System.currentTimeMillis());
Intent intent1 = new Intent(SignalrPushService.this,
AllAlarmActivity.class);//跳轉到檢視的activity
PendingIntent pendingIntent = PendingIntent.getActivity(
SignalrPushService.this, 0, intent1, 0);
notification.setLatestEventInfo(getApplicationContext(), "報警提示",
message, pendingIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;// 點選後自動消失
notification.defaults = Notification.DEFAULT_SOUND;// 聲音預設
manager.notify(messageNotificationID, notification);// 發動通知,id由自己指定,每一個Notification對應的唯一標誌
messageNotificationID++;
}
}
};


public class MyBinder extends Binder // ①
{
public String getMessage() {
// 獲取Service的執行狀態:count
return message;
}
}


@Override
public IBinder onBind(Intent arg0) {
return binder;
}


@Override
public void onCreate() {
super.onCreate();
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread() {
public void run() {
Looper.prepare();
beginConnect();// 從服務端獲取訊息
Looper.loop();
};
}.start();
return super.onStartCommand(intent, flags, startId);
}


@Override
public void onDestroy() {
super.onDestroy();
this.quit = true;
}


private void beginConnect() {


// TODO Auto-generated method stub
conn = new HubConnection(Icons.HUB_URL, getBaseContext(),
new LongPollingTransport()) {
@Override
public void OnMessage(String message) {
SignalrPushService.this.message = message;
handler.sendEmptyMessage(0);
}
};
conn.getHeaders().put("Cookie",
"BearerToken=" + SharedPref.getToken(getApplicationContext()));
quit = false;
while (!quit) {
try {
hub = conn.CreateHubProxy("clientHub");
} catch (OperationApplicationException e) {
e.printStackTrace();
}
/*
* hub.On("debug1", new HubOnDataCallback() {//addNewMessageToPage

* @Override public void OnReceived(JSONArray args) { Message msg =
* handler.obtainMessage(); msg.what = 1; handler.sendMessage(msg);
* Toast.makeText(SignalrPushService.this, args+"",
* Toast.LENGTH_SHORT).show(); } });
*/
conn.Start();
}
}
}

我的服務因為伺服器加密了所以得加一步

conn.getHeaders().put("Cookie",
"BearerToken=" + SharedPref.getToken(getApplicationContext()));

多加了一個head  cookie 

這裡是新建了一個執行緒來啟動signalr

到此就實現了推送服務。