程序员人生 网站导航

android 用signalr 实现推送服务

栏目:综合技术时间:2015-03-17 09:15:58

我做的app需要实现signalr 推送服务 

有两种方法

1种人家已给我们集成了还有视频教程

地址为 https://www.youtube.com/watch?v=f9ih_M7PC10  下载的程序在这 依照视频做,但是更新了我没成功完成 https://www.youtube.com/watch?v=f9ih_M7PC10

第2种自己集成  

  1共分两步

     第1步我是在activity 里面实现接收伏务器推送的数据

首先 google上面下载 java-client 地址 https://github.com/SignalR/java-client

再下载 basic-http-client-android-0.88.jar  地址 basic-http-client-android-0.88.jar

这两个是准备工作,下面就是 生成自己需要的包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得自己重新做了,这里我讲1下怎样做的

解压aar 去除布局部份重新打包.jar     Rename *.aar to *.zip and extract the jar.意思是先重新命名aar为zip解压提取里面的jar 


3。视频中打包的longPolling。jar 我这边不1样所以打包不起来,选择把用到的所有类全部加在1个包中 其实就相当于解压打包的。固然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();
}
}

这里就能够看到推送的消息了。

第2步在你不运行程序的时候实现通知栏通知推送的消息

那就是得自己先写1个服务了其实很简单,就是相当于把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);
// 构建1个通知对象(需要传递的参数有3个,分别是图标,标题和 时间)
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对应的唯1标志
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();
}
}
}

我的服务由于服务器加密了所以得加1步

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

多加了1个head  cookie 

这里是新建了1个线程来启动signalr

到此就实现了推送服务。

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐