PhoneStateListener causing problems in outgoin calls - phone-state-listener

Outgoing calls are ended automatically when phonestatelistener is used to monitor the calls.
This is my code and when this is executed it blocks the outgoing calls :
public class CallHelper {
public String number;
private Context ctx;
private TelephonyManager tm;
private CallStateListener callStateListener;
private OutgoingReceiver outgoingReceiver;
SharedPreferences trackMeData;
public CallHelper(Context ctx) {
this.ctx = ctx;
number ="";
callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
trackMeData = ctx.getSharedPreferences("LockedSIM", 0);
}
private class CallStateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
number = incomingNumber;
sendsmstoph(number);
System.out.println("Incomgin");
Toast.makeText(ctx, "Incoming: " + incomingNumber,Toast.LENGTH_LONG).show();
break;
}
}
}
public class OutgoingReceiver extends BroadcastReceiver {
public OutgoingReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(ctx, "Outgoing: " + number, Toast.LENGTH_LONG).show();
sendsmstoph(number);
}
}

Related

Cannot build Bitfinex Java Client - Not getting any response

So, the main goal here is to connect to the Bitfinex WebSocket by building a WebSocket Client. I would like to start receiving a stream of information(price,trades,etc). The problem is that at this stage I cannot even subscribe to a specific currency pair. In other words, I am sending a request for information to the WebSocket server but I am not receiving any responses and I cannot figure why this is. My code is below.
This is the main method
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
String URL = "wss://api-pub.bitfinex.com/ws/2/";
WebSocketClient client = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(client);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
StompSessionHandler sessionHandler = new MyStompSessionHandler();
stompClient.connect(URL,sessionHandler);
new Scanner(System.in).nextLine(); // Don't close immediately.
}
}
This is the MyStompSessionHandler
public class MyStompSessionHandler extends StompSessionHandlerAdapter{
#Override
public void afterConnected(
StompSession session, StompHeaders connectedHeaders) {
System.out.println("New session established : " + session.getSessionId());
System.out.println("wss://api-pub.bitfinex.com/ws/2");
session.send("wss://api-pub.bitfinex.com/ws/2/", getSampleMessage());
System.out.println("Message sent to websocket server");
}
#Override
public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
System.out.println("Got an exception:" + exception);
}
#Override
public Type getPayloadType(StompHeaders headers) {
return OutboundMessage.class;
}
private Object getSampleMessage() {
InboundMessage inboundMessage = new InboundMessage();
inboundMessage.setEvent("subscribe");
inboundMessage.setChannel("ticker");
inboundMessage.setSymbol("tBTCUSD");
return inboundMessage;
}
#Override
public void handleFrame(StompHeaders headers, Object payload) {
InboundMessage msg = (InboundMessage) payload;
System.out.println(msg.toString());
}
}
This is the InboundMessage class
public class InboundMessage {
private String event;
private String channel;
private String symbol;
public InboundMessage() {
}
public InboundMessage(String event, String channel, String symbol) {
this.event = event;
this.channel = channel;
this.symbol = symbol;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
#Override
public String toString() {
return "InboundMessage{" +
"event='" + event + '\'' +
", channel='" + channel + '\'' +
", symbol='" + symbol + '\'' +
'}';
}
I looked at the Bitfinex website and I don't see any evidence that STOMP is supported. They just have a REST and a WebSocket API. Therefore, using STOMP from your client isn't going to work.

viewholder onclickListener null object reference

Attempt to invoke interface method 'void com.example.imovie.adapter.MovieItemClickListener.onMovieClick(com.example.imovie.models.Movie, android.widget.ImageView)' on a null object reference
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MyViewHolder> {
Context context ;
List<Movie> mData;
MovieItemClickListener movieItemClickListener;
public MovieAdapter(Context context, List<Movie> mData, MovieItemClickListener listener) {
this.context = context;
this.mData = mData;
movieItemClickListener = listener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_movie,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.TvTitle.setText(mData.get(i).getTitle());
myViewHolder.ImgMovie.setImageResource(mData.get(i).getThumbnail());
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView TvTitle;
private ImageView ImgMovie;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
TvTitle = itemView.findViewById(R.id.item_movie_title);
ImgMovie = itemView.findViewById(R.id.item_movie_img);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movieItemClickListener.onMovieClick(mData.get(getAdapterPosition()),ImgMovie);//i have a null object reference
}
});
}
}
}
public class HomeFragment extends Fragment implements MovieItemClickListener {
private HomeViewModel homeViewModel;
private List<Slide> listSlides;
private ViewPager slidePager;
private TabLayout indicator;
private RecyclerView moviesRV;
private RecyclerView moviesRV2;
private MovieItemClickListener movieItemClickListener;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
slidePager = root.findViewById(R.id.slider_pager);
indicator = root.findViewById(R.id.indicator);
moviesRV = root.findViewById(R.id.rsViewMovies);
moviesRV2 = root.findViewById(R.id.rsViewMovies2);
iniSlider();
final SliderPagerAdapter sliderPagerAdapteradapter = new SliderPagerAdapter(getContext(), listSlides);
final MovieAdapter movieAdapter = new MovieAdapter(getContext(), DateSource.getPopularMovies(), movieItemClickListener);
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
homeViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
slidePager.setAdapter(sliderPagerAdapteradapter);
indicator.setupWithViewPager(slidePager, true);
moviesRV.setAdapter(movieAdapter);
moviesRV.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
moviesRV2.setAdapter(movieAdapter);
moviesRV2.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
}
});
return root;
}
#Override
public void onMovieClick(Movie movie, ImageView imageView) {
Intent intent = new Intent(getContext(), MovieDetailActivity.class);
intent.putExtra("title", movie.getTitle());
intent.putExtra("imgURL", movie.getThumbnail());
intent.putExtra("imgCover", movie.getCoverPhoto());
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(getActivity(),
imageView, "sharedName");
startActivity(intent, options.toBundle());
Toast.makeText(getContext(), "item clicked : " + movie.getTitle(), Toast.LENGTH_LONG).show();
}
class SliderTimer extends TimerTask {
#Override
public void run() {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (slidePager.getCurrentItem() < listSlides.size() - 1) {
slidePager.setCurrentItem(slidePager.getCurrentItem() + 1);
} else {
slidePager.setCurrentItem(0);
}
}
});
}
}
}
private void iniSlider() {
listSlides = new ArrayList<>();
listSlides.add(new Slide(R.drawable.a, "slide title \n movie title"));
listSlides.add(new Slide(R.drawable.b, "slide title"));
listSlides.add(new Slide(R.drawable.a, "slide title \n movie title"));
listSlides.add(new Slide(R.drawable.b, "slide title"));
}
}
If I'm not wrong, HomeFragment.movieItemClickListener is never initialized.
You may want to make the following changes in HomeFragment:
1. Delete the line
private MovieItemClickListener movieItemClickListener;
2. In this line
final MovieAdapter movieAdapter = new MovieAdapter(getContext(), DateSource.getPopularMovies(), movieItemClickListener);
change movieItemClickListener to this, because HomeFragment implements MovieItemClickListener.
That should fix the NullPointerException.

Updating adapter of AutoCompleteTextView from LiveData

I have a AutoCompleteTextView that I give it 2 different adapters depending on the amount of text that is being present at the textview - if it has 0 characters I want it to display a list of "recently searched" strings adapter, while if it has more than 1 characters I want it to display auto completion list.
My getRecentlySearchedQueries method along with the RecentSearchedViewModel-
private List<String> recentlySearchedQueries = new ArrayList<>(); // pasted from the top of the class
#Override
public void getRecentlySearchedQueries() {
recentSearchViewModel.getAllQueries().observe(getActivity(), databaseRecentlySearchList -> {
if (databaseRecentlySearchList == null) {
return;
}
for (int i = 0; i < databaseRecentlySearchList.size(); i++) {
Log.d("localDBValue", "Added value - " + databaseRecentlySearchList.get(i).toString() + "\n");
String query = databaseRecentlySearchList.get(i).getQuery();
recentlySearchedQueries.add(query);
}
//Log.d("localDBValue", "recent search list value - " + recentlySearchedQueries);
});
}
public class RecentSearchViewModel extends AndroidViewModel {
private RecentSearchRepository recentSearchRepository;
private LiveData<List<RecentSearchModel>> allRecentlySearched;
public RecentSearchViewModel(#NonNull Application application) {
super(application);
recentSearchRepository = new RecentSearchRepository(application);
allRecentlySearched = recentSearchRepository.getAllRecentSearches();
}
public void insert(RecentSearchModel model) {
recentSearchRepository.insert(model);
}
public void update(RecentSearchModel model) {
// add implementation in the future if needed
}
public void delete(RecentSearchModel model) {
// add implementation in the future if needed
}
public LiveData<List<RecentSearchModel>> getAllQueries() {
return allRecentlySearched;
}
}
public class RecentSearchRepository {
private RecentSearchDao recentSearchDao;
private LiveData<List<RecentSearchModel>> allRecentSearches;
public RecentSearchRepository(Application application) {
MarketplaceDatabase database = MarketplaceDatabase.getRecentSearchInstance(application);
recentSearchDao = database.recentSearchDao();
allRecentSearches = recentSearchDao.getRecentSearchList();
}
public void insert(RecentSearchModel model) {
new RecentSearchRepository.InsertRecentSearchAsyncTask(recentSearchDao).execute(model);
}
public void update (RecentSearchModel model) {
//TODO - implement in future if needed
}
public void delete(RecentSearchModel model) {
//TODO - implement in future if needed
}
public LiveData<List<RecentSearchModel>> getAllRecentSearches() {
return allRecentSearches;
}
private static class InsertRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public InsertRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.insert(recentSearchModels[0]);
return null;
}
}
private static class UpdateRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public UpdateRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.update(recentSearchModels[0]);
return null;
}
}
}
#Dao
public interface RecentSearchDao {
#Insert()
void insert(RecentSearchModel model);
#Update
void update(RecentSearchModel model);
#Delete
void delete(RecentSearchModel model);
#Query("select * from recent_search_table")
LiveData<List<RecentSearchModel>> getRecentSearchList();
}
#Entity(tableName = "recent_search_table")
public class RecentSearchModel {
#PrimaryKey(autoGenerate = true)
private int ID;
private String query;
public RecentSearchModel(){
}
public RecentSearchModel(String query) {
this.query = query;
}
public void setID(int ID) {
this.ID = ID;
}
public int getID() {
return ID;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
#Override
public String toString() {
return "RecentSearchModel{" +
"query='" + query + '\'' +
'}';
}
#Override
public boolean equals(#Nullable Object obj) {
if (obj instanceof RecentSearchModel)
return this.query.equalsIgnoreCase(((RecentSearchModel) obj).query);
return false;
}
}
So, what I am doing here is for start getting all values inside my local DB and adding them to my String list that is part of the adapter. So far so good.
The issue I am facing is that the adapter won't show the amount of strings available in the list that populates it. In fact, it sometimes shows a view half-cut with wierd information, sometimes does not show anything and sometimes shows part of the corrent information. What am I missing?
Another thing I am facing is that the "recently searched" adapter won't work when clicking on the AutoCompleteTextView - it only works when typing and deleting values so the char length is 0. How can I make it work from start of focus?
Here is the way I am populating the information to the ViewModel -
/**
* Shows the searched products following
*/
#Override
public void getSearchedProducts(String searchedQuery) {
MarketplaceUtils.getSearchedProducts(searchedQuery, marketApiCalls, false, initialSearchTake, initialMarketplacePage, new MarketplaceUtils.OnProductsFetchCompleteListener() {
#Override
public void onSuccess(List<MiniProductModel> list) {
if (!searchedQuery.equals(currentSearchedText))
return;
if (list == null) {
//reaching here means we do not have a result to show to the UI so we empty the list.
currentProductList.clear();
productsAdapter.notifyDataSetChanged();
return;
}
if (searchedQuery.length() > 3 && searchAutoCompleteStrings.contains(searchedQuery)) {
Log.d("localDBValue", "searchedValue - " + searchedQuery);
recentSearchViewModel.insert(new RecentSearchModel(searchedQuery));
}
mPresenter.setDiscoverProductsLayoutVisibility(View.GONE);
currentProductList.clear();
currentProductList.addAll(list);
productsAdapter.notifyDataSetChanged();
}
#Override
public void onError(Throwable throwable) {
Log.d("searchedProducts", throwable.getMessage());
}
});
}
The default behaviour for #Insert method of Room is OnConflictStrategy.ABORT - so what I did is to implement equals() method to verify that the RecentSearchModels that are being compared are compared by their string value. Still does seems to effect anything.

How can I display my Firebase notification message in my textviews in background mode?

I want to display my Firebase notification message in textviews in background mode, but it's only working and displaying in foreground mode.
I have already used broadcastReceiver. It is working, but only in the foreground. How can I make it work in background mode?
This is my Firebase Messaging Service class:
public class ProfileActivity extends AppCompatActivity {
TextView notificationTitle, notificationMessage;
public static final String NODE_USERS = "users";
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(mHandler,new IntentFilter("com.example.linguanotification_FCM-MESSAGE"));
setContentView(R.layout.activity_profile);
notificationTitle=findViewById(R.id.title_notification);
notificationMessage=findViewById(R.id.notification_message);
mAuth = FirebaseAuth.getInstance();
FirebaseMessaging.getInstance().subscribeToTopic("updates");
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
saveToken(token);
} else {
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
private void saveToken(String token) {
String email = mAuth.getCurrentUser().getEmail();
User user = new User(email, token);
DatabaseReference dbUsers = FirebaseDatabase.getInstance().getReference(NODE_USERS);
dbUsers.child(mAuth.getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Token Saved", Toast.LENGTH_LONG).show();
}
}
});
}
private BroadcastReceiver mHandler = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("title");
String message=intent.getStringExtra("message");
notificationTitle.setText(title);
notificationMessage.setText(message);
}
};
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(), title, body);
}
if (remoteMessage.getData().size()>0)
{
String title = remoteMessage.getData().get("title");
String message= remoteMessage.getData().get("message");
Intent intent = new Intent("com.example.linguanotification_FCM-MESSAGE");
intent.putExtra("title",title);
intent.putExtra("message",message);
LocalBroadcastManager localBroadcastManager=LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
}
public class NotificationHelper {
public static void displayNotification(Context context, String title, String body) {
Intent intent = new Intent(context, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.dd)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(context);
mNotificationMgr.notify(1, mBuilder.build());
}
}
public class MainActivity extends AppCompatActivity {
//1. Notification Channel
//2. Notification Builder
//3. Notification Manager
public static final String CHANNEL_ID = "12";
public static final String CHANNEL_NAME = "23";
public static final String CHANNEL_DESC = "34";
private EditText editTextEmail, editTextPassword;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.INVISIBLE);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
findViewById(R.id.buttonSignUp).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createUser();
}
});
}
private void createUser() {
final String email = editTextEmail.getText().toString().trim();
final String password = editTextEmail.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email required");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Password should be atleast 6 char long");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
startProfileActivity();
}else{
if(task.getException() instanceof FirebaseAuthUserCollisionException){
userLogin(email, password);
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
private void userLogin(String email, String password){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
startProfileActivity();
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
//here we are checking if the user is not null then the user already logged in
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null)
{
startProfileActivity();
}
}
private void startProfileActivity() {
Intent intent = new Intent(this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}

Working example of JNA mouse hook

Can any one provide me with a working example of JNA mouse hook, which would be able to track mouse movements/click outside my Java Swing application ?
Thanks in Advance
Yep, here is the code...
public class CWMouseHook {
public final User32 USER32INST;
public final Kernel32 KERNEL32INST;
public CWMouseHook()
{
if(!Platform.isWindows())
{
throw new UnsupportedOperationException("Not supported on this platform.");
}
USER32INST = User32.INSTANCE;
KERNEL32INST = Kernel32.INSTANCE;
mouseHook=hookTheMouse();
Native.setProtected(true);
}
public static LowLevelMouseProc mouseHook;
public HHOOK hhk;
public Thread thrd;
public boolean threadFinish = true;
public boolean isHooked = false;
public static final int WM_MOUSEMOVE = 512;
public static final int WM_LBUTTONDOWN = 513;
public static final int WM_LBUTTONUP = 514;
public static final int WM_RBUTTONDOWN = 516;
public static final int WM_RBUTTONUP = 517;
public static final int WM_MBUTTONDOWN = 519;
public static final int WM_MBUTTONUP = 520;
public void unsetMouseHook()
{
threadFinish = true;
if (thrd.isAlive())
{
thrd.interrupt();
thrd = null;
}
isHooked = false;
}
public boolean isIsHooked()
{
return isHooked;
}
public void setMouseHook()
{
thrd = new Thread(new Runnable() {
#Override
public void run()
{
try
{
if(!isHooked)
{
hhk = USER32INST.SetWindowsHookEx(14, mouseHook,KERNEL32INST.GetModuleHandle(null),0);
isHooked = true;
MSG msg = new MSG();
while ((USER32INST.GetMessage(msg, null, 0, 0)) != 0)
{
USER32INST.TranslateMessage(msg);
USER32INST.DispatchMessage(msg);
System.out.print(isHooked);
if (!isHooked)
break;
}
}
else
System.out.println("The Hook is already installed.");
}
catch (Exception e)
{ System.err.println(e.getMessage());
System.err.println("Caught exception in MouseHook!");
}
}
},"Named thread");
threadFinish = false;
thrd.start();
}
private interface LowLevelMouseProc extends HOOKPROC
{
LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam);
}
public LowLevelMouseProc hookTheMouse() {
return new LowLevelMouseProc()
{
#Override
public LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT info) {
if (nCode >= 0)
{
switch(wParam.intValue())
{
case CWMouseHook.WM_LBUTTONDOWN:
// do stuff
break;
case CWMouseHook.WM_RBUTTONDOWN:
//do stuff
break;
case CWMouseHook.WM_MBUTTONDOWN:
//do other stuff
break;
case CWMouseHook.WM_LBUTTONUP:
//do even more stuff
break;
case CWMouseHook.WM_MOUSEMOVE:
break;
default:
break;
}
/****************************DO NOT CHANGE, this code unhooks mouse *********************************/
if (threadFinish == true)
{
USER32INST.PostQuitMessage(0);
}
/***************************END OF UNCHANGABLE *******************************************************/
}
return USER32INST.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
};
}
public class Point extends Structure
{
public class ByReference extends Point implements Structure.ByReference {};
public NativeLong x;
public NativeLong y;
}
public static class MOUSEHOOKSTRUCT extends Structure
{
public static class ByReference extends MOUSEHOOKSTRUCT implements Structure.ByReference {};
public POINT pt;
public HWND hwnd;
public int wHitTestCode;
public ULONG_PTR dwExtraInfo;
}
That's all about there is to it. Cheers.
It's a basically a ripoff of the code of a guy in Sun forums...but also tested by me, and it works so cheers again.
Edit: I edited the code so it includes the LowLevelMouseProc but you can use your extension of HOOK which you can define elsewhere. It doesn't matter that much. Be wary that for some reason you have TO have the variable mouseHook as static otherwise hook just unhooks after a while.
movements:
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;
public class GlobalMouseWheelListenerExample implements NativeMouseWheelListener {
public void nativeMouseWheelMoved(NativeMouseWheelEvent e) {
System.out.println("Mosue Wheel Moved: " + e.getWheelRotation());
}
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
// Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeMouseWheelListener(new GlobalMouseWheelListenerExample());
}
}
click:
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
public class GlobalMouseListenerExample implements NativeMouseInputListener {
public void nativeMouseClicked(NativeMouseEvent e) {
System.out.println("Mosue Clicked: " + e.getClickCount());
}
public void nativeMousePressed(NativeMouseEvent e) {
System.out.println("Mosue Pressed: " + e.getButton());
}
public void nativeMouseReleased(NativeMouseEvent e) {
System.out.println("Mosue Released: " + e.getButton());
}
public void nativeMouseMoved(NativeMouseEvent e) {
System.out.println("Mosue Moved: " + e.getX() + ", " + e.getY());
}
public void nativeMouseDragged(NativeMouseEvent e) {
System.out.println("Mosue Dragged: " + e.getX() + ", " + e.getY());
}
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
//Construct the example object.
GlobalMouseListenerExample example = new GlobalMouseListenerExample();
//Add the appropriate listeners for the example object.
GlobalScreen.getInstance().addNativeMouseListener(example);
GlobalScreen.getInstance().addNativeMouseMotionListener(example);
}
}

Resources