Query a web page - java

How must I go about coding to get an app to query the state of a device, through internet protocol to see if its on or off.
public void port0156 (View view) {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://192.168.2.66/index.html?o0=1");
}

You can register a broadcastreceiver to monitor connectivity changes.
In manifest :
<receiver android:name="com.yourpackage.NetworkChangeReciever" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
the class in com.yourpackage :
public class NetworkChangeReciever extends BroadcastReceiver {
private final static String TAG = "NetworkChangeReciever";
public interface NetworkChangeRecieverListener {
public void OnNetworkChangeReciever(boolean wifiConnected);
}
#Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) || mobile.isAvailable()) {
Log.d(TAG, "Network Available.");
}
else {
Log.d(TAG, "Network Unavailable");
}
}
}

You can see if the app is online (or reachable) by seeing if it returns a ping you can easily do this by using OS and parsing the output.

Related

App crashes after granting USB permission - Unity app using aar java plugin

I am creating an Unity app which will be controlling Numato GPIO USB powered controller through smartphone USB connection. Since I have to connect the controller to phone I have no debug log so I have no idea what is going on. Thus, I include plugin code and a custom manifest which I use in Unity.
I get questioned by the App if I want to grant permission to control the device (Shows right device name etc) and after I grant the permission app crashes immediately.
Is there a way to check what causes the error? Or maybe I don't see something obvious here.
public class PluginInstance extends Activity {
private static Activity unityActivity;
private static Context unityContext;
public Gpio laser1;
public static void receiveUnityActivity(Activity tActivity) {
unityActivity = tActivity;
}
public static void receiveUnityContext(Context tContext) { unityContext = tContext; }
//Debugging purposes
public void Toast(String msg) {
Toast.makeText(unityActivity, msg, Toast.LENGTH_SHORT).show();
}
//Action Usb Permission
public static final String ACTION_USB_PERMISSION = "com.unity3d.player.UnityPlayerActivity.USB_PERMISSION";
public DevicesManager mDevicesManager;
//USB permission
public final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
Bundle deviceIndexBundle = intent.getExtras();
if (deviceIndexBundle == null) {
return;
}
int deviceIndex = deviceIndexBundle.getInt(AppConstant.EXTRA_DEVICE_INDEX);
Toast.makeText(unityActivity, "Usb permission granted", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(unityActivity, "Usb permission declined", Toast.LENGTH_SHORT).show();
}
unregisterReceiver(mUsbReceiver);
}
}
}
};
public void InstantiateManager() {
mDevicesManager = DevicesManager.getInstance();
}
public void GetGpios() {
NumatoUSBDevice numatoUSBDevice = mDevicesManager.getDevices().get(0);
Gpio lazer1 = numatoUSBDevice.mGpios.get(1);
}
public void GpioOn() {
laser1.setCurrentOutputState(true);
laser1.setState(true);
}
public void GpioOff() {
laser1.setCurrentOutputState(false);
laser1.setState(false);
}
public void EnumerateDevices() {
UsbManager manager = (UsbManager) unityActivity.getSystemService(Context.USB_SERVICE);
int index = 0;
ArrayList<UsbDevice> cdcAcmDevices = CdcAcmDriver.ListDevices(manager);
mDevicesManager.clearDevices();
ArrayList<Integer> supportedDevices = NumatoUSBDevice.GetSupportedProductIds();
if(!cdcAcmDevices.isEmpty()){
for (UsbDevice cdcAcmDevice : cdcAcmDevices){
int vendorId = cdcAcmDevice.getVendorId();
if(vendorId == NumatoUSBDevice.VID_NUMATOLAB && supportedDevices.contains(cdcAcmDevice.getProductId())){
mDevicesManager.addDevice(new NumatoUSBDevice(index, cdcAcmDevice, manager));
index++;
}
}
}
}
public void MakeConnection() {
NumatoUSBDevice numatoUSBDevice = mDevicesManager.getDevices().get(0);
UsbManager manager = (UsbManager) unityActivity.getSystemService(Context.USB_SERVICE);
//TODO unityContext in mPermissionIntent
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(unityContext, 0,
new Intent(ACTION_USB_PERMISSION).putExtra(AppConstant.EXTRA_DEVICE_INDEX, 0), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
unityActivity.registerReceiver(mUsbReceiver, filter);
manager.requestPermission(numatoUSBDevice.getDevice(), mPermissionIntent);
}
}
And the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<application>
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:theme="#style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter"/>
</activity>
</application>
</manifest>
Edit: I managed to access debug log through wifi and this is what I get:
FATAL EXCEPTION: main
Process: com.jonquil.A2NumatoController, PID: 16837
java.lang.RuntimeException: Error receiving broadcast Intent { act=com.unity3d.player.UnityPlayerActivity.USB_PERMISSION flg=0x10 (has extras) } in com.jonquil.unityplugin.PluginInstance$1#7d45921
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1689)
at android.app.LoadedApk$ReceiverDispatcher$Args$$ExternalSyntheticLambda0.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7838)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.unregisterReceiver(android.content.BroadcastReceiver)' on a null object reference
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:769)
at com.jonquil.unityplugin.PluginInstance$1.onReceive(PluginInstance.java:63)
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1679)
... 9 more
This looks like there is a problem with broadcast receiver since error is caused by invoking method on a null object reference.

Android Internet Connection checker OUTSIDE the app

My app needs to do something whenever the internet is connected and vice-versa. However, I need to do this OUTSIDE my application. There are a lot of ideas and help here on stackoverflow but it is always WITHIN the application. I know that the AlarmManager works outside the application but it would just be draining the battery if I try to check if there's internet connection every 5 minutes. What I wanted is to check the connection outside the app to download something.
I also found out that Intent Service can work outside the application as well. I have tried to put this inside the Wakeful Broadcast Receiver. However, it is still not being called.
Can someone out there help me? Thanks!
Here's my Wakeful Broadcast Receiver
public class ConnectivityOutsideAppReceiver extends WakefulBroadcastReceiver {
private static final String LOG_TAG = ConnectivityOutsideAppReceiver.class.getSimpleName();
private ConnectivityManager connectivityManager;
private static boolean connection = false;
#Override
public void onReceive(Context context, Intent intent){
ComponentName comp = new ComponentName(context.getPackageName(),
ConnectivityOutsideAppService.class.getName());
// Start the service, keeping the device awake while it is
// launching.
startWakefulService(context, (intent.setComponent(comp)
));
}
}
This is the Intent Service
public class ConnectivityOutsideAppService extends IntentService {
private static final String LOG_TAG = ConnectivityOutsideAppService.class.getSimpleName();
private ConnectivityManager connectivityManager;
private static boolean connection = false;
private Context context;
public ConnectivityOutsideAppService() {
super(ConnectivityOutsideAppService.class.getSimpleName());
this.context = context;
}
#Override
protected void onHandleIntent(Intent intent) {
connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
checkConnectionOnDemand();
Log.e(LOG_TAG, " ## onHandleIntent##");
if (connection == true
&& intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
false)) {
Log.e(LOG_TAG, " ## connection == true ##");
connection = false;
} else if (connection == false
&& !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
false)) {
Log.e(LOG_TAG, " ## connection == false ##");
connection = true;
}
ConnectivityOutsideAppReceiver.completeWakefulIntent(intent);
}
public static boolean hasConnection() {
return connection;
}
private void checkConnectionOnDemand() {
Log.e(LOG_TAG, " ## checkConnectionOnDemand ##");
final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null || info.getState() != NetworkInfo.State.CONNECTED) {
if (connection == true) {
Log.e(LOG_TAG, " ## connection == true ##");
connection = false;
}
} else {
if (connection == false) {
Log.e(LOG_TAG, " ## connection == false ##");
connection = true;
}
}
}
}
This is my Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<service
android:name="com.timetrackermobilelog.BusinessServices.ConnectivityOutsideAppService"
android:exported="false"/>
<receiver android:name="com.timetrackermobilelog.Utilities.ConnectivityOutsideAppService"
android:enabled="true"
android:process=":remote">
<intent-filter android:priority="1000" >
<action android:name="com.timetrackermobilelog.Utilities.ConnectivityOutsideAppService" />
<category android:name="com.Utilities" />
</intent-filter>
</receiver>
I have tried registering the receiver inside the Activity but it doesn't work as well.
IntentFilter intentFilter = new IntentFilter("com.pointwest.timetrackermobilelog.Utilities.ConnectivityOutsideAppReceiver");
ConnectivityOutsideAppReceiver connectivityOutsideAppReceiver = new ConnectivityOutsideAppReceiver();
registerReceiver(connectivityOutsideAppReceiver, intentFilter);
Is there anything that I missed?
Thanks to #Mike M. in giving the answer with just a few lines of changes.
In Android Manifest, change it to :
<intent-filter android:priority="1000" >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
And onHandleIntent of the Service, change it to :
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Android Broadcast Receiver not working (with two receiver)

I have two BroadcastReceiver and only one is working now.
Manifest
<receiver
android:name="com.example.basicplayerapp.core.AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
<!-- WebSocket -->
<receiver
android:name="com.example.basicplayerapp.core.NetworkReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service android:name="com.example.basicplayerapp.core.WebSocketServices"></service>
When I have only the AudioJackReceiver it works prefect. Now that I added NetworkReceiver the AudioJackReceiver stopped work. Any advice please. thanks.
onCreate of the Video Activity
if (HEADSET_ONLY) { myAudioJackReceiver = new AudioJackReceiver(); }
AudioJackReceiver
public class AudioJackReceiver extends BroadcastReceiver {
public static final String TAG = AudioJackReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
audio.setStreamMute(AudioManager.STREAM_MUSIC, true);
Toast.makeText(context, "Please plug in your headset to enjoy the sound.", Toast.LENGTH_LONG).show();
makeLog("i", "Headset is unplugged");
break;
case 1:
audio.setStreamMute(AudioManager.STREAM_MUSIC, false);
makeLog("i", "Headset is plugged");
break;
default:
makeLog("i", "I have no idea what the headset state is");
Toast.makeText(context, "ERROR => I have no idea what the headset state is", Toast.LENGTH_LONG).show();
}
}
}//end onReceive
NetworkReceiver
public class NetworkReceiver extends BroadcastReceiver {
public static final String TAG = NetworkReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.i(TAG, "connected");
Intent startServiceIntent = new Intent(context, WebSocketServices.class);
context.startService(startServiceIntent);
}
else if(networkInfo != null){
NetworkInfo.DetailedState state = networkInfo.getDetailedState();
Log.i(TAG, state.name());
}
else {
Log.i(TAG, "lost connection");
}
}//end onReceive
};//end NetworkReceiver

Connect WiFi Manager from separate AsyncTask class in Android

I have an application that uses an AsyncTask to connect to WiFi using WifiManager.
Now, I am using this in my MainActivity class as
public class connectWifi extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
public connectWifi(MyActivity activity) {
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Connecting to WiFi. Please Wait.");
dialog.show();
}
#Override
protected void onPostExecute(Void result) {
connected = true;
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo conn = wifi.getConnectionInfo();
Context context = getApplicationContext();
CharSequence wifi_on = "Connected to " + conn.getSSID();
int duration = Toast.LENGTH_LONG;
Toast responseToast = Toast.makeText(context, wifi_on, duration);
responseToast.show();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... voids) {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
try {
Thread.sleep(3000);
} catch (Exception e) {
}
return null;
}
}
Now, I have another class AlarmReceiver which gets called via a Broadcast. I am performing some network based action in that class which needs me to connect to WiFi first.
How can I create a separate class for connectWifi which does not involve first running MainActivity?
The issue I am facing is in creating the Context object which says Non-static 'getApplicationContext()' cannot be referenced from static context.
The same issue is with getSystemService(). How can I create this class as needed?
abc is the AsyncTask class.
AlarmReceiver is the BroadcastReceiver
My current flow of control is as follows:
START PROCEDURE
- AlarmManager receives Broadcast
- AlarmManager calls enableWifi() in abc
- enableWifi() connects to WiFi
- AlarmManager checks for connection state
- AlarmManager then calls new abc().execute("DATA1")
- abc then performs the doInBackground task (network request)
- AlarmManager calls disableWifi() in abc to end WiFi
END PROCEDURE
You can create a separated class that depends on Context. Both Activity and a BroadcastReceiver can provide a Context to this class.
Activity is a subclass of Context, so you can pass the Activity as parameter.
And the first parameter of onReceive from BroadcastReceiver is the Context.
So you can create an class that receives an Context instance an use the WifiManager:
// This can run outside UI Thread
public static void enableWifi(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
// This must run on UI Thread
public static void verifyWifi(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo conn = wifi.getConnectionInfo();
CharSequence wifi_on = "Connected to " + conn.getSSID();
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, wifi_on, duration).show();
}
You can use this class to detect when Wifi is enabled or change it's state.
public class NetworkChangeReceiver extends BroadcastReceiver {
// Static Listener, you can change this
static OnNetworkConnectionChangedListener mListener;
// Service to check if Wifi is connected or not
ConnectivityManager mConnectivityManager;
#Override
public void onReceive(Context context, Intent intent) {
if(mListener != null) {
if(mConnectivityManager == null) {
mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
mListener.onConnectionChanged(NetworkStatusHelper.getConnectivityStatus(mConnectivityManager) != NetworkStatusHelper.TYPE_NOT_CONNECTED);
}
}
public static boolean isConnected(Context context) {
return NetworkStatusHelper.getConnectivityStatus((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)) != NetworkStatusHelper.TYPE_NOT_CONNECTED;
}
public static void setOnNetworkConnectionChangedListener(OnNetworkConnectionChangedListener listener) {
mListener = listener;
}
public interface OnNetworkConnectionChangedListener {
public void onConnectionChanged(boolean connected);
}
}
With this you i'll need to require the ACCESS_NETWORK_STATE permission.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And you i'll need to add a receiver for CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED
<receiver
android:name="yourpackage.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
With this you can track when Wifi change its connectivity and is connected.

how to stop displaying apps in active application window in android

I made an app as a service which runs in background. This app is basically a battery alarm. It works fine but the only problem is that when this service is running it also displays this app in the active application task manager. So when I exit this app it stops that service as well. So what I want is to only stop this service when the user unchecks the box in the app settings. If it is checked then it should not be stopped even if it is closed in active application task manager.
How can I stop showing my app in task manager?
I think I should provide code over here This is my service class
public class BatteryService extends Service {
Notify notification = new Notify();
BatteryAlarm alarm = new BatteryAlarm();
private MediaPlayer mMediaPlayer;
boolean flag = false;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
//method to start service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notification.initNotification(this, false);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
//Broadcast receiver to get battery info
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context c, Intent i) {
//notification.initNotification(c);
int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = i.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
SharedPreferences getAlarm = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String alarms = getAlarm.getString("ringtones", "content://media/internal/audio/media/45"); // /system/media/audio/ringtones/ANDROMEDA.ogg , content://media/internal/audio/media/45
Uri uri = Uri.parse(alarms);
if(plugged == 2) {
if(level == 100) {
if(uri != null) {
if(flag == false) {
playAlarm(c, uri);
notification.initNotification(c, true);
Toast.makeText(c, "Battery charge is completed. Unplug your mobile phone!", Toast.LENGTH_LONG).show();
flag = true;
}
}
}
} else if (plugged == 0) {
if(uri != null) {
stopAlarm();
}
notification.cancelNotification(c);
//Toast.makeText(c, "Mobile is unplugged", Toast.LENGTH_LONG).show();
}
}
};
//play alarm method
private void playAlarm(Context c, Uri uri) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(getBaseContext(), uri);
final AudioManager audioManager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (Exception ex) {
ex.printStackTrace();
onDestroy();
}
}
//method to stop playing alarm
private void stopAlarm() {
mMediaPlayer.stop();
flag = false;
}
//method to stop service
public void onDestroy() {
super.onDestroy();
notification.cancelNotification(this);
unregisterReceiver(this.mBatInfoReceiver);
stopAlarm();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
This is my main activity
public class BatteryNotify extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.xml.prefs);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences getCB = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cb = getCB.getBoolean("checkbox", true);
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkbox");
if(cb == true) {
startService(new Intent(getBaseContext(), BatteryService.class));
} else if(cb == false) {
stopService(new Intent(getBaseContext(), BatteryService.class));
}
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("true")) {
startService(new Intent(getBaseContext(), BatteryService.class));
} else {
stopService(new Intent(getBaseContext(), BatteryService.class));
}
return true;
}
});
}
}
and here is my menifest file
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".BatteryNotify"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BatteryService"></service>
</application>
The best way to do this would be to create a BroadcastReceiver, register it in the manifest with the appropriate intent-filters and when it receives one it starts the Service or Activity to perform whatever task you need.
EDIT:
Create your BroadcastReceiver as a separate class and register it in the manifest. When it receives a battery event, create a PendingIntent to start the Service. That way it doesn't matter if your app isn't running. It will be started for you.
How can I stop showing my app in task manager?
You can't, for obvious security reasons.

Categories

Resources