Pusher with Service application on Android dose not bind events - android-service

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;
}
}
}

Related

Kafka consumer receive null value when sending customer object

So i want to implement application which reads data from json format files. And I have created customer object for the data in json. And I want to send these object through kafka topic. So far i have successfully send String message to producer to consumer. But when i try to send object, in the consumer side, when I do .value().toString(). I got null value. The following is the code I have used:
This is producer:
public class MyProducer {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.put("bootstrap.servers", "kafka.kafka-cluster-shared.non-prod-5-az-scus.prod.us.walmart.net:9092");
properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer", "xxxxxxxxx.KafkaJsonSerializer");
properties.put("acks", "1");
properties.put("retries", "2");
properties.put("batch.size", "16384");
properties.put("linger.ms", "1");
properties.put("buffer.memory", "33554432");
KafkaProducer<String, pharmacyData> kafkaProducer = new KafkaProducer<String, pharmacyData>(
properties);
String topic = "insights";
//try {
Gson gson = new Gson();
Reader reader = Files.newBufferedReader(Paths.get("......./part.json"));
List<pharmacyData> pdata = new Gson().fromJson(reader, new TypeToken<List<pharmacyData>>() {}.getType());
//pdata.forEach(System.out::println);
reader.close();
//} catch (Exception e) {
//e.printStackTrace();
//}
for (pharmacyData data : pdata) {
kafkaProducer.send(new ProducerRecord<String, pharmacyData>(topic, data), new Callback() {
#Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
if (e == null) {
System.out.println(recordMetadata.partition() + "--" + recordMetadata.serializedValueSize());
} else {
e.printStackTrace();
}
}
});
}
kafkaProducer.close();
}
}
This is the customer object class:
public class pharmacyData {
private String load_date;
private String store_nbr;
private String state;
private String pmp_flag;
private String zero_flag;
private String submit_ts;
public pharmacyData(String load_date, String store_nbr, String state, String pmp_flag, String zero_flag, String submit_ts) {
this.load_date = load_date;
this.store_nbr = store_nbr;
this.state = state;
this.pmp_flag = pmp_flag;
this.zero_flag = zero_flag;
this.submit_ts = submit_ts;
}
public String getLoad_date() {
return load_date;
}
public void setLoad_date(String load_date) {
this.load_date = load_date;
}
public String getStore_nbr() {
return store_nbr;
}
public void setStore_nbr(String store_nbr) {
this.store_nbr = store_nbr;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPmp_flag() {
return pmp_flag;
}
public void setPmp_flag(String pmp_flag) {
this.pmp_flag = pmp_flag;
}
public String getZero_flag() {
return zero_flag;
}
public void setZero_flag(String zero_flag) {
this.zero_flag = zero_flag;
}
public String getSubmit_ts() {
return submit_ts;
}
public void setSubmit_ts(String submit_ts) {
this.submit_ts = submit_ts;
}
#Override
public String toString() {
return "pharmacyData{" +
"load_date='" + load_date + '\'' +
", store_nbr='" + store_nbr + '\'' +
", state='" + state + '\'' +
", pmp_flag='" + pmp_flag + '\'' +
", zero_flag='" + zero_flag + '\'' +
", submit_ts='" + submit_ts + '\'' +
'}';
}
}
this is the customer Serializer:
public class KafkaJsonSerializer implements Serializer {
private Logger logger = LogManager.getLogger(this.getClass());
#Override
public void configure(Map map, boolean b) {
}
#Override
public byte[] serialize(String s, Object o) {
byte[] retVal = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
retVal = objectMapper.writeValueAsBytes(o);
} catch (Exception e) {
logger.error(e.getMessage());
}
return retVal;
}
#Override
public void close() {
}
}
This is the customer Deserializer:
public class KafkaJsonDeserializer implements Deserializer {
#Override
public void configure(Map map, boolean b) {
}
#Override
public Object deserialize(String s, byte[] bytes) {
ObjectMapper mapper = new ObjectMapper();
pharmacyData pdata = null;
try {
pdata = mapper.readValue(bytes, pharmacyData.class);
} catch (Exception e) {
e.printStackTrace();
}
return pdata;
}
#Override
public void close() {
}
}
This is consumer:
public class MyConsumer {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("bootstrap.servers", "kafka.kafka-cluster-shared.non-prod-5-az-scus.prod.us.walmart.net:9092");
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
properties.put("value.deserializer", "xxxxxxxx.KafkaJsonDeserializer");
properties.put("group.id", "consumer-group-1");
properties.put("enable.auto.commit", "true");
properties.put("auto.commit.interval.ms", "1000");
properties.put("auto.offset.reset", "earliest");
properties.put("session.timeout.ms", "30000");
KafkaConsumer<String, pharmacyData> consumer = new KafkaConsumer<>(properties);
String topic = "insights";
consumer.subscribe(Collections.singletonList(topic));
while (true) {
ConsumerRecords<String, pharmacyData> consumerRecords = consumer.poll(100);
for (ConsumerRecord<String, pharmacyData> consumerRecord : consumerRecords) {
System.out.println(consumerRecord.key() + "--" + consumerRecord.toString());
//System.out.println(consumerRecord.offset() + "--" + consumerRecord.partition());
}
}
}
}
Can someone please help me with the issues? Thank you very much!
Problem solved:
The solution of this issue just add a default constructor as below:
public pharmacyData() {
}
See this page for more details.

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
}
}

Remove (duplicate) failed TestNG result via rerun tests

I added rerun test by Testng, but have a problem with duplicate tests in test report. Could you help me with this
private int retryCount = 0;
private int maxRetryCount = 1;
#Override
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
System.out.println("Retrying test " + result.getName() + " with status "
+ getResultStatusName(result.getStatus()) + " for the " + (retryCount+1) + " time(s).");
retryCount++;
return true;
}
return false;
}
public String getResultStatusName(int status) {
String resultName = null;
if(status==1)
resultName = "SUCCESS";
if(status==2)
resultName = "FAILURE";
if(status==3)
resultName = "SKIP";
return resultName;
}
And
public class RetryListener implements IAnnotationTransformer {
#Override
public void transform(ITestAnnotation testannotation, Class testClass,
Constructor testConstructor, Method testMethod) {
IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
if (retry == null) {
testannotation.setRetryAnalyzer(iOpiumListener.class);
}
}
}
But in test report displayed or two failed or one passed and one failed test
Olga, I believe that you're missing additional listener that will clean your test results:
public class TestListener implements ITestListener {
#Override
public void onTestStart(ITestResult result) {
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onStart(ITestContext context) {
}
#Override
public void onFinish(ITestContext context) {
Set<ITestResult> failedTests = context.getFailedTests().getAllResults();
for (ITestResult temp : failedTests) {
ITestNGMethod method = temp.getMethod();
if (context.getFailedTests().getResults(method).size() > 1) {
failedTests.remove(temp);
} else {
if (context.getPassedTests().getResults(method).size() > 0) {
failedTests.remove(temp);
}
}
}
}
}
However, please, be aware of the fact that it'll work only with pure TestNG, case you have additional tools that rely on TestNG, i.e. Cucumber - It'll be necessary to clean those reports separately.
You can catch results which are incorrect (onTestFailure) and delete them when all the tests are done (onFinish)
public class RetryAnalyzer implements IRetryAnalyzer {
private static int retryCount = 0;
private static final int maxRetryCount = 1;
private static boolean isRerun = false;
#Override
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
isRerun = true;
return true;
} else {
retryCount = 0;
isRerun = false;
}
return false;
}
public boolean isRerun() {
return isRerun;
}
private String getResultStatusName(int status) {
String resultName = null;
if (status == 1)
resultName = "SUCCESS";
if (status == 2)
resultName = "FAILURE";
if (status == 3)
resultName = "SKIP";
return resultName;
}
}
public class TestListener implements ITestListener, IAnnotationTransformer {
private List<ITestResult> failedTestsToRemove = new ArrayList<>();
#Override
public void onTestStart(ITestResult result) {
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
RetryAnalyzer retryAnalyzer = (RetryAnalyzer) result.getMethod().getRetryAnalyzer();
if (retryAnalyzer.isRerun()) {
failedTestsToRemove.add(result);
}
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onStart(ITestContext context) {
}
#Override
public void onFinish(ITestContext context) {
for (ITestResult result : failedTestsToRemove) {
context.getFailedTests().removeResult(result);
}
}
#Override
public void transform(ITestAnnotation testannotation, Class testClass, Constructor testConstructor,
Method testMethod) {
IRetryAnalyzer retryAnalyzer = testannotation.getRetryAnalyzer();
if (retryAnalyzer == null) {
testannotation.setRetryAnalyzer(RetryAnalyzer.class);
}
}
}

calling alarm from a service

I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()

question about simple MINA client and server

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)