I can't get a string from one process to another one.
I already use an Intent for this problem, but my problem is that the class where I want to get that string extends PhoneCallListener instead of Activity.
For better understanding of my problem, here is the code:
// this is the class from where i want to send a string
package net.cellobject.blockingincomingcall;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SecondTab extends Activity
{
EditText e1;
Button b1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
e1=(EditText)findViewById(R.id.edt1);
b1=(Button)findViewById(R.id.b1);
LoadPreferences();
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String msg=e1.getText().toString();
SavePreferences("msg1",msg);
LoadPreferences();
if(msg=="")
{
Toast.makeText(getApplicationContext(), "First Enter the message then save it",Toast.LENGTH_LONG).show();
e1.requestFocus();
}
}
});
}
private void LoadPreferences()
{
SharedPreferences shp= getPreferences(MODE_PRIVATE);
String s1=shp.getString("msg1","");
e1.setText(s1);
}
private void SavePreferences(String key, String msg)
{
SharedPreferences shp= getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor=shp.edit();
editor.putString(key, msg);
editor.commit();
}
}
// this is the class where i want to get the string
package net.cellobject.blockingincomingcall;
import java.lang.reflect.Method;
import android.content.Context;
import android.media.AudioManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
public class PhoneCallStateListener extends PhoneStateListener
{
private Context context;
public PhoneCallStateListener(Context context)
{
this.context = context;
}
public void onCallStateChanged(int state, String incomingNumber)
{
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
AudioManager audioManager=(AudioManager)context. getSystemService (Context.AUDIO_SERVICE);
//Turn ON the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, true);
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService (Context.TELEPHONY_SERVICE);
try {
#SuppressWarnings("rawtypes")
Class clazz = Class.forName (telephonyManager.getClass() .getName());
Method method = clazz. getDeclaredMethod ("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(telephonyManager);
//Checking incoming call number
String incomming=incomingNumber.toString();
if (incomingNumber.equalsIgnoreCase(incomming))
{
Log.v("incomming_call",incomming);
telephonyService.endCall();
sendSMS(incomming, "I am Busy!!call me latter");
}
} catch (Exception e) {
e.printStackTrace();
}
audioManager.setStreamMute(AudioManager.STREAM_RING, false);
break;
}
super.onCallStateChanged(state, incomingNumber);
}
private void sendSMS(String incomming, String string)
{
android.telephony.SmsManager sms=android.telephony.SmsManager.getDefault();
sms.sendTextMessage(incomming, null, string, null, null);
}
}
how to get data from activity class to the PhoneStateListener class?
See above link And please don't repeat same question again and again..
Thanks
Related
I am facing this problem for the last two weeks. Can you help me why this problem occurs?
Error occur at this line allClient.callPhoneNumber("+16315192247");
Please check it. Every time it crashes.
package com.eureka.voicecallinapk;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import com.sinch.android.rtc.calling.CallListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String APP_KEY = "b7258284-f0dnd-4734-afec-210d387d****";
//i do it for security because i am posting here
public static final String APP_SECRET = "k76tOLgz+kSdKL7ULYsH**==";
public static final String ENVIRONMENT = "clientapi.sinch.com";
public Call call;
private TextView callState;
public SinchClient sinchClient;
private Button button;
private String callerId;
private String recipientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
callerId = intent.getStringExtra("callerId");
recipientId = intent.getStringExtra("recipientId");
sinchClient = Sinch.getSinchClientBuilder()
.context(MainActivity.this)
.userId("172976")
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
// sinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
button = findViewById(R.id.button);
callState = findViewById(R.id.callState);
button.setOnClickListener(view -> {
if (call == null) {
try {
boolean s=isStarted();
Log.d("checksinch", String.valueOf(s));
CallClient callClient = sinchClient.getCallClient();
callClient.callPhoneNumber("+16315192247"); // Error occur at this line "SinchClient not started"
//callClient.callPhoneNumber("+16315192247");
// call = sinchClient.getCallClient().callPhoneNumber("+46000000000.");
// call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}catch (Exception e){
Log.d("checksinch", e.getMessage());
}
} else {
call.hangup();
button.setText("Call");
}
});
}
private boolean isStarted() {
return (sinchClient != null && sinchClient.isStarted());
}
private class SinchCallListener implements CallListener {
#Override
public void onCallEnded(Call endedCall) {
call = null;
SinchError a = endedCall.getDetails().getError();
button.setText("Call");
callState.setText("");
setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
}
#Override
public void onCallEstablished(Call establishedCall) {
callState.setText("connected");
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
#Override
public void onCallProgressing(Call progressingCall) {
callState.setText("ringing");
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call incomingCall) {
call = incomingCall;
Toast.makeText(MainActivity.this, "incoming call", Toast.LENGTH_SHORT).show();
call.answer();
call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}
}
}
I'm trying to pass the values from the MainActivity class into SMSReceiver class using SharedPreferences but the values that returned isn't true
i used this and this but it seems it doesn't work
Edit : i'm using a service in my program so i can't call the members like MainActivity.MyPREFENRECES, SMSreceiver.rK because after i kill the activity i get null exception
Edit I'm calling the method run in the layout
any help please ??
MainActivity.java
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final String MyPREFERENCES = "MyPrefs" ;
public static Switch smsSwitch;
private EditText ringKey,vibrateKey,silentKey;
private AudioManager myAudioManager;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsSwitch = (Switch)findViewById(R.id.smsSwitch);
ringKey = (EditText)findViewById(R.id.ringWord);
vibrateKey = (EditText)findViewById(R.id.vibrateWord);
silentKey = (EditText)findViewById(R.id.silentWord);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
smsSwitch.setChecked(true);
if (sharedpreferences.contains(SMSreceiver.rK))
{
ringKey.setText(sharedpreferences.getString(SMSreceiver.rK, ""));
}
if (sharedpreferences.contains(SMSreceiver.sK))
{
silentKey.setText(sharedpreferences.getString(SMSreceiver.sK, ""));
}
if (sharedpreferences.contains(SMSreceiver.vK))
{
vibrateKey.setText(sharedpreferences.getString(SMSreceiver.vK, ""));
}
smsSwitch.setChecked(sharedpreferences.getBoolean("checked",false));
}
public void vibrate(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
public void ring(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
public void silent(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
public void mode(View view){
int mod = myAudioManager.getRingerMode();
if(mod == AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(getApplicationContext(), "Normal Mode", Toast.LENGTH_SHORT).show();
}
else if(mod == AudioManager.RINGER_MODE_SILENT){
Toast.makeText(getApplicationContext(), "Silent Mode", Toast.LENGTH_SHORT).show();
}
else if(mod == AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(getApplicationContext(), "Vibrate Mode", Toast.LENGTH_SHORT).show();
}
else{
}
}
public void run(View view){
String r = ringKey.getText().toString();
String v = vibrateKey.getText().toString();
String s = silentKey.getText().toString();
boolean c = smsSwitch.isChecked();
Editor editor = sharedpreferences.edit();
editor.putString("ring", r);
editor.putString("vibrate", v);
editor.putString("silent", s);
editor.putBoolean("checked",c);
editor.commit();
}
}
SMSreceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSreceiver extends BroadcastReceiver
{
private final String TAG = this.getClass().getSimpleName();
public static final String SMS_BUNDLE = "pdus";
public static SharedPreferences sharedpreference;
public static String rK="ring";
public static String vK="vibrate";
public static String sK="silent";
#Override
public void onReceive(Context context, Intent intent)
{
Intent startServiceIntent = new Intent(context, MainActivity.class);
context.startService(startServiceIntent);
sharedpreference = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if(sharedpreference.getBoolean("checked",true)) {
if (smsBody.contains(sharedpreference.getString(rK,"ring"))) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(context, "Normal Mode Activated", Toast.LENGTH_SHORT).show();
} else if (smsBody.contains(sharedpreference.getString(vK,"vibrate"))) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(context, "Vibrate Mode Activated", Toast.LENGTH_SHORT).show();
} else if (smsBody.contains(sharedpreference.getString(sK,"silent"))) {
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(context, "Silent Mode Activated", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
In my example, i am entering mobile no., message content in one activity. Before leaving that activity i am saving that info in "Shared Preference". In other activity i am trying to get those mob no,message,i am able to get no but unable to getting that message(second value).please help me to solve the issue.
DefaultDetails.java
package com.example.nirbhaya;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DefaultDetails extends Activity implements OnClickListener{
Button save,reset;
EditText dMob,dMsg,dEmail;
String defMobNo,defMsg,defEmail;
SharedPreferences DefaultData;
private static final String TAG = "DD-Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.defaultdetails);
initializing();
}
private void initializing() {
// TODO Auto-generated method stub
save = (Button)findViewById(R.id.bsave1);
reset = (Button)findViewById(R.id.bReset);
dMob = (EditText)findViewById(R.id.etDefMobNo);
dMsg = (EditText)findViewById(R.id.etDefMsg);
dEmail = (EditText)findViewById(R.id.etDefEmail);
save.setOnClickListener(this);
reset.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.bsave1:
defMobNo = dMob.getText().toString();
defMsg = dMsg.getText().toString();
defEmail = dEmail.getText().toString();
Log.i(TAG,"DONE");
DefaultData = getSharedPreferences("defMobileNo",0);
SharedPreferences.Editor store = DefaultData.edit();
store.putString("defMobileNo", defMobNo);
store.putString("defMessgae", defMsg);
store.putString("defEMail", defEmail);
store.commit();
Intent openStartingPoint = new Intent (getApplicationContext(), CurrentDetails.class);
startActivity(openStartingPoint);
break;
case R.id.bReset:
((EditText) findViewById(R.id.etDefMobNo)).setText("");
((EditText) findViewById(R.id.etDefEmail)).setText("");
((EditText) findViewById(R.id.etDefMsg)).setText("");
break;
}
}
}
DefSMS.java
package com.example.nirbhaya;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DefSms extends Activity{
Button buttonSend;
String defNo,defMsg;
SharedPreferences DefaultData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.defsms);
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
DefaultData = getSharedPreferences("defMessgae",0);
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(defNo, null, defMsg, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
Here def no getting message as Couldn't load data
please help me
Replace with this:
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
This is how basically sharedpreference work
To Store the values
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","myNameisnothing");
editor.commit();
To get the values
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String name = prfs.getString("Name", "");
This way it'd return the value of the name as myNameisnothing.
PS.Correct me if im wrong.
You are wrongly using
DefaultData = getSharedPreferences("defMessgae",0); in DefSMS.java
Please remove this and it will work fine.
You were trying to get shared preference named defMessgae which doesnot even exist. So when you try to access it, android will create a new preference with default value. That is why you were getting "Couldn't load data"
I have a problem in which I can't get data from activity class to the PhoneStateListener class.
for better understanding the code is as below:
This is the class from where I want to send the data or string
package net.cellobject.blockingincomingcall;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SecondTab extends Activity
{
EditText e1;
Button b1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
e1=(EditText)findViewById(R.id.edt1);
b1=(Button)findViewById(R.id.b1);
LoadPreferences();
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String msg=e1.getText().toString();
SavePreferences("msg1",msg);
LoadPreferences();
if(msg=="")
{
Toast.makeText(getApplicationContext(), "First
Enter the message then save it"
,Toast.LENGTH_LONG).show();
e1.requestFocus();
}
}
});
}
private void LoadPreferences()
{
SharedPreferences shp= getPreferences(MODE_PRIVATE);
String s1=shp.getString("msg1","");
e1.setText(s1);
}
private void SavePreferences(String key, String msg)
{
SharedPreferences shp= getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor=shp.edit();
editor.putString(key, msg);
editor.commit();
}
}
This is the class where I want to get the data or string which is extends with PhoneStateListener?
package net.cellobject.blockingincomingcall;
import java.lang.reflect.Method;
import android.content.Context;
import android.media.AudioManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
public class PhoneCallStateListener extends PhoneStateListener
{
private Context context;
public PhoneCallStateListener(Context context)
{
this.context = context;
}
public void onCallStateChanged(int state, String incomingNumber)
{
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
AudioManager audioManager = (AudioManager) context.
getSystemService(Context.AUDIO_SERVICE);
//Turn ON the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, true);
TelephonyManager telephonyManager = (TelephonyManager) context.
getSystemService(Context.TELEPHONY_SERVICE);
try {
#SuppressWarnings("rawtypes")
Class clazz = Class.forName(telephonyManager.getClass().getName());
Method method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(telephonyManager);
//Checking incoming call number
String incoming=incomingNumber.toString();
if (incomingNumber.equalsIgnoreCase(incoming))
{
Log.v("incoming_call",incoming);
telephonyService.endCall();
sendSMS(incoming, "I am Busy!!call me later");
}
} catch (Exception e) {
e.printStackTrace();
}
audioManager.setStreamMute(AudioManager.STREAM_RING, false);
break;
}
super.onCallStateChanged(state, incomingNumber);
}
private void sendSMS(String incoming, String string)
{
android.telephony.SmsManager sms=android.telephony.SmsManager.getDefault();
sms.sendTextMessage(incoming, null, string, null, null);
}
}
Since you have Context in both Activity and Receiver you may use SharedPreference to set and get data on both places.. WHats the problem..
context.getSharedPreference("name" , MODE_PRIVATE);
im posting a very simple method to store and get preferences, use this i will solve your problem related to store and retrieve preferences.
public class Preferences {
public static void record(String key,Context context,String value)
{
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences .Editor editor=pref.edit();
editor.putString(key,value );
editor.commit();
}
public static String getRecord(String key,Context context)
{
return PreferenceManager.getDefaultSharedPreferences(context).getString(key,PREF_DEFAULT_VALUE);
}
}
Here is my code:
package com.callplus;
import java.io.IOException;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class AudioRecordTest extends Service {
private static String TAG = "AudioRecordTest";
private static String FileName = null;
private MediaRecorder Recorder = null;
public static String callerName, date, path,number;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "I am in Oncreate");
DBAdapter db = new DBAdapter(this);
db.open(SQLiteDatabase.NO_LOCALIZED_COLLATORS);
db.getPath();
path = db.audioPath;
db.close();
final TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
public void onCallStateChanged(final int state,
final String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (Recorder != null) {
Recorder.release();
Recorder.stop();
}
Log.d("TestActivity", "Call is idle.");
actionStop(getApplicationContext());
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("TestActivity", "Call connected");
startRecording();
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
default:
break;
}
} finally {
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
stopSelf();
}
public static void actionStop(Context ctx)
{
Intent i = new Intent(ctx, AudioRecordTest.class);
Log.d(TAG, "I am in ActionStop");
// i.setAction(ACTION_STOP);
ctx.startService(i);
}
}
I want to stop the service when call idle.
hi in actionStop method instead of stopService method call you have called startService method again.
ctx.stopService(i);
Use the above line instead of that and tel the response