question about simple MINA client and server - apache-mina

I am just trying to create a simple MINA server and client to evaluate. Here is my code.
public class Server {
private static final int PORT = 8080;
static class ServerHandler extends IoHandlerAdapter {
#Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
cause.printStackTrace();
}
#Override
public void sessionCreated(IoSession session) {
System.out.println("session is created");
session.write("Thank you");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("session is closed.");
}
#Override
public void messageReceived(IoSession session, Object message) {
System.out.println("message=" + message);
session.write("Reply="+message);
}
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
SocketAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
acceptor.setHandler(new Server.ServerHandler());
acceptor.getSessionConfig().setReadBufferSize( 2048 );
acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Listening on port " + PORT);
for (;;) {
Thread.sleep(3000);
}
}
}
public class Client {
private static final int PORT = 8080;
private IoSession session;
private ClientHandler handler;
public Client() {
super();
}
public void initialize() throws Exception {
handler = new ClientHandler();
NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.setHandler(handler);
for (;;) {
try {
ConnectFuture future = connector.connect(new InetSocketAddress(PORT));
future.awaitUninterruptibly();
session = future.getSession();
break;
} catch (RuntimeIoException e) {
System.err.println("Failed to connect.");
e.printStackTrace();
Thread.sleep(5000);
}
}
if (session == null) {
throw new Exception("Unable to get session");
}
Sender sender = new Sender();
sender.start();
session.getCloseFuture().awaitUninterruptibly();
connector.dispose();
System.out.println("client is done.");
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
Client client = new Client();
client.initialize();
}
class Sender extends Thread {
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.messageSent(session, "message");
}
}
class ClientHandler extends IoHandlerAdapter {
#Override
public void sessionOpened(IoSession session) {
}
#Override
public void messageSent(IoSession session, Object message) {
System.out.println("message sending=" + message);
session.write(message);
}
#Override
public void messageReceived(IoSession session, Object message) {
System.out.println("message receiving "+ message);
}
#Override
public void exceptionCaught(IoSession session, Throwable cause) {
cause.printStackTrace();
}
}
}
When I execute this code, the Client seems to keep sending a message instead of stopping after it sends. It looks to me that there is a recursive call in underlying MINA code. I know that I am doing something wrong.
Can somebody tell me how to fix this?
Thanks.

Try to initialize and start your sender and use the session within sessionOpened (ClientHandler)

Related

Spring AMQP RabbitMQ RPC Priority Queue

I am trying to have a RPC queue where messages from the Producer/client are prioritized to the consumer. I want all priority 2 messages processed before any priority one messages. I also want each consumer to be able to handle 10 messages at a time. I am able to get each consumer to process 10 messages at a time. I am NOT able to get the prioritization of messages to work. Below is my setup:
Config Files:
#Configuration
public class QueueConfig {
public static final String QUEUE_NAME = "requests";
private int maxPriority = 2;
#Autowired
private ConnectionFactory connectionFactory;
#Bean
public Queue requests() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-max-priority", maxPriority);
return new Queue(QUEUE_NAME,true,false,false, args);
}
#Bean
public Queue replies() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-max-priority", maxPriority);
return new Queue("replies",true,false,false, args);
}
#Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
container.setQueueNames(replies().getName());
return container;
}
#Bean
public RabbitTemplate template() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setRoutingKey(requests().getName());
return rabbitTemplate;
}
#Bean
public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate rabbitTemplate, SimpleMessageListenerContainer container) {
AsyncRabbitTemplate asyncRabbitTemplate = new AsyncRabbitTemplate(rabbitTemplate, container);
asyncRabbitTemplate.setReceiveTimeout(90000);
return asyncRabbitTemplate;
}
}
Client/Producer:
#Component
public class Client {
#Autowired
private AsyncRabbitTemplate template;
public void sendHigh(String name) {
MessagePostProcessor messageProcessor = new MessagePostProcessor() {
#Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setPriority(2);
return message;
}
};
ListenableFuture<String> response = template.convertSendAndReceive(QueueConfig.QUEUE_NAME, (Object) name,(MessagePostProcessor) messageProcessor);
try {
response.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public void sendLow(String name) {
MessagePostProcessor messageProcessor = new MessagePostProcessor() {
#Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setPriority(1);
return message;
}
};
ListenableFuture<String> response = template.convertSendAndReceive(QueueConfig.QUEUE_NAME, (Object) name,(MessagePostProcessor) messageProcessor);
try {
response.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
config file 2:
#Configuration
#EnableAsync
public class ServiceConfig implements AsyncConfigurer {
#Override
#Bean
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}
}
Consumer:
#Component
public class Consumer {
#RabbitListener(queues = QueueConfig.QUEUE_NAME)
public String consume(#Payload String name) {
System.out.println("Request Consumer " + name);
String result = name;
if(result.equals("john") || result.equals("john1")) {
try {
Thread.sleep(22000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
Application.properties:
spring.rabbitmq.dynamic=true
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.host=localhost
spring.rabbitmq.listener.simple.concurrency=10
spring.rabbitmq.listener.direct.acknowledge-mode=MANUAL
Junit:
I would expect all john and john1's to be received by the consumer before jeff, but that is not the behavior that I am seeing. Basically im looking at this println and expecting all john and john1's to print before jeff System.out.println("Request Consumer " + name);
#RunWith(SpringRunner.class)
#ComponentScan(basePackages = "com.test.test")
#EnableAutoConfiguration
#SpringBootTest
public class ApplicationTests {
#Autowired AsyncClass asyncClass;
#Test
public void contextLoads() throws InterruptedException, ExecutionException {
List<Future<String>> futures = new ArrayList<>();
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
futures.add(asyncClass.runAsyncHigh("john"));
Thread.sleep(1000);
futures.add(asyncClass.runAsyncLow("jeff"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
futures.add(asyncClass.runAsyncHigh("john1"));
for(Future<String> future : futures) {
future.get();
}
}
#Component
public class AsyncClass {
#Autowired Client client;
#Async
public Future<String> runAsyncHigh(String name){
client.sendHigh(name);
return new AsyncResult<String>(name);
}
#Async
public Future<String> runAsyncLow(String name){
client.sendLow(name);
return new AsyncResult<String>(name);
}
}
Thanks,
Brian

Retrofit error response handling

I am using retrofit 2.3.0 to consume API's in my app but a week ago I started receiving error message and existing code was not able to display error message in UI.
Previously, I was using errorBody.toString() then suddenly after few months I got error and then last week I tried with errorBody.string() but it dodn't work. Now today it's working.
I have attached screenshots of response from server and my error handling also. Here is my code to display error message.
private static void showToastForError(retrofit2.Response<Object> response, int requestType) {
if (response != null && response.errorBody() != null) {
try {
JSONObject jObjError = null;
try {
jObjError = new JSONObject(response.errorBody() != null ? response.errorBody().toString() : "");
Toast.makeText(Application.getAppContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think you should custom call adapter to handle error.
Here my custom adapter
public final class ErrorHandlingAdapter {
/**
* A callback which offers granular callbacks for various conditions.
*/
public interface MyCallback<T> {
/**
* Called for [200, 300) responses.
*/
void success(Response<T> response);
/**
* Called for 401 responses.
*/
void unauthenticated(Response<?> response);
/**
* Called for [400, 500) responses, except 401.
*/
void clientError(Response<?> response);
/**
* Called for [500, 600) response.
*/
void serverError(Response<?> response);
/**
* Called for network errors while making the call.
*/
void networkError(IOException e);
/**
* Called for unexpected errors while making the call.
*/
void unexpectedError(Throwable t);
}
public interface MyCall<T> {
void cancel();
void enqueue(MyCallback<T> callback);
MyCall<T> clone();
boolean isExcute();
}
public static class ErrorHandlingCallAdapterFactory extends CallAdapter.Factory {
#Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations,
Retrofit retrofit) {
if (getRawType(returnType) != MyCall.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalStateException(
"MyCall must have generic type (e.g., MyCall<ResponseBody>)");
}
Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
Executor callbackExecutor = retrofit.callbackExecutor();
return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor);
}
private static final class ErrorHandlingCallAdapter<R> implements CallAdapter<R> {
private final Type responseType;
private final Executor callbackExecutor;
ErrorHandlingCallAdapter(Type responseType, Executor callbackExecutor) {
this.responseType = responseType;
this.callbackExecutor = callbackExecutor;
}
#Override
public Type responseType() {
return responseType;
}
#Override
public <R1> R adapt(Call<R1> call) {
return (R) new MyCallAdapter(call, callbackExecutor);
}
}
}
/**
* Adapts a {#link Call} to {#link MyCall}.
*/
static class MyCallAdapter<T> implements MyCall<T> {
private final Call<T> call;
private final Executor callbackExecutor;
MyCallAdapter(Call<T> call, Executor callbackExecutor) {
this.call = call;
this.callbackExecutor = callbackExecutor;
}
#Override
public void cancel() {
call.cancel();
}
#Override
public void enqueue(final MyCallback<T> callback) {
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
// on that executor by submitting a Runnable. This is left as an exercise for the reader.
callbackExecutor.execute(new Runnable() {
#Override
public void run() {
int code = response.code();
if (code >= 200 && code < 300) {
callback.success(response);
} else if (code == 401) {
if (Storage.getInstance().isLogin())
Storage.getInstance().logout(App.self().getApplicationContext());
} else if (code >= 400 && code < 500) {
callback.clientError(response);
} else if (code >= 500 && code < 600) {
callback.serverError(response);
} else {
callback.unexpectedError(new RuntimeException("Unexpected response " + response));
}
}
});
}
#Override
public void onFailure(Call<T> call, Throwable t) {
// on that executor by submitting a Runnable. This is left as an exercise for the reader.
callbackExecutor.execute(new Runnable() {
#Override
public void run() {
if (t instanceof IOException) {
if (call.isCanceled()) {
return;
}
callback.networkError((IOException) t);
Toast.makeText(App.self(), R.string.error_no_connect_internet, Toast.LENGTH_SHORT).show();
} else {
callback.unexpectedError(t);
}
}
});
}
});
}
#Override
public MyCall<T> clone() {
return new MyCallAdapter<>(call.clone(), callbackExecutor);
}
#Override
public boolean isExcute() {
return call.isExecuted();
}
}
}
Here my config to add custom call adapter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(new ErrorHandlingAdapter.ErrorHandlingCallAdapterFactory()) // custom call adapter
.addConverterFactory(GsonConverterFactory.create())
.client(getHeader())
.build();
And handle request, ex:
#GET("api/getSomething")
ErrorHandlingAdapter.MyCall<BaseResponse> getSomething(#Query("param"),...)
Handle response:
ErrorHandlingAdapter.MyCall<BaseResponse> mCalls = ApiUtils.getSomething(...);
mCalls.enqueue(new ErrorHandlingAdapter.MyCallback<BaseResponse>() {
#Override
public void success(Response<BaseResponse> response) {
//handle response
}
#Override
public void unauthenticated(Response<?> response) {
//handle unauthenticated error
}
#Override
public void clientError(Response<?> response) {
//handle clientError error
}
#Override
public void serverError(Response<?> response) {
//handle serverError error
}
#Override
public void networkError(IOException e) {
//handle networkError error
}
#Override
public void unexpectedError(Throwable t) {
//handle unexpectedError error
}
}

Pusher with Service application on Android dose not bind events

I had a problem with Pusher with Service application on Android.
When I using pusher on Application or Activity then It's working.
But I move it to Service and register with application in manifress like:
<service android:name=".services.PusherServices"/>
It's not working.
When i startService Pusher connected success with authorization, but It's not bind events when I call method for register Channel.
PusherServices.java
package vn.hemlock.winkle.pancake.services;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.pusher.client.Pusher;
import com.pusher.client.PusherOptions;
import com.pusher.client.channel.PrivateChannel;
import com.pusher.client.channel.PrivateChannelEventListener;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionState;
import com.pusher.client.connection.ConnectionStateChange;
import com.pusher.client.util.HttpAuthorizer;
import net.windjs.android.utils.Encrypt;
import net.windjs.android.utils.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import vn.hemlock.winkle.pancake.abstracts.ChatEvents;
import vn.hemlock.winkle.pancake.contracts.ServicesURI;
import vn.hemlock.winkle.pancake.ui.Conversation;
import vn.hemlock.winkle.pancake.ui.Message;
import vn.hemlock.winkle.pancake.ui.Page;
/**
* Created by me866chuan on 5/4/15.
*/
public class PusherServices extends Service {
private String LOG_TAG = "Pusher Services";
private boolean pusherOn = false;
public final String PUSHER_KEY = "...";
private String userToken = "";
private String userID = "";
private final IBinder mBinder = new LocalBinder();
public boolean isPusherOn() {
return pusherOn;
}
public void setPusherOn(boolean pusherOn) {
this.pusherOn = pusherOn;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
#Override
public IBinder onBind(Intent intent) {
setUserID(intent.getStringExtra("userId"));
setUserToken(intent.getStringExtra("userToken"));
startPusher();
startService(intent);
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
Log.e(LOG_TAG, "OFF");
stopService(intent);
return true;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pusher.disconnect();
}
private Pusher pusher;
public void startPusher() {
HashMap<String, String> hash = new HashMap<>();
Log.e(LOG_TAG, "Token: "+getUserToken());
hash.put("authorization", getUserToken());
HttpAuthorizer authorizer = new HttpAuthorizer(ServicesURI.PUSHER_AUTHORIZER);
authorizer.setHeaders(hash);
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
pusher = new Pusher(PUSHER_KEY, options);
pusher.connect(new ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange change) {
Log.e(LOG_TAG, "State changed to " + change.getCurrentState() +
" from " + change.getPreviousState());
if(change.getCurrentState().toString().toUpperCase().equals("CONNECTED") || change.getCurrentState().toString().toUpperCase().equals("CONNECTING")){
setPusherOn(true);
}
else setPusherOn(false);
}
#Override
public void onError(String message, String code, Exception e) {
Log.e(LOG_TAG, "There was a problem connecting: " + message);
}
}, ConnectionState.ALL);
}
PrivateChannel userChannel;
public void userListenChanel(final Activity activity) {
if (pusher == null) return;
userChannel = pusher.subscribePrivate("private-" + Encrypt.stringMD5(getUserID()));
userChannel.bind("fetch_accounts", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
if (activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ChatEvents.getInstance().onNewPage(new Page((new JSONObject(data)).getJSONObject("page")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e(LOG_TAG, "USER FETCH FAIL: " + s);
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e(LOG_TAG, "USER FETCH SUCCESS: " + s);
}
});
}
PrivateChannel pageChannel;
private String idPageChannelListen;
public void pageListenChanel(final Activity activity, String pageId) {
if (pusher == null) return;
idPageChannelListen = pageId;
Log.e(LOG_TAG, "Channel page: "+"private-" + Encrypt.stringMD5(pageId));
pageChannel = pusher.subscribePrivate("private-" + Encrypt.stringMD5(pageId));
pageChannel.bind("realtime_updates", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Real time update with data: " + data);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject finalJsonObject = jsonObject;
if(activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (finalJsonObject == null) return;
try {
if (finalJsonObject.has("message")) ChatEvents.getInstance().onNewMessage(new Message(finalJsonObject.getJSONObject("message")));
else if (finalJsonObject.has("conversation")) ChatEvents.getInstance().onNewConversation(new Conversation(finalJsonObject.getJSONObject("conversation")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e(LOG_TAG, "Real time update failed: " + s);
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e(LOG_TAG, "Real time update successed: " + s);
}
});
pageChannel.bind("fetch_conversations", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
if(activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ChatEvents.getInstance().onNewConversation(new Conversation((new JSONObject(data)).getJSONObject("conversation")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
}
#Override
public void onSubscriptionSucceeded(String s) {
}
});
pageChannel.bind("fetch_comments", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
}
#Override
public void onSubscriptionSucceeded(String s) {
}
});
}
public void removeLisnterPage(String pageId) {
if (pusher != null) pusher.unsubscribe("private-" + Encrypt.stringMD5(pageId));
idPageChannelListen = "";
}
public void reconnectPusher() {
if (pusher != null) {
pusher.disconnect();
pusher.connect();
}
}
public void disconnectPusher() {
if (pusher != null) pusher.disconnect();
}
public String getIdPageChannelListen() {
return idPageChannelListen;
}
public class LocalBinder extends Binder {
public PusherServices getService() {
// Return this instance of LocalService so clients can call public methods
return PusherServices.this;
}
}
}

Estimote : Show notification when the app is closed

How to show notification when the app is closed with estimote api.As it is having default BeaconService we need to implement it in the application level to show the notification when the app is closed.So for that i'm trying with the following code.
Activity:-
public class Dashboard extends Activity {
private static final String TAG = Dashboard.class.getSimpleName();
ConnectionDetector cDetector;
private static final int NOTIFICATION_ID = 123;
private NotificationManager notificationManager;
JSONParser jParser = new JSONParser();
AlertDialogManager alert;
private static final String URL_NOTIFICATIONS = "";
ArrayList<NameValuePair> pairs;
private static final int REQUEST_ENABLE_BT = 1234;
private ProgressDialog pDialog;
private BeaconManager bManager;
// private Beacon beacon;
private Region region = new Region("regionID", null, null, null);
List<Beacon> beaconList;
BroadcastReceiver receiver;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_demo);
getActionBar().setDisplayHomeAsUpEnabled(true);
cDetector = new ConnectionDetector(getApplicationContext());
// check Internet connection
if (!cDetector.isConnectingToInternet()) {
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working internet connection", false);
return;
}
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region region,
final List<Beacon> beacons) {
// Note that results are not delivered on UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// Note that beacons reported here are already sorted by
// estimated distance between device and beacon.
getActionBar().setSubtitle(
"Found beacons: " + beacons.size());
}
});
}
});
Log.i("BeaconsList", "beaconslist" + beaconList);
// region = new Region("regionId", ((Beacon)
// beaconList).getProximityUUID(),
// ((Beacon) beaconList).getMajor(),
// ((Beacon) beaconList).getMinor());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
// new GetNotificationData().execute();
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
#Override
protected void onStart() {
super.onStart();
// Check if device supports Bluetooth Low Energy.
if (!bManager.hasBluetooth()) {
Toast.makeText(this, "Device does not have Bluetooth Low Energy",
Toast.LENGTH_LONG).show();
return;
}
// If Bluetooth is not enabled, let user enable it.
if (!bManager.isBluetoothEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
connectToService();
}
}
#Override
protected void onStop() {
try {
bManager.stopRanging(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while stopping ranging", e);
}
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
connectToService();
} else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
.show();
getActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService() {
getActionBar().setSubtitle("Scanning...");
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startRanging(region);
} catch (RemoteException e) {
Toast.makeText(
Dashboard.this,
"Cannot start ranging, something terrible happened",
Toast.LENGTH_LONG).show();
Log.e(TAG, "Cannot start ranging", e);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
notificationManager.cancel(NOTIFICATION_ID);
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while starting monitoring");
}
}
});
}
#Override
protected void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
bManager.disconnect();
super.onDestroy();
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(Dashboard.this, Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
Dashboard.this, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(Dashboard.this)
.setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
TextView statusTextView = (TextView) findViewById(R.id.status);
statusTextView.setText(msg);
}
}
Application Class:-
public class MyApplication extends Application {
BeaconManager bManager;
NotificationManager notificationManager;
private Region region = new Region("regionID", null, null, null);
private static final int NOTIFICATION_ID = 123;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region regions, List<Beacon> beacons) {
// TODO Auto-generated method stub
Log.i("Beacons", "" + beacons.size());
}
});
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d("BEACON", "Error while starting monitoring");
}
}
});
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(getApplicationContext(),
Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
getApplicationContext(), 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(
getApplicationContext()).setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
and i have mentioned the beaconservice in manifest also as follows..
Can any one help what is going wrong here and how can show the notification when the app is closed.

restart app and follow the same steps Robotium

I am learning to use robotium and I am trying to relaunch the application and do the same steps 5 time. I know to put for loop, but how do I relaunch application? I was using robotium recorder to do some of it, but it's easier to edit the script manually instead of recording again so I am trying to figure this out.
import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;
#SuppressWarnings("rawtypes")
public class explore extends ActivityInstrumentationTestCase2 {
private Solo solo;
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.application.calc.android.main.CGabboMainActivity";
private static Class<?> launcherActivityClass;
static{
try {
launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
#SuppressWarnings("unchecked")
public explore() throws ClassNotFoundException {
super(launcherActivityClass);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation());
getActivity();
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
public void testRun() {
// Wait for activity: 'com.application.calc.android.main.CGabboMainActivity';
solo.waitForActivity("CGabboMainActivity", 2000);
// Sleep for 10211 milliseconds
solo.sleep(5000);
// Click on source_internet_radio
solo.clickOnWebElement(By.id("handle_name"));
//Sleep for 5697 milliseconds
solo.clickOnWebElement(By.id("source_help"));
solo.clickOnWebElement(By.id("nav_item_1"));
//solo.finishOpenedActivities();
//solo.waitForActivity("CGabboMainActivity", 2000);
//this.launchActivity(LAUNCHER_ACTIVITY_FULL_CLASSNAME, launcherActivityClass,null);
//solo.clickOnWebElement(By.xpath(".//*[#id='nav_panel_0']/div[1]/div/div[2]"));
//solo.sleep(15211);
//solo.clickOnWebElement(By.id("handle_name"));
}
}
I can suggest to create private helper method with test logic and 5 different test methods which call the helper. Before every test method there is setUp and after there is tearDown so your application will be restarted. Your class can look like:
import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;
#SuppressWarnings("rawtypes")
public class explore extends ActivityInstrumentationTestCase2 {
private Solo solo;
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.application.calc.android.main.CGabboMainActivity";
private static Class<?> launcherActivityClass;
static{
try {
launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
#SuppressWarnings("unchecked")
public explore() throws ClassNotFoundException {
super(launcherActivityClass);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation());
getActivity();
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
public void testRun1() {
helper();
}
public void testRun2() {
helper();
}
public void testRun3() {
helper();
}
public void testRun4() {
helper();
}
public void testRun5() {
helper();
}
private void helper() {
// Wait for activity: 'com.application.calc.android.main.CGabboMainActivity';
solo.waitForActivity("CGabboMainActivity", 2000);
// Sleep for 10211 milliseconds
solo.sleep(5000);
// Click on source_internet_radio
solo.clickOnWebElement(By.id("handle_name"));
//Sleep for 5697 milliseconds
solo.clickOnWebElement(By.id("source_help"));
solo.clickOnWebElement(By.id("nav_item_1"));
//solo.finishOpenedActivities();
//solo.waitForActivity("CGabboMainActivity", 2000);
//this.launchActivity(LAUNCHER_ACTIVITY_FULL_CLASSNAME, launcherActivityClass,null);
//solo.clickOnWebElement(By.xpath(".//*[#id='nav_panel_0']/div[1]/div/div[2]"));
//solo.sleep(15211);
//solo.clickOnWebElement(By.id("handle_name"));
}
}
Another way is to create own test suite.