[Q] DEV get the outgoing call number: howto? - General Questions and Answers

I'm developing my first application.
I've done a service that get the phone calls and does something...
No problem for incoming calls, the telephonymanager with his phonestatelistener gives me the incoming number in the CALL_STATE_RINGING, but how to get the outgoing call number?
I'm getting mad!
thanks for any help.

rabarama said:
I'm developing my first application.
I've done a service that get the phone calls and does something...
No problem for incoming calls, the telephonymanager with his phonestatelistener gives me the incoming number in the CALL_STATE_RINGING, but how to get the outgoing call number?
I'm getting mad!
thanks for any help.
Click to expand...
Click to collapse
Stop getting mad! Dark3n comes to your rescue!
You are right phonestate listener doesn't give you the outgoing calls.
You will have to make a broadcast receiver for "android.intent.action.NEW_OUTGOING_CALL", the intent you get will have an extra "Intent.EXTRA_PHONE_NUMBER" and thats the outgoing call number.
btw you the permission "android.permission.PROCESS_OUTGOING_CALLS" to do this
May your first application be downloaded lots of times

Thanks a lot, but i'm not totally out of troubles...
How to get the broadcastReceiver inside my service?
I tried only inserting a inner class inside my service but it gives me error when i make a call...
i post some code...
Code:
package mypackage;
import ...
public class MyService extends Service {
String TELEPHONENUMBER="";
//here is the problem...
public class OutgoingCallReceiver extends BroadcastReceiver {
public void onReceive(Context context, final Intent intent) {
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
TELEPHONENUMBER = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
}
}
@Override
public void onCreate() {
super.onCreate();
try{
TelephonyManager telephonyManager=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);;
PhoneStateListener listener;
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//if the previous state was offhook tellme "i had a call with TELEPHONENUMBER"
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//if previous state wasn't ringin HERE I HAVE TO GET THE OUTGOING CALL NUMBER...
break;
case TelephonyManager.CALL_STATE_RINGING:
//get TELEPHONENUMBER fron incoming call and do something
TELEPHONENUMBER=incomingNumber;
break;
}
}
};
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}catch(Exception ie){}
}
how to simply register a litener for outgoingcalls as i did with phonestatelistener?

SOLVED
SOLVED!!
ok, i'm now dancing naked and drunk...
it was quite easy in effect...
I post some code for who will be in my situation...
If you have to get phone numbers from incoming and outgoing calls in a service this could be one way...
Code:
package mypackage;
import ...
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
br=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
TELEPHONENUMBER = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
} catch (Exception e) {
}
}
};
this.registerReceiver(br,new IntentFilter("android.intent.action.NEW_OUTGOING_CALL"));
try{
TelephonyManager telephonyManager=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener listener;
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//do what you want
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//do what you want
break;
case TelephonyManager.CALL_STATE_RINGING:
TELEPHONENUMBER=incomingNumber;
//do what you want
break;
}
};
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}catch(Exception ie){}
}

Awesome !
I recommend unregistering your receiver like this.
@Override
public void onDestroy() {
this.unregisterReceiver(br);
super.onDestroy();
}
Click to expand...
Click to collapse
In your service.

make call without intents
Hi all,
I have a specific problem hopefully someone can help me..
I would like to make an Android application to measure and diagnose
mobile networks. Hence I have to make calls and meanwhile check the
mobile network parameters.
I tried to use ACTION_DIAL intent but in this case I cannot get
parameters of calls (e.g. call setup time)because the intent hides it.
I debugged it and checked what happen in the sdk when setup a call but
I couldn't find out.
I look into the sdk's internal telephony package and try to find the
class which use the dial function, I found several classes and I gone
through them by the callhierarchy.
Finally I got to the CallManager class and I didn't find further class
which use this class' dial function.
Please help me to find a way to make a call without intents.
Someone of you have a good hint for me?
Another issue: Is it possible to simulate a speech to play a voice file (mp3, wav etc) during a call?
Could someone help me about this issue?
Thanks in advance!
speky

Tried to record call\s using the above code.. some probs..
Dark3n said:
Awesome !
I recommend unregistering your receiver like this.
In your service.
Click to expand...
Click to collapse
thanks.. Dark3n.. For your useful code... I used theese code to record incoming & outgoing calls.. It records the calls only one after the other...
..
If 1,2,3,4,5,6,7 are the calls i made.
Then 1(Call recorded,service killed),2(Service Started,Call not recorded),3(Call recorded,service killed),4(Service Started,Call not recorded),5(Call recorded,service killed),6(Service Started,Call not recorded),7(Call recorded,service killed)......
Why this happens....Any solutions to record all calls from service??
Thanks in advance..
HEre is my code..
package com.exampled.demoserv;
import java.io.File;
import java.io.IOException;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class ParentalService extends Service {
String TELEPHONENUMBER;
boolean recording=false;
final MediaRecorder recorder=new MediaRecorder();
@Override
public void onCreate() {
super.onCreate();
//NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Toast.makeText(getApplicationContext(), "Service created", Toast.LENGTH_SHORT).show();
BroadcastReceiver br=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
TELEPHONENUMBER = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
} catch (Exception e) {
}
}
};
this.registerReceiver(br,new IntentFilter("android.intent.action.NEW_OUTGOING_CALL"));
startMonitoring();
}
public void startMonitoring()
{
TelephonyManager mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(new TeleListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
class TeleListener extends PhoneStateListener
{
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state)
{
case TelephonyManager.CALL_STATE_IDLE:
Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Stop CaLLED "+recording+TELEPHONENUMBER, Toast.LENGTH_LONG).show();
stopRecording();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOKing"+TELEPHONENUMBER, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Start CaLLED "+recording+TELEPHONENUMBER, Toast.LENGTH_LONG).show();
startRecording();
break;
case TelephonyManager.CALL_STATE_RINGING:
TELEPHONENUMBER=incomingNumber;
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGINGini:"+TELEPHONENUMBER, Toast.LENGTH_SHORT).show();
break;
}
}
}
public void startRecording()
{
if(recording==false)
{
Toast.makeText(getApplicationContext(), "Recorder_Sarted"+TELEPHONENUMBER, Toast.LENGTH_LONG).show();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
String file= Environment.getExternalStorageDirectory().toString();
String filepath= file+"/11111111111111";
File dir= new File(filepath);
dir.mkdirs();
filepath+="/"+TELEPHONENUMBER+".3gp";
recorder.setOutputFile(filepath);
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.start();
recording=true;
}
}
public void stopRecording()
{
if(recording==true)
{
Toast.makeText(getApplicationContext(), "Recorder_Relesed from "+recording, Toast.LENGTH_LONG).show();
recorder.stop();
recorder.reset();
recorder.release();
recording=false;
}
}
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
}
Click to expand...
Click to collapse

Related

[Q] Tropo SMS Integration In Android Api

I'm building a complete build of Android with tropo: (Google tropo)
Here's my tropo hosted script in javascript:
Code:
if (typeof number == 'undefined') {//IF the call doesn't come from me (there's no variable set)
var callerId=currentCall.callerID;
var textmessage=currentCall.initialText
hangup()
call('(Put your phone number Here', {network: 'SMS'});
//Analyse message and format it for sending
var message = new Array();
var nbMessages=((textmessage.length())/149) ;//.length() ????? why????
var i=0;
for(i=0;i<nbMessages;i++){
message[i]=callerId+textmessage.substr(i*149,149);
say(message[i]);
wait(1000);
}
hangup()
}
else //SENDING PART:number and text are parameters
{
call(number, {network:"SMS"});
say(text);
}
I've used the CM9 source code for the galaxy s2 that I downloaded and builded following this guide: (Google teamhacksung CyanogenMod9 How to build)
For sending, I simply post an HTTP Post request to my tropo app
Here's the code
I modified the SMSManager.java class in android.telephony package
Code:
public void sendTextMessage(
String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent) {
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (TextUtils.isEmpty(text)) {
throw new IllegalArgumentException("Invalid message body");
}
/* OLD METHOD FOR SMS BY CARRIER
try {
ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null) {
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
} catch (RemoteException ex) {
// ignore it
}*/
//My new Method via tropo
//Création de l'objet Tropo SMS
TropoSms sms = new TropoSms(destinationAddress, text, sentIntent,deliveryIntent);
sms.send();
}
/**/
public void sendMultipartTextMessage(
String destinationAddress, String scAddress, ArrayList<String> parts,
ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) {
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (parts == null || parts.size() < 1) {
throw new IllegalArgumentException("Invalid message body");
}
if (parts.size() > 1) {
/*//OLD METHOD FOR SMS CARRIER
try {
ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null) {
iccISms.sendMultipartText(destinationAddress, scAddress, parts,
sentIntents, deliveryIntents);
}
} catch (RemoteException ex) {
// ignore it
}*/
//My tropo Method
for(int i=0; i< parts.size();i++){
TropoSms sms = new TropoSms(destinationAddress, parts.get(i), sentIntents.get(i),deliveryIntents.get(i));
sms.send();
}
} else {
PendingIntent sentIntent = null;
PendingIntent deliveryIntent = null;
if (sentIntents != null && sentIntents.size() > 0) {
sentIntent = sentIntents.get(0);
}
if (deliveryIntents != null && deliveryIntents.size() > 0) {
deliveryIntent = deliveryIntents.get(0);
}
sendTextMessage(destinationAddress, scAddress, parts.get(0),
sentIntent, deliveryIntent);
}
}
Here I created the Tropo SMS class in the android.telephony.tropo package
Code:
/**
*
*/
package android.telephony.tropo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.telephony.SmsManager;
/**
* @author kevmegforest
*
*/
public class TropoSms {
protected String destinationAddress="Undefined";
protected String message="Undefined";
protected PendingIntent sentIntent;
protected PendingIntent deliveryIntent;
private static String token="1...4c";
public TropoSms(){
}
public TropoSms(String sendAddress, String text, PendingIntent sendIntent, PendingIntent deliverIntent){
destinationAddress=sendAddress;
message=text;
sentIntent=sendIntent;
deliveryIntent=deliverIntent;
}
/**------------------------------------------
* SETTERS AND GETTERS
* @return
*/
public String getDestinationAddress() {
return destinationAddress;
}
public String getMessage() {
return message;
}
//--------------------------------------------------
/**
* Methods
*/
public void send(){ //Success return true //Fail return false
boolean success=true;
this.message=manageText();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
HttpPost post = new HttpPost("https://api.tropo.com/1.0/sessions");
//Creating JSON object
JSONObject json= new JSONObject();
try {
json.put("token", token);
json.put("number", this.destinationAddress );
json.put("text", this.message);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
}
try {
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
//Post headers Setup
post.addHeader("accept", "application/json");
post.addHeader("content-type","application/json");
response=client.execute(post);
//Checking response
//HOW TO
if(response.getStatusLine().getStatusCode() !=200)
success=false;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success =false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
}
this.manageIntent(success);
client.getConnectionManager().shutdown();//Ending connection
}
private void manageIntent(boolean sendsuccess)
{
if(sendsuccess)
{
try {
this.sentIntent.send(Activity.RESULT_OK);
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
this.sentIntent.send(SmsManager.RESULT_ERROR_GENERIC_FAILURE);
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String manageText()
{
String correctedText=this.message;//The last character in each table is the one to replace with
char characterToReplaceA[]={'à','â','ä','a'};
char characterToReplaceC[]={'ç','c'};
char characterToReplaceE[]={'é','è','ê','ë','e'};
char characterToReplaceI[]={'ì','î','ï','i'};
char characterToReplaceO[]={'ò','ô','ö','o'};
char characterToReplaceU[]={'ù','û','ü','u'};
char characterToReplace[][]={characterToReplaceA,characterToReplaceC,characterToReplaceE,characterToReplaceI,characterToReplaceO,characterToReplaceU};
for(int i=0;i<characterToReplace.length;i++){
for(int j=0;j<(characterToReplace[i].length-1);j++){
correctedText=correctedText.replace(characterToReplace[i][j],characterToReplace[i][characterToReplace[i].length-1]);
correctedText=correctedText.replace(Character.toUpperCase(characterToReplace[i][j]),Character.toUpperCase(characterToReplace[i][characterToReplace[i].length-1]));
}
}
return correctedText;
}
}
The sending part works really well. Since it's an API change I can use any SMS App in android and it would work.
But I have a problem with receiving.
My tropo script can only modify the body message of the sms. So when someone send a SMS message to tropo, I prefixed the body message with 10 characters representing it's phone number like this:
original message: "Hello"
new message:"15551231234Hello"
I then send this message to my phone
The modified class SubmitPdu in android.telephony package in the SMSMessage.java file
It's wherethe SMS app get the sms with the createfrompdu() method
Code:
public static SmsMessage createFromPdu(byte[] pdu, String format) {
SmsMessageBase wrappedMessage;
if (FORMAT_3GPP2.equals(format)) {
wrappedMessage = com.android.internal.telephony.cdma.SmsMessage.createFromPdu(pdu);
} else if (FORMAT_3GPP.equals(format)) {
wrappedMessage = com.android.internal.telephony.gsm.SmsMessage.createFromPdu(pdu);
} else {
Log.e(LOG_TAG, "createFromPdu(): unsupported message format " + format);
return null;
}
//Verify here if it comes from TROPO
Log.d("SMSNumberCompare", "Original number:"+wrappedMessage.getOriginatingAddress());
Log.d("SMSNumberCompare", "Tropo number:"+TropoSmsReceiver.TROPO_APP_PHONE_NUMBER);
if(PhoneNumberUtils.compare(wrappedMessage.getOriginatingAddress(), TropoSmsReceiver.TROPO_APP_PHONE_NUMBER)){
Log.d("SMSNumberCompare", "Comparison:"+(PhoneNumberUtils.compare(wrappedMessage.getOriginatingAddress(), TropoSmsReceiver.TROPO_APP_PHONE_NUMBER)));
//Creating TropoReceive Object
TropoSmsReceiver tropo = (TropoSmsReceiver) wrappedMessage; //Downcasting
tropo.formatFromTropo();
//upcasting
wrappedMessage=tropo;
}
return new SmsMessage(wrappedMessage);
}
And here's my TropoSmsReceiver Class which extends the SmsMessageBase class
Code:
package com.android.internal.telephony.tropo;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage.MessageClass;
import android.util.Log;
import com.android.internal.telephony.SmsMessageBase;
public class TropoSmsReceiver extends SmsMessageBase {
public final static String TROPO_APP_PHONE_NUMBER="###########";
//My new Methods
//this method will format the text to get the parameters transferred from the tropo text
public void formatFromTropo(){
Log.d("TropoFormat", "old address"+this.originatingAddress.address);
this.originatingAddress.address=PhoneNumberUtils.formatNumber(this.messageBody.substring(0, 10), PhoneNumberUtils.FORMAT_NANP );
Log.d("TropoFormat", "new address"+this.originatingAddress.address);
this.messageBody=this.messageBody.substring(11);
Log.d("TropoFormat", "new Body"+this.messageBody);
}
@Override
public MessageClass getMessageClass() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getProtocolIdentifier() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isReplace() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isCphsMwiMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMWIClearMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMWISetMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMwiDontStore() {
// TODO Auto-generated method stub
return false;
}
@Override
public int getStatus() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isStatusReportMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isReplyPathPresent() {
// TODO Auto-generated method stub
return false;
}
}
The interesting part is my new method formatFromTropo()
But I have a problem, it doesn't work.
It builds sucessfully
In the logcat, the debug log says it goes in the if statement (it says Comparison: true and it's placement is in the if)
But when the tropo.formatFromTropo() is called the catlog has no mention of any log declared in the TropoSmsReceiver File. How is that possible? Can you help me?
It's my first android project (app or android Source change) and java project so you can give me many recommendations(and comments) too.
Thank you

[Q] Sending "string" serially (byte code given)

Hi all,
I am developing an android app for my project which sends data serially, through RS232 + OTG cable, to a circuit developed by me (and the PC code for which is already done and developed in C#). I'm new to android and tried to get help from example apps. i found an app which establishes the serial communication successfully but the problem is that it sends data in the form of byte, but i want data to be sent as a string and also received as a string. portion of the activity of interest is being added which sends binary 10101010... but I want data in string format. like "abcdefg". it must also be noted that this code is ignoring the incoming data but i want the incoming data to be stored in a variable (which i think is not very difficult but it could be handy if someone can also guide about that)
if someone can help, it'll be highly appreciated
Code:
package android_serialport_api.sample;
import java.io.IOException;
import java.util.Arrays;
import android.os.Bundle;
import java.io.*;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
public class Sending01010101Activity extends SerialPortActivity {
SendingThread mSendingThread;
byte[] mBuffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending01010101);
mBuffer = new byte[1024];
Arrays.fill(mBuffer, (byte) 0x55);
if (mSerialPort != null) {
mSendingThread = new SendingThread();
mSendingThread.start();
}
}
@Override
protected void onDataReceived(byte[] buffer, int size) {
// ignore incoming data
}
private class SendingThread extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
try {
if (mOutputStream != null) {
mOutputStream.write(mBuffer);
} else {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
}
not enough info is availabe on the internet on this topic and I only expect help from this forum. its very important for me

[Q] How can I create a white list of Apps?

Hi, I am developping a home screen app, and I want only certain apps to be able tu be launched from my home screen.
I want to do it exactly like Surelock:
When the user tries to open an app that doesn't belong to my list of accepted apps, he should receive a toast saying something like example: "com.android.settings blocked by this app".
I need that type of security, I came across a piece of code on the web, but it does not work...
Could you help me out either by suggesting something new or by helping me understand and fix this one?
public class MonitorService extends Service {
private Handler handler;
Runnable runnable;
@override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler = new Handler();
runnable = new Runnable() {
@override
public void run() {
new Thread(new Runnable() {
@override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am
.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
String currentActivityName=componentInfo.getClassName();
String packageName=componentInfo.getPackageName();
if(whitelist.contains(currentActivityName)){
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName(blockActivityPackageName,
blockActivityName));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
}
}
}).start();
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
@override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, MonitorService.class);
startService(intent);
}
@override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}}

[Q] [Help] Activity flow

Hello, I am trying to create a simple REST client in android, i have created the client that makes the connections and the service intent. I can call it from the main activity but i have a problem getting the result from the service intent to the activity. How can i achive this? I am kind of confused on how to handle this...
Code:
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_AUTH.equals(action)) {
final String username = intent.getStringExtra(EXTRA_PARAM_USERNAME);
final String password = intent.getStringExtra(EXTRA_PARAM_PASSWORD);
boolean authenticated = handleActionAuth(username, password);
Log.d(TAG, "Result: "+authenticated);
/*** What can i call here to notify the activity??? ***/
} else if (ACTION_BAZ.equals(action)) {
}
}
}
Thanks

[SOLVED] App to enable Wifi after sleep (for cheap eBook reader)

So this is one problem one shouldn't have, if manufacturers would make sensible decisions - but oh well...
I bought an cheap eBook reader (InkBook Calypso Plus) that unfortunately comes with a very reduced Android 8.1 user interface but otherwise with an pretty open system. But when the devices goes to sleep it disables wifi (which is fine for me) and you've to re-enable it manually every time (which is not fine for me). There is no option to change that behavior in the default interface.
So I'm looking for ideas to fix this: Either by an app that just regularly checks if wifi is off and turns it back on when the device wakes up or by any other way to turn this "feature" off (maybe there is a way to access the original android settings and change it there?).
- The devices runs Android 8.1 with a custom user interface from the manufacturer
- I can sideload *.apks
- It doesn't have Google Play Store/Services
- It's not rooted and I don't know if this is possible
AllesMeins said:
So this is one problem one shouldn't have, if manufacturers would make sensible decisions - but oh well...
I bought an cheap eBook reader (InkBook Calypso Plus) that unfortunately comes with a very reduced Android 8.1 user interface but otherwise with an pretty open system. But when the devices goes to sleep it disables wifi (which is fine for me) and you've to re-enable it manually every time (which is not fine for me). There is no option to change that behavior in the default interface.
So I'm looking for ideas to fix this: Either by an app that just regularly checks if wifi is off and turns it back on when the device wakes up or by any other way to turn this "feature" off (maybe there is a way to access the original android settings and change it there?).
- The devices runs Android 8.1 with a custom user interface from the manufacturer
- I can sideload *.apks
- It doesn't have Google Play Store/Services
- It's not rooted and I don't know if this is possible
Click to expand...
Click to collapse
You need root because the activity that you are trying to manage is regulated by "wakelocks" which can be managed with apps from the PlayStore that require root in order to modify your wakelocks.
There also may be a way to use adb to change the behaviour of the wakelock causing your undesired behaviour. I haven't looked to see if there is a way to do this with adb, it may or may not require root, I'm not certain.
Or, your issue is caused by "deep-sleep" or "doze", if so, you need to find a way to remove or disable deep-sleep or doze.
Or, it may be caused by some kind of battery or power management setting on your device, try disabling any battery or power management settings.
So to just give you a "kind of solution" if somebody stumbles upon this. I solved this by (very crudely) copying together my own app that's always active and waits for "screen on" to re-enable wifi. That can be done without root on my device
MainActivity.java
Java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btnStartService, btnStopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnStartService = findViewById(R.id.buttonStartService);
btnStopService = findViewById(R.id.buttonStopService);
btnStartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService();
}
});
btnStopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService();
}
});
}
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Monitoring WifiStatus");
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
startService(onOffIntend);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
stopService(onOffIntend);
}
}
OnOffReciever.java:
Java:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
public class OnOffReceiver extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is switched off
Log.w("WifiWakeUp","Screen Off");
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is turned on and screen lock deactivated
Log.w("WifiWakeUp","Screen On");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
}, new IntentFilter(Intent.ACTION_USER_PRESENT));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Foregroundservice.java
Java:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("WifiWakeUp")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_wifi_24)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AllesMeins said:
So to just give you a "kind of solution" if somebody stumbles upon this. I solved this by (very crudely) copying together my own app that's always active and waits for "screen on" to re-enable wifi. That can be done without root on my device
MainActivity.java
Java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btnStartService, btnStopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnStartService = findViewById(R.id.buttonStartService);
btnStopService = findViewById(R.id.buttonStopService);
btnStartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService();
}
});
btnStopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService();
}
});
}
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Monitoring WifiStatus");
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
startService(onOffIntend);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
stopService(onOffIntend);
}
}
OnOffReciever.java:
Java:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
public class OnOffReceiver extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is switched off
Log.w("WifiWakeUp","Screen Off");
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is turned on and screen lock deactivated
Log.w("WifiWakeUp","Screen On");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
}, new IntentFilter(Intent.ACTION_USER_PRESENT));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Foregroundservice.java
Java:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("WifiWakeUp")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_wifi_24)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
Click to expand...
Click to collapse
I'm wondering how long this took you and how much of a headache it was.
Actually much less than I feared. Took me maybe a few hours because it's basically just two answers from StackExchange copied together.

Categories

Resources