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.
Related
I am trying to start a service inside a Unity3d Android plugin but can not make it work. Is working on Android Studio test app, but the service call fail inside unity.
My service class
public class ProximityService extends Service {
private String TAG = "iProximity: ";
NotificationManager _NotificationManager;
private Context _Context;
private static Timer _Timer = new Timer();
public ProximityService() {
}
private void sendNotification() {
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, iRealUnityPlayerActivity.class), 0);
builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ireal)
.setContentTitle("Notification")
.setContentText("message")
.setTicker("msg: mensaje")
.setSound(sound)
.setAutoCancel(true);
builder.setContentIntent(contentIntent);
_NotificationManager.notify(0, builder.build());
}
#Override
public void onCreate() {
Log.i(TAG, "onCreate()");
super.onCreate();
_Context = getApplicationContext();
_NotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
// methods
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommanf()");
//startProximity();
sendNotification();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind()");
// TODO: Return the communication channel to the service.
return null;
}
}
Java class that is used to start the service:
public final class StatusCheckStarter {
static Context myContext;
// Called From C# to get the Context Instance
public static void ReceiveContextInstance(Context tempContext) {
myContext = tempContext;
}
public static String StartProximityService()
{
String result = "OK";
try
{
myContext.startService(new Intent(myContext, ProximityService.class));
}
catch (Exception e) {
e.printStackTrace();
result = e.getMessage();
}
return result;
}
public static String Dummy() {
return "DONEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE";
}
}
Unity C# code that is used to call the java functions to start the service:
AndroidJavaClass unityClass;
AndroidJavaObject unityActivity;
AndroidJavaObject unityContext;
AndroidJavaClass customClass;
string a1 = "";
string a2 = "";
string a3 = "";
string a4 = "";
void Start () {
//Replace with your full package name
sendActivityReference("info.ireal.proximitylib.StatusCheckStarter");
//Now, start service
startService();
Debug.Log ("START");
}
void sendActivityReference(string packageName)
{
unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");
customClass = new AndroidJavaClass(packageName);
customClass.CallStatic("ReceiveContextInstance", unityContext);
}
void startService()
{
a4 = customClass.CallStatic<string> ("Dummy");
a3 = customClass.CallStatic<string>("StartProximityService");
}
The Dummy method is working and return a string value, but the service does not work
Adb logcat message:
Unable to start service Intent {
cmp=info.ireal.proximitytest/info.ireal.proximitylib.ProximityService
VirtualScreenParam=Params{mDisplayId=-1, null, mFlags=0x00000000)} }
U=0: not found
I really appreciate any help Best regards
Mariano
I am using the solution from this thread but still cant make it work.
EDIT
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
android:installLocation="preferExternal"
android:versionCode="1"
android:versionName="1.0">
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true"/>
<application
android:theme="#style/UnityThemeSelector"
android:icon="#drawable/app_icon"
android:label="#string/app_name"
android:debuggable="true">
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<service android:name="info.ireal.proximitylib.ProximityService" />
<!---<service android:name="ProximityService" />-->
</application>
</manifest>
This could be the Manifest. Make sure to include the service class in the service tag.
It could be any of these problems below. Build, Run and test each one you try.
1.Add the class to the Manifest.
<application
<service android:name=".ProximityService" />
</application>
2.Add the class with the full path to the Manifest.
If this does not work, use the full service class package name
<application
<service android:name="info.ireal.proximitylib.ProximityService" />
</application>
3.Add the class to the Manifest from Unity itself.
Again, if that fails, go to <UnityInstallationDirecory>\Editor\Data\PlaybackEngines\AndroidPlayer\Apk
Copy the AndroidManifest.xml from that place file to your Assets\Plugins\Android directory then include the service tag code above in the Manifest. Save and run.
4.Finally, use Activity instead of Context.
Changes on the Java side:
A.Rename static Context myContext; to static Activity myActivity;
B.Change
public static void ReceiveContextInstance(Context tempContext) {
myContext = tempContext;
}
to
public static void ReceiveContextInstance(Activity tempActivity) {
myActivity = tempActivity;
}
Changes on C# side:
C.Replace customClass.CallStatic("ReceiveContextInstance", unityContext); with customClass.CallStatic("ReceiveContextInstance", unityActivity);
Is there any way to develop an app that starts up when a user receives a phone call? I can't really go into details about the idea but was wondering if there was some call that would allow that to happen.
You can use a Broadcast Receiver for thatlike this
public class PhoneStatReceiver extends BroadcastReceiver{
private static final String TAG = "PhoneStatReceiver";
private static boolean incomingFlag = false;
private static String incoming_number = null;
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
incomingFlag = false;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i(TAG, "call OUT:"+phoneNumber);
}else{
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
incomingFlag = true;//标识当前是来电
incoming_number = intent.getStringExtra("incoming_number");
Log.i(TAG, "RINGING :"+ incoming_number);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(incomingFlag){
Log.i(TAG, "incoming ACCEPT :"+ incoming_number);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if(incomingFlag){
Log.i(TAG, "incoming IDLE");
}
break;
}
}
}
}
Register this receiver in AndroidManifest like this
<receiver android:name=".filter.PhoneStatReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>
Yes We can start an diffrent app when User receives a phone call.Example :- Truecaller,Mobile no. Tracker apps.
You can use Services for this.
public class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
final Context cont = context;
final Intent in = intent;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(cont, MainActivity.class);
i.putExtras(in);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
cont.startActivity(i);
}
}, 1000);
}
}
}
You must implement this handler with postDelayed so that your activity screen can be on top of native call screen. If you dont want this to happen then you must remove this handler.
Add these to your manifest--
<receiver
android:name=".CallReceiver"
android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
You have to use another extra_state for onreceiving call. This is for ringing state.
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.
Hi i am trying to get the device location using the Location api in android using the device network or wifi connection. However it doesnt seem to get the latt or longitude.
i have created a location provider and manager, and registered a location listener.
i then
launched
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
and from that point on, the app doesnt retrieve new location changes at all. what am i missing?
here is my userLocation Code
public class UserLocation implements LocationListener{
public static final int UPDATE_LATT = 0;
private static final int TIME_INTERVAL = 1000;
private static final int DISTANCE = 10;
private LocationManager locationManagaer;
private LocationProvider locationProvide;
private Handler mHandler;
public UserLocation(Context context, Handler handler){
locationManagaer = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationProvide = locationManagaer.getProvider(LocationManager.NETWORK_PROVIDER);
mHandler = handler;
}
public void startSearchLocation(){
Log.d("", "sart location search");
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("", "location update on " + location.getLongitude());
Message.obtain(mHandler,UPDATE_LATT, new Position(location.getLongitude(), location.getLatitude()));
}
#Override
public void onProviderDisabled(String provider) {
Log.d("", "onProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("", "onStatusChanged");
}
}
here is my activity that uses this class to setup and listen for new locations
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
position = (Position) msg.obj;
Toast.makeText(
getApplicationContext(),
position.getLattitude() + " " + position.getLongetude(),
Toast.LENGTH_LONG).show();
}
};
userLocation = new UserLocation(this, mHandler);
initializeViews();
userLocation.startSearchLocation();
}
Here is my position POJO
public class Position {
private double longetude;
private double lattitude;
public Position(){
}
public Position(double longetude, double lattitude){
}
public double getLongetude() {
return longetude;
}
public void setLongetude(double longetude) {
this.longetude = longetude;
}
public double getLattitude() {
return lattitude;
}
public void setLattitude(double lattitude) {
this.lattitude = lattitude;
}
}
Here is part of my manifest file
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jr.haliotest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Logcat:
03-23 20:19:14.309: D/(16992): sart location search
03-23 20:19:14.384: E/(16992): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
03-23 20:19:14.384: I/(16992): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.449: I/(16992): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.514: I/(16992): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl
Testing on a htc one x thats rooted if that helps. wifi is on and god signal
If you are within a building then it is probably that your device is not able to connect to a GPS Provider. I would suggest if you move to a more open space so that you can get a signal.
One hint that if the device is connected to receive a gps signal. The sign of the gps will stop blinking and will become solid.
I would start by checking if your phones location services are enabled and maybe try rebooting. Also try using "GPS" instead of "network" to see if the problem is related to your network not providing location info.
From my experience wifi networks will sometimes simply not provide location info. I'm not sure if that's also true for cell networks, but I suspect there is no guarantee.
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.