NotificationListenerService gets killed but not restarted - Java for Android App Development

Hi all i'm having troubles with an app that I'm developing. I make use of NotificationListenerService, prompt the user to set the Notification permission from the menu and all works flawlessly. But when I update my app, or when my service gets killed it, for unknown reasons, doesn't restart.
In `onCreate()` I retain a reference to the service with `instance = this;` that I use to determine if my service is running from other classes.
This is some methods in `onNotificationPosted(StatusBarNotification notification)` that extends NotificationListenerService:
PHP:
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if (MyOtherService.hasInstance()) {
Log.v(TAG, "onNotificationPosted called by system");
int count_debug = 1;
for (StatusBarNotificationListenerInterface listener : toBeNotified) {
if(listener != null) {
Log.v(TAG, "Loop call #" + count_debug++);
listener.onNotificationHotAdded(sbn);
}
}
} else {
// MyOtherService isn't running. Does nothing but clearing toBeNotified list.
toBeNotified.clear();
Log.v(TAG, "onNotificationPosted: MyOtherService is stopped ");
}
}
public static void registerForNotifications(StatusBarNotificationListenerInterface listener) {
if (!toBeNotified.contains(listener)) {
Log.v(TAG, listener.getClass().getCanonicalName() + " added to toBeNotified list");
toBeNotified.add(listener);
}
}
NOTE: MyOtherService extends DreamService and just register itself calling the `registerForNotifications()` method.
In the `MyNotificationListener` I override `onStartCommand` returning `START_STICKY`
I'm really going crazy with this stuff being killed almost at each update.

klarkent said:
Hi all i'm having troubles with an app that I'm developing. I make use of NotificationListenerService, prompt the user to set the Notification permission from the menu and all works flawlessly. But when I update my app, or when my service gets killed it, for unknown reasons, doesn't restart.
In `onCreate()` I retain a reference to the service with `instance = this;` that I use to determine if my service is running from other classes.
This is some methods in `onNotificationPosted(StatusBarNotification notification)` that extends NotificationListenerService:
PHP:
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if (MyOtherService.hasInstance()) {
Log.v(TAG, "onNotificationPosted called by system");
int count_debug = 1;
for (StatusBarNotificationListenerInterface listener : toBeNotified) {
if(listener != null) {
Log.v(TAG, "Loop call #" + count_debug++);
listener.onNotificationHotAdded(sbn);
}
}
} else {
// MyOtherService isn't running. Does nothing but clearing toBeNotified list.
toBeNotified.clear();
Log.v(TAG, "onNotificationPosted: MyOtherService is stopped ");
}
}
public static void registerForNotifications(StatusBarNotificationListenerInterface listener) {
if (!toBeNotified.contains(listener)) {
Log.v(TAG, listener.getClass().getCanonicalName() + " added to toBeNotified list");
toBeNotified.add(listener);
}
}
NOTE: MyOtherService extends DreamService and just register itself calling the `registerForNotifications()` method.
In the `MyNotificationListener` I override `onStartCommand` returning `START_STICKY`
I'm really going crazy with this stuff being killed almost at each update.
Click to expand...
Click to collapse
just to help others ( sorry for old post) bute start_sticky has a bug in android 4.4+
https://code.google.com/p/android/issues/detail?id=63793

Related

[Q] How to read directories?

Hey guys, this is the first time im trying my hand at android development, im still fairly new to development altogether.
Basically what I'm trying to do at the moment is read a list of folder-names in a particular directory, then write those to another file.
The file I'm writing to is at /data/data/com.rone/files/app_list
I'm trying to read from /data/data/
The app has been given su privileges as well. My issue is that I can't seem to read from any folder other than / (root)
Code:
private OnClickListener sort_listener = new OnClickListener() {
@Override
public void onClick(View v) {
String datafolders ="";
File dir = new File("/data/data/");
if(dir.isDirectory() && dir.canRead()){
Log.v("DEBUG", dir.getName() + " is the searching directory!");
for(int i = 0; i < dir.list().length; i++) {
datafolders += dir.list()[i] + " \n";
}
}
else {
Log.v("ERROR", "directory does not exist or can not be accessed!");
}
writeFile(datafolders, "app_list");
}
};
public void writeFile(String input, String filename) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(input.getBytes());
fos.close();
return;
} catch (FileNotFoundException e) {
Log.v("ERROR", e.getMessage());
} catch (IOException e) {
Log.v("ERROR", e.getMessage());
}
}
public String readFile(String filename) {
try {
FileInputStream fis = openFileInput(filename);
String temp = "";
int ch;
while ((ch = fis.read()) > -1) {
temp += (char) ch;
}
fis.close();
return temp;
} catch (FileNotFoundException e) {
Log.v("ERROR", e.getMessage());
return "Exception" + e;
} catch (IOException e) {
Log.v("ERROR", e.getMessage());
return "Exception" + e;
}
}
It only writes to the file when I use:
Code:
File dir = new File("./");
Also, my app is specifically written for the SGS and I'm using Eclipse. Any way to get and import a custom SGS skin with the Menu and Back button functionality?
No replies? No one knows how to read the directories? Is there a limitation built-in that stops from reading directories? Even with su permissions?

Android ICS SSL Authentication Help

Im trying to build an RSS feed reader that needs to do some client side SSL authentication.
Ive got, or at least think i have, the certificate and now cannot figure out how to setup a ssl tunnel to send the certificate to the server to authenticate.
here is what i have so far:
public class Authenticator extends Activity {
PrivateKey privateKey = null;
String SavedAlias = "";
private static final String TAG = "AUTHENTICATOR.CLASS";
final HttpParams httpParams = new BasicHttpParams();
private KeyStore mKeyStore = KeyStore.getInstance();
public Handler mHandler = new Handler(Looper.getMainLooper());
public void run()
{
mHandler.post(new Runnable() {
public void run() {
new AliasLoader().execute();
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCertificates("TEST");
}
public class AliasLoader extends AsyncTask<Void, Void, X509Certificate[]>
{
X509Certificate[] chain = null;
@Override protected X509Certificate[] doInBackground(Void... params) {
android.os.Debug.waitForDebugger();
if(!SavedAlias.isEmpty())
{
try {
chain = KeyChain.getCertificateChain(getApplicationContext(),SavedAlias);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
else
{
this.cancel(true);
}
return chain;
}
@Override
protected void onPostExecute(X509Certificate[] chain)
{
if(chain != null)
{
Toast.makeText(getApplicationContext(), "YAY, Certificate is not empty", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Certificate is Empty", Toast.LENGTH_LONG).show();
}
/*
if (privateKey != null) {
Signature signature = null;
try {
signature = Signature.getInstance("SHA1withRSA");
} catch (NoSuchAlgorithmException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
try {
signature.initSign(privateKey);
} catch (InvalidKeyException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
*/
}
}
public void getCertificates(String Host)
{
KeyChainAliasCallback callBack = new KeyChainAliasCallback() {
@Override
public void alias(String alias) {
if (alias != null)
{
Looper.prepare();
saveAlias(alias);
run();
Looper.loop();
}
}
};
KeyChain.choosePrivateKeyAlias(this, callBack,
new String[] {"RSA", "DSA"}, // List of acceptable key types. null for any
null, // issuer, null for any
null, // host name of server requesting the cert, null if unavailable
443, // port of server requesting the cert, -1 if unavailable
null); // alias to preselect, null if unavailable
}
public void saveAlias(String alias)
{
SavedAlias = alias;
}
}
Any help on how to do this would be greatly appreciated as i have never done any authentication before and i have found it difficult to find anything on this topic for android 4.0 as 4.0 seems to be different in implementation then the older versions.

Android mediarecorder error

Hi!
I have been developing android app which records sounds from the phones mic. Error happens when trying to excecute this method:
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public void startRecording(View view) {
System.out.println("Start recording");
final Button aloita = (Button) findViewById(R.id.button3);
final Button lopeta = (Button) findViewById(R.id.button2);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(tiedostonimi);
try {
recorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() kusi");
}
System.out.println(LOG_TAG);
recorder.start();
aloita.setEnabled(false);
lopeta.setEnabled(true);
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Error: Unfortunately myapp has stopped
LogCat: Could not excecute method of the activity and then some onClick errors
If I comment all the recorder.* from this method the app works fine. (I use also System.out.println as a debug tool)
I need help!
Update:
I changed the outputfiles variable and now I've got error: start called in an invalid state: 4.

[Q] Can I register a listener on process state?

I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
MidnightJava said:
I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
Click to expand...
Click to collapse
Afaik there's no way to accomplish that other than your way or being system/root app. See this similar question here for reference.
Can you show how you start the process?
EmptinessFiller said:
Can you show how you start the process?
Click to expand...
Click to collapse
Sure. Here's the class that manages starting, stopping, and statusing (running or not) the binary executable. In this case, it's the omniNames service of the omni ORB (CORBA broker).
Code:
public class RHManager {
private TimerTask task = new TimerTask() {
@Override
public void run() {
if (RHManager.this.listener != null) {
listener.running(isOmniNamesRunning());
}
}
};
private IStatusListener listener;
public RHManager() {
}
public void startOmniNames() {
final Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"start"};
final String[] env = new String[] {"LD_LIBRARY_PATH=/sdcard/data/com.axiosengineering.rhmanager/omniORB/lib"};
Thread t = new Thread() {
public void run() {
try {
int res = exec.doExec(args, env);
logMsg("omniNames start return code " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
}
String std = exec.getOutResult();
logMsg("omniNames start: std out==> " + std );
String err = exec.getErrResult();
logMsg("omniNames start: err out==> " + err );
};
};
t.start();
logMsg("omniNames started");
}
private boolean isOmniNamesRunning() {
String pid_s = getOmniNamesPid();
Integer pid = null;
if (pid_s != null) {
try {
pid = Integer.parseInt(pid_s);
} catch (NumberFormatException e) {
return false;
}
}
if (pid != null) {
RunningAppProcessInfo activityMgr = new ActivityManager.RunningAppProcessInfo("omniNames", pid, null);
return activityMgr.processName != null ;
}
return false;
}
public void stopOmniNames() {
String pid = getOmniNamesPid();
android.os.Process.killProcess(Integer.parseInt(pid));
android.os.Process.sendSignal(Integer.parseInt(pid), android.os.Process.SIGNAL_KILL);
}
private String getOmniNamesPid() {
Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"pid"};
String pid = "";
try {
int res = exec.doExec(args, null);
logMsg("oniNames pid return code: " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
return pid;
}
String std = exec.getOutResult();
logMsg("omniNames pid: std out ==> " + std);
String err = exec.getErrResult();
logMsg("omniNames pid: err out ==> " + err);
String[] parts = std.split("\\s+");
if (parts.length >= 2) {
pid = parts[1];
}
return pid;
}
//monitor omniNames status and report status periodically to an IStatusListener
public void startMonitorProcess(IStatusListener listener, String string) {
this.listener = listener;
Timer t = new Timer();
t.schedule(task, 0, 1000);
}
private void logMsg(String msg) {
if (RhMgrConstants.DEBUG) {
System.err.println(msg);
}
}
}
Here's the Exec class that handles invocation of Runtime#exec(), consumes std and err out, and reports those and process return status to the caller.
Code:
public class Exec {
private String outResult;
private String errResult;
private Process process;
private boolean failed = false;
StreamReader outReader;
StreamReader errReader;
public int doExec(String[] cmd, String[] envp) throws IOException{
Timer t = null;
try {
process = Runtime.getRuntime().exec(cmd, envp);
outReader = new StreamReader(process.getInputStream());
outReader.setPriority(10);
errReader = new StreamReader(process.getErrorStream());
outReader.start();
errReader.start();
t = new Timer();
t.schedule(task, 10000);
int status = process.waitFor();
outReader.join();
errReader.join();
StringWriter outWriter = outReader.getResult();
outResult = outWriter.toString();
outWriter.close();
StringWriter errWriter = errReader.getResult();
errResult = errWriter.toString();
errWriter.close();
return (failed ? -1: status);
} catch (InterruptedException e) {
return -1;
} finally {
if (t != null) {
t.cancel();
}
}
}
public int doExec(String[] cmd) throws IOException{
return doExec(cmd, null);
}
public String getOutResult(){
return outResult;
}
public String getErrResult(){
return errResult;
}
private static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter(30000);
}
public void run() {
try {
int c;
while ((c = is.read()) != -1){
sw.write(c);
}
}
catch (IOException e) { ; }
}
StringWriter getResult() {
try {
is.close();
} catch (IOException e) {
System.err.println("Unable to close input stream in StreamReader");
}
return sw;
}
}
private TimerTask task = new TimerTask() {
@Override
public void run() {
failed = true;
process.destroy();
}
};
}
Here's the script that startOminNames() invokes. It's the shell script installed with omniORB with functions other than start and get_pid removed, since those are handled by Android classes. You can invoke any executable in place of the script, or wrap your executable in a script.
Code:
#
# omniNames init file for starting up the OMNI Naming service
#
# chkconfig: - 20 80
# description: Starts and stops the OMNI Naming service
#
exec="/sdcard/data/com.axiosengineering.rhmanager/omniORB/bin/omniNames"
prog="omniNames"
logdir="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs"
logfile="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs/omninames-localhost.err.log"
options=" -start -always -logdir $logdir -errlog $logfile"
start() {
#[ -x $exec ] || exit 5
echo -n $"Starting $prog: "
$exec $options
}
get_pid() {
ps | grep omniNames
}
case "$1" in
start)
start && exit 0
$1
;;
pid)
get_pid
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?
And here's the IStatusListener interface
Code:
public interface IStatusListener {
public void running(boolean running);
}
Runtime.exec() has some pitfalls. See this helpful Runtime.exec tutorial for a nice explanation.
And you may also want to check out this post on loading native binaries in Android.

[Q] updating parse?

I'm new to parse. Having trouble with updating. I don't have a problem at all with saving and retrieving user data. Just updating users data.
In my error toast I added some code to tell me my objectId. According to that its the objectId for my User. Not profile_info like I believe I need.
The error I get is "no result for query".
Code:
update.setOnClickListener(new OnClickListener() {
public void onClick(View arg1) {
final String obId = ParseUser.getCurrentUser().getObjectId();
ParseQuery<ParseObject> query = ParseQuery.getQuery("profile_info");
query.getInBackground(obId, new GetCallback<ParseObject>() {
public void done(ParseObject profile_info, ParseException e) {
if (e == null) {
profile_info.put("first_name", fname.getText().toString());
profile_info.put("last_name", lname.getText().toString());
profile_info.put("height_in_feet", hf.getText().toString());
profile_info.put("height_in_inches", hi.getText().toString());
profile_info.put("weight", weight.getText().toString());
profile_info.put("waist", waist.getText().toString());
profile_info.put("wrist", wrist.getText().toString());
profile_info.put("hip", hip.getText().toString());
profile_info.put("forearm", forearm.getText().toString());
profile_info.saveInBackground();
Toast.makeText(getApplicationContext(),
"Your profile has been updated",
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage() + "\nthe objectId is " + obId,
Toast.LENGTH_SHORT)
.show();
}
}
});
}
})
[\CODE]
Sent from my Nexus 6 using XDA Free mobile app
I figured it out. Not sure if this is the right way to do it but it works.
Code:
ParseQuery<ParseObject> pQuery = new ParseQuery<ParseObject>("profile_info");
pQuery.whereEqualTo("first_name", fname.getText().toString());
pQuery.getFirstInBackground(new GetCallback<ParseObject>()
{ [user=439709]@override[/user]
public void done(ParseObject profile_info, ParseException e) {
if (e == null){
[\CODE]
I I also figured out that I can't change the text that's in the text field used in this: "pQuery.whereEqualTo"
Sent from my Nexus 6 using XDA Free mobile app

Categories

Resources