Access SharedPreferences from another class (non-activity) - android

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();
}
}
}
}
}
}

Related

"SinchClient not started" The main problem in android studio

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");
}
}
}

Creating a sms reader app to read the incoming messages via text to speech and run in background but it does meet the requirements

**MainActivity.java**
package com.cetpainfotech.newandroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsMessage;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggle = (ToggleButton)findViewById(R.id.speechToggle);
smsText = (TextView)findViewById(R.id.sms_text);
smsSender = (TextView)findViewById(R.id.sms_sender);
toggleListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if(isChecked){
speaker.allow(true);
speaker.speak(getString(R.string.start_speaking));
}else{
speaker.speak(getString(R.string.stop_speaking));
speaker.allow(false);
}
}
};
toggle.setOnCheckedChangeListener(toggleListener);
checkTTS();
initializeSMSReceiver();
registerSMSReceiver();
}
private void checkTTS(){
Intent check = new Intent();
check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(check, CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CHECK_CODE){
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
speaker = new Speaker(this);
}else {
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
private void registerSMSReceiver() {
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
private String getContactName(String phone){
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor.moveToFirst()){
return cursor.getString(0);
}else {
return "unknown number";
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
speaker.destroy();
}
}
**Speaker.java** //Helper class
This class is used to avoid calling the TTS API directly from the Activity.
This class implements the OnInitListener interface so that it knows when the TTS engine is ready.
package com.cetpainfotech.newandroid;
import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import java.util.HashMap;
import java.util.Locale;
public class Speaker implements OnInitListener {
private TextToSpeech tts;
private boolean ready = false;
private boolean allowed = false;
public Speaker(Context context){
tts = new TextToSpeech(context, this);
}
public boolean isAllowed(){
return allowed;
}
public void allow(boolean allowed){
this.allowed = allowed;
}
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
// Change this to match your
// locale
tts.setLanguage(Locale.US);
ready = true;
}else{
ready = false;
}
}
public void speak(String text){
// Speak only if the TTS is ready
// and the user has allowed speech
if(ready && allowed) {
HashMap<String, String> hash = new HashMap<>();
hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_NOTIFICATION));
tts.speak(text, TextToSpeech.QUEUE_ADD, hash);
}
}
public void pause(int duration){
tts.playSilence(duration, TextToSpeech.QUEUE_ADD, null);
}
// Free up resources
public void destroy(){
tts.shutdown();
}
}

Using shared preferences in Activity recognition app

I want to save the details of activities of user even if he closed the app by pressing back button or changed the orientation.I used shared prefences but i don't know how it works.i saw in different programmings using sharepreferences to save data.But i can't do it.Is there any changes i have to do.
Here is my code:
package tmt.niranjan.travellingtrack;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.ActivityRecognitionClient;
public class MainActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener {
private ActivityRecognitionClient arclient;
private PendingIntent pIntent;
private BroadcastReceiver receiver;
private TextView tvActivity;
public static final String SHARED_PREFERENCES =
"tmt.niranjan.travellingtrack.SHARED_PREFERENCES";
public static final String KEY_LOG_FILE_NUMBER =
"tmt.niranjan.travellingtrack.KEY_LOG_FILE_NUMBER";
public static final String KEY_LOG_FILE_NAME =
"tmt.niranjan.travellingtrack.KEY_LOG_FILE_NAME";
public static final String KEY_LOG_FILE_NAME1 =
"tmt.niranjan.travellingtrack.KEY_LOG_FILE_NAME";
public static final String KEY_PREVIOUS_ACTIVITY_TYPE =
"tmt.niranjan.travellingtrack.KEY_PREVIOUS_ACTIVITY_TYPE";
private SharedPreferences mpref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvActivity = (TextView) findViewById(R.id.Actrec);
mpref = getApplicationContext().getSharedPreferences(
SHARED_PREFERENCES, Context.MODE_PRIVATE);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
arclient = new ActivityRecognitionClient(this, this, this);
arclient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Editor editor = mpref.edit();
String v = "Type:"+intent.getExtras().getInt("Type")+" "+"Activity :" + intent.getStringExtra("Activity") + " " + "Confidence : " + intent.getExtras().getInt("Confidence") + "\n";
editor.putInt(KEY_PREVIOUS_ACTIVITY_TYPE,intent.getExtras().getInt("Type"));
editor.putString(KEY_LOG_FILE_NAME, "Activity");
editor.putInt(KEY_LOG_FILE_NUMBER, intent.getExtras().getInt("Confidence"));
editor.putString(KEY_LOG_FILE_NAME1,v);
tvActivity.setText(v);
editor.commit();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("tmt.niranjan.myactivityrecognition.ACTIVITY_RECOGNITION_DATA");
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(arclient!=null){
arclient.removeActivityUpdates(pIntent);
arclient.disconnect();
}
Toast.makeText(this, "ondestroycalled", Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnected(Bundle arg0) {
Intent intent = new Intent(this, ActivityRecognitionService.class);
pIntent = PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
arclient.requestActivityUpdates(1000, pIntent);
}
#Override
public void onDisconnected() {
}
}
You are missing editor.apply(); before editor.commit();
Give it a go and see if it works
Here is code that I use and works fine, so if it is not editor.apply then it would suggest that nothing is being set from your intents.getextra, have you debugged to see if these contain a value?
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key_pref_branch_code", mainObject.getString("Code"));
editor.putString("key_pref_branch_id", mainObject.getString("ID"));
editor.putString("key_pref_branch_name", mainObject.getString("Name"));
editor.putString("key_pref_json_url", "http://xxxxx:8080/storehandler.ashx");
editor.apply();
editor.commit();

How to get data from activity class to the PhoneStateListener class?

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);
}
}

Unable to pass string from one process to another

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

Categories

Resources