Why does this static Receiver not respond to the ACTION_POWER_(DIS)CONNECTED Event? - static

I want a STATIC Broadcast Receiver to get fired, whenever the Phone gets charged or not. In my Manifest.xml, i have written the following Entry:
<receiver
android:name=".Starter">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
The Broadcast Receiver itself looks like this:
public class Starter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "blablabla", Toast.LENGTH_LONG).show();
}
}
When I register the Receiver programmatically, everything works fine, but I want the Receiver also to respond, when the Activity is not open, so I have to make a static Receiver.
Thank you for your help!!!

Related

How to pass parameters to Apache Camel through command line?

I use Apache Camel’s Spring Main to boot my Camel application. I need my application to read the command line arguments to set some parameters. So, I cannot use property files.
At the moment, I can pass arguments via the JVM system properties, and it works well:
Application.java
public class Application extends org.apache.camel.spring.Main {
public static void main(String[] args) throws Exception {
Application app = new Application();
instance = app;
app.run(args);
}
}
camel-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="shutdownBean" class="com.example.ShutdownBean" />
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file:{{inputFile}}?noop=true"/>
<to uri="bean:shutdownBean" />
</route>
</camelContext>
</beans>
I run the app with java com.example.Application -DinputFile=C:/absolute/path/to/watch and everything works fine:
…
FileEndpoint INFO Using default memory based idempotent repository with cache max size: 1000
InternalRouteStartupManager INFO Route: route1 started and consuming from: file://C:/absolute/path/to/watch
AbstractCamelContext INFO Total 1 routes, of which 1 are started
…
But I would like to have some input validation and make the app easier to use because -D could be confusing for a non Java user. So I change Application.java:
public class Application extends org.apache.camel.spring.Main {
private File inputFile;
public static void main(String[] args) throws Exception {
Application app = new Application();
instance = app;
app.run(args);
}
public Application() {
addOption(new ParameterOption("i", "inputFile", "The input file", "inputFile") {
#Override
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
File file = FileUtils.getFile(parameter);
// some business validation
setInputFile(file);
}
});
}
private void setInputFile(File inputFile) {
this.inputFile = inputFile;
}
}
Then, I could use the following command to run the application: java com.example.Application -inputFile C:/absolute/path/to/watch
How can I use my inputFile field into my Camel route?
Call addProperty(String key, String value) in your doProcess method. Then it will be accessible throught {{key}} notation.
MyApplication:
public final class MyApplication extends Main {
private MyApplication() {
super();
addCliOption("g", "greeting", "Greeting");
addCliOption("n", "name", "Who to greet");
}
public static void main(String[] args) throws Exception {
MyApplication app = new MyApplication();
app.configure().addRoutesBuilder(MyRouteBuilder.class);
app.run(args);
}
private void addCliOption(String abbrevation, String parameterName, String description) {
addOption(new ParameterOption(abbrevation, parameterName, description, parameterName) {
protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) {
addProperty("console." + parameterName, parameter);
}
});
}
}
MyRouteBuilder:
public class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("quartz:foo")
.log("{{console.greeting}} {{console.name}}");
}
}
java org.apache.camel.example.MyApplication -greeting Hello -name Morgan
23:10:25.862 [DefaultQuartzScheduler-MyCoolCamel_Worker-1] INFO route1 - Hello Morgan
23:10:26.832 [DefaultQuartzScheduler-MyCoolCamel_Worker-2] INFO route1 - Hello Morgan
23:10:27.829 [DefaultQuartzScheduler-MyCoolCamel_Worker-3] INFO route1 - Hello Morgan

Simple Camel test fails with no messages recieved

Am using Spring Boot and I have just added camel to it.
I have a simple camel route setup :
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
#Component
public class MyRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("file://in").to("file://out");
}
}
When I try to create simple test for this route with :
#RunWith(CamelSpringBootRunner.class)
#SpringBootTest
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MyRouteTest extends CamelTestSupport {
#Autowired
private CamelContext camelContext;
#Produce(uri = "file://in")
private ProducerTemplate producerTemplate;
#EndpointInject(uri = "mock:file://out")
private MockEndpoint mockEndpoint;
#Test
public void routeTest() throws Exception {
mockEndpoint.expectedMessageCount(1);
producerTemplate.sendBody("Test");
mockEndpoint.assertIsSatisfied();
}
}
It fails with
mock://file://out Received message count. Expected: <1> but was: <0>
Not sure what could be a problem here. I have producer template that has uri as my route from point and am mocking to endpoint with EndpointInject and the the mock uri?
Fixed but not 100%
If I change route from real one
from("file://in").to("file://out");
to
from("file://in").to("mock:out");
And in my test override
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new MyRoute();
}
to create specific route
and strangest of all ! Had to remove :
#SpringBootTest
and after that
private CamelContext camelContext;
And then it started working !
But unfortunately not what I need, still there are things that need to be fixed, I would like to use my real prod route !
from("file://in").to("file://out");
And if possible not use advise on route , but just mock it , tried with
mock:file://out in test, but it didnt work :(
and also , it does not work with #SpringBootTest ??? very strange ?!
You need to add
#Override
public String isMockEndpoints() {
return "*";
}
This should mock all the enpoints and then you can use mock:file:out for example
If I am not misstaken you are mocking your output endpoint yet your endpoint endpoint is a file endpoint. When you send a message you need to drop a message to whereever the file endpoint is polling. Otherwise you need to mock that as well.

#Around Advice Not working with Controller. #Before,#After etc working without errors

I am trying to use the Around method around my rest controller using a logger class. I get the output "Before calling Controller","After calling controller" etc, but I don't get any return result in my postman.
The code works fine with #Before method and #After.
The ReST Controller looks like this.
#RestController("/")
public class DummyController {
#RequestMapping(value="hello",method=RequestMethod.GET)
public String dummyMethod() {
System.out.println("In Controller...");
return "Hello There";
}
}
This is the Aspect class.
#Aspect
#Component
public class Logger {
#Around("within(DummyController)")//Around Not working....
public void printMessage(ProceedingJoinPoint p) throws Throwable
{
System.out.println("Before Calling Method...");
p.proceed();
System.out.println("After calling method...");
}
The bean configuration is as below:
<mvc:annotation-driven />
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.aop.test"> </context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
My output is:
Before Calling Method...
In Controller...
After calling method...
But the webservice output is blank in postman instead of "Hello There". The status is "200 OK"
The code works as expected with other Advices like #Before,#After...
Any pointers on where the code went wrong?
Thanks in Advance..
change your Aspect to below and it should work.
#Aspect
#Component
public class Logger {
#Around("within(DummyController)")//Around Not working....
public Object printMessage(ProceedingJoinPoint p) throws Throwable
{
System.out.println("Before Calling Method...");
Object result = p.proceed();
System.out.println("After calling method...");
return result;
}
Notice that I made the advice return the object returned by ProceedingJoinPoint

google maps - show current position coordinates

I want to show coordinates from my current position on map. Here is the code and it doesn't work like it should. It only shows map within defined parameters, but when I click on button that shows my current position, nothing happens.
I made this code using Android Studio tutorials on web.
I am using Android studio and just a fresh learner.
This is also what I get in event log when I run the app on my smartphone:
21:56:48 Can't bind to local 8600 for debugger
21:56:49 An established connection was aborted by the software in your host machine
java.io.IOException: An established connection was aborted by the software in your host machine
at sun.nio.ch.SocketDispatcher.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
at com.android.ddmlib.Client.sendAndConsume(Client.java:686)
at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:349)
at com.android.ddmlib.Client.requestAllocationStatus(Client.java:525)
at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:569)
at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:544)
at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:360)
at com.android.ddmlib.Devic...
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity_koordinate"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
package com.example.apollo.kartamackovec;
import android.location.Location;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity_koordinate extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, MapsActivity {
public GoogleMap mMap;
public GoogleApiClient client;
public TextView mLongitudeText;
public TextView mLatitudeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng mackovec = new LatLng(46.4239, 16.4339);
mMap.addMarker(new MarkerOptions().position(mackovec).title("Marker u Mačkovcu"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(mackovec));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mackovec, 18));
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(Bundle connectionHint) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(client);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
Toast.makeText(this, "Location " + mLatitudeText+","+mLongitudeText,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "noconnection",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onStart() {
client.connect();
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.apollo.kartamackovec/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
client.disconnect();
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.apollo.kartamackovec/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "noconnection",
Toast.LENGTH_LONG).show();
}
}

Nlog doesn't print messages on application close

All ViewModel classes inherit from a base class:
public abstract class ScreenBase : ViewModelBase, IScreen, IDisposable
{
protected readonly NLog.Logger _logger;
protected ScreenBase()
: this(Messenger.Default) { }
protected ScreenBase(IMessenger messenger)
: base(messenger)
{
_logger = NLog.LogManager.GetLogger(this.GetType().Name);
_logger.Debug("{0} ({1}) constructed. ", this.GetType().Name, this.GetHashCode());
}
~ScreenBase()
{
FinalizeProc();
}
[Conditional("DEBUG")]
private void FinalizeProc()
{
_logger.Debug("{0} ({1}) Finalized. ", this.GetType().Name, this.GetHashCode());
}
}
As you can see, any time instance of ViewModel is created / destroyed, it should log it. I am logging it into Console window and file:
<targets>
<!-- add your targets here -->
<target name="logDebugInfo" xsi:type="File" deleteOldFileOnStartup="true" fileName="${specialfolder:folder=CommonApplicationData}/MyApp/debug.txt" layout="${longdate} | ${uppercase:${level}} | ${stacktrace} | ${message}${onexception:EXCEPTION OCCURRED\:${exception:format=tostring}}" />
<target name="console" xsi:type="Console" />
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Trace" maxlevel="Info" writeTo="logDebugInfo" />
<logger name="*" minlevel="Trace" writeTo="console" />
</rules>
Each message is properly logged until the application is closed. When 'X' Close button is pressed on the main view, I do not do anything specific in code, I let the application close itself. However, no 'Finalized' messages are displayed at that point.
Anyone knows why?
The reason why this is happening is that Logger is being destroyed on application shutdown.

Resources