My project is about communication between 2 phones, on which the app will be installed.
The communication is an SMS communication, each SMS contains data and the receiving device must interpret it and sort in specified ListViews.
The project contains classes of: Send Data Form and class of 3 ListViews displaying the received data.
My problem is , that I'm not sure If my sms is sent(Because a dialog window does not appear after clicking the send button. Moreover, on the second emulator there is no indication whenever there is an incoming SMS message.
Send Data Form:
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AddContactDeatils extends Activity implements OnClickListener {
Button sendToParallel, sendToParallel2;
TextView nameT, idT, phoneT;
EditText nameF, idF, phoneF;
int recipient;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact_form);
sendToParallel=(Button)findViewById(R.id.sendToParallel);
sendToParallel.setOnClickListener(this);
sendToParallel2=(Button)findViewById(R.id.sendToParallel2);
sendToParallel2.setOnClickListener(this);
nameT=(TextView)findViewById(R.id.nameTitle);
idT=(TextView)findViewById(R.id.idTitle);
phoneT=(TextView)findViewById(R.id.phoneTitle);
nameF=(EditText)findViewById(R.id.nameField);
idF=(EditText)findViewById(R.id.idField);
phoneF=(EditText)findViewById(R.id.phoneField);
}
protected void sendSms(String phoneNumber, String message) {
// TODO Auto-generated method stub
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
public void checkRecipient(EditText et)
{
try {
recipient=Integer.parseInt(et.toString());
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(this, "Only numbers are allowed", Toast.LENGTH_LONG).show();
et.setText("");
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
String message = null;
String name=nameF.toString();
message+=name+";";
String idTxt=idF.toString();
message+=idTxt+";";
String phone=phoneF.toString();
message+=phone;
switch(id)
{
case R.id.sendToParallel:
{
sendSms("5554", message) ;
break;
}
case R.id.sendToParallel2:
{
sendSms("5556", message) ;
break;
}
}
}
}
3 ListViews Displaying recieved data
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DataLists extends Activity implements OnClickListener {
ListView idList, namesList, phonesList;
MyReciever mr;
ArrayList<String>ids= new ArrayList<String>();
ArrayList<String>names=new ArrayList<String>();
ArrayList<String>phones=new ArrayList<String>();
ArrayAdapter<String> idAdapter, namesAdapter, phonesAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details_lists);
idList=(ListView)findViewById(R.id.idList);
namesList=(ListView)findViewById(R.id.namesList);
phonesList=(ListView)findViewById(R.id.phonesList);
idAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,ids );
idList.setAdapter(idAdapter);
namesAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
namesList.setAdapter(namesAdapter);
phonesAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, phones);
phonesList.setAdapter(phonesAdapter);
}
public void addItemToIdList(String st)
{
ids.add(st);
idAdapter.notifyDataSetChanged();
}
public void addItemToNamesList(String st)
{
names.add(st);
namesAdapter.notifyDataSetChanged();
}
public void addItemToPhonesList(String st)
{
phones.add(st);
phonesAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private class MyReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle=intent.getExtras();
SmsMessage[]msgs=null;
if(bundle!=null)
{
Object[]pdus=(Object[]) bundle.get("pdus");
msgs=new SmsMessage[pdus.length];
for(int i=0;i<msgs.length;i++)
{
int index=0, prev=0;
String msgBody=msgs[i].getMessageBody().toString();
index=msgBody.indexOf(';');
prev=index;
String name=msgBody.substring(0, index);
addItemToNamesList(name);
msgBody=msgBody.substring(index+1);
index=msgBody.indexOf(';');
String id=msgBody.substring(prev, index);
addItemToIdList(id);
msgBody=msgBody.substring(index+1);
String phone=msgBody;
addItemToPhonesList(phone);
}
}
}
}
}
Add Pemissions for Send and Recive SMS
<uses-permission android:name="android.permission.SEND_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" >
</uses-permission>
and Run Two Emulator for Send Sms.. eg 5554 to 5556
Related
I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.
I'm developing a simple chat app and it just stops after transmitting the message. The Server shows the message that means that it is sent successfully but my app crashes after that. This is the Client code :
package com.example.androidpc;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Chat extends Activity {
Socket socket;
EditText msg_txt;
TextView chatfield_tv;
Button send_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
msg_txt = (EditText) findViewById(R.id.msg_txt);
chatfield_tv = (TextView) findViewById(R.id.chatfield_tv);
send_btn = (Button) findViewById(R.id.send_btn);
socket = SocketWrapper.getSocket();
send_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new chatIO().execute();
}
});
}
private class chatIO extends AsyncTask<String,String,String>{
PrintStream ps;
Scanner scan;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
ps = new PrintStream(socket.getOutputStream());
ps.println(msg_txt.getText().toString());
publishProgress("you");
scan = new Scanner(socket.getInputStream());
publishProgress("i");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
if(values[0].equals("you"))
{
chatfield_tv.append("You : "+msg_txt.getText().toString());
msg_txt.setText("");
}
else
{
chatfield_tv.append("Server : "+scan.nextLine());
}
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
ps.flush();
scan.close();
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am developing an application that has a form to send email without in-built application. I have seen so many examples for email sending. In all the examples, it is for so many email ID. That means we can send email to multiple persons at a time. But I want to send email to one person only. I am following this tutorial. Please let me know where and what should I have to change the code.
http://javapapers.com/android/android-email-app-with-gmail-smtp-using-javamail/
From this tutorial in the ToEmail box, we can add multiple email ID. But I want to add a single email ID only.Please help me where should I change this.This is the code I have edited from this tutorial..plzzz help.
import java.util.Arrays;
import java.util.List;
import javax.security.auth.Subject;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Contact extends Activity implements OnClickListener, OnItemSelectedListener
{
Button submit1,clear;
EditText et1,et2,et3;
Spinner spin;
String[] selction = { "I want to request a mobile feature",
"I want to tell about something that I like",
"I want to tell you about something that I do not like",
"I have general comments",
"I want to contact the office",
"I want to suggest an improvement in the church premise"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
Spinner spin=(Spinner)findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
#SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,selction);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
//--------------------Submit_Button_Start-----------------------------------------------------------
final Button submit1=(Button)findViewById(R.id.button1);
submit1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail ="user#gmail.com";
String fromPassword="password";
String toEmails="anything#gmail.com";
//List<String> toEmailList = Arrays.asList(toEmails.split("\\s*,\\s*"));
//Log.i("SendMailActivity", "To List: " + toEmailList);
String emailBody = ((TextView) findViewById(R.id.editText1)).getText().toString();
new SendMailTask(Contact.this).execute(fromEmail,fromPassword, toEmails, emailBody);
}
});
//--------------------Submit_Button_End-----------------------------------------------------------
clear=(Button)findViewById(R.id.button2);
clear.setOnClickListener(this);
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
/*ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.question,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);*/
}
public boolean onCactivity_list_itemreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact, menu);
return true;
}
/*
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
*/
#Override
public void onClick(View v1)
{
if(v1==clear)
{
et1.setText("");
et2.setText("");
et3.setText("");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
/*
new AlertDialog.Builder(Contact1.this)
.setMessage("Your requested has been Accepted\nThank You")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
})
.show();*/
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
It looks like you should just build a list with only one item. Something like:
...
List<String> toEmailList = new ArrayList<String>();
toEmailList.add("anything#gmail.com");
...
I am working on an android app which is having functionality of tabs.
Everything is working fine but I am not able to call activtygroup from listadapter.
Here is my code for list adapter:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.socialgoal.R;
import com.tv.socialgoal.imageloader.ImageLoader;
public class AllyListAdapter extends BaseAdapter{
Activity ctx;
ArrayList<Object> alist;
private ImageLoader imageLoader;
AllyBean allyBean;
private String photoPath;
public AllyListAdapter(Activity ctx, ArrayList<Object> alist) {
super();
this.ctx = ctx;
this.alist = alist;
imageLoader=new ImageLoader(ctx);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return alist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
LayoutInflater linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
View v=linf.inflate(R.layout.ally_list_row, null);
TextView tv=(TextView)v.findViewById(R.id.allyName);
ImageView profileImage=(ImageView)v.findViewById(R.id.ally_image);
Button inviteBtn=(Button)v.findViewById(R.id.invite_btn);
//SHOW DATA FROM LIST
allyBean=(AllyBean)alist.get(position);
tv.setText(allyBean.getName());
photoPath=allyBean.getAvatar();
profileImage.setTag(photoPath);
imageLoader.displayImage(photoPath, ctx, profileImage, false);
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
});
return v;
}
/*public void replaceContentView(String id, Intent newIntent) {
View view =getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}*/
}
Now I have to call AddRemoveFriends activtygroup.
Here is the code for activtygroup:
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.tv.servercommunication.IServerResponse;
import com.tv.servercommunication.WebServiceCommunicator;
import com.tv.socialgoal.Constant;
import com.tv.socialgoal.R;
import com.tv.socialgoal.network.NetworkAvailablity;
import com.tv.task.TabViewActivity;
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse{
Button backBtn;
Button addRemoveFriendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_profile_screen);
backBtn=(Button)findViewById(R.id.back_button);
addRemoveFriendBtn=(Button)findViewById(R.id.add_remove_frnd_btn);
backBtn.setOnClickListener(this);
addRemoveFriendBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_button:
break;
case R.id.add_remove_frnd_btn:
callAddFriend_WS();
break;
default:
break;
}
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case Constant.PID_ADD_REMOVE_FRIEND:
if (parseResponse(msg.obj.toString()) == true) {
Intent intent = new Intent(getParent(),
TabViewActivity.class);
startActivity(intent);
} else {
runOnUiThread(new Runnable() {
public void run() {
Constant.showAlertDialog(
Constant.DIALOG_TITLE_ERROR,
"Invalid username or password.",
getParent(), false);
}
});
}
break;
default:
break;
}
}
};
// GET USER ACCESSTOCKEN AND USER ID
private boolean parseResponse(String response) {
String message = null;
JSONObject post;
boolean isUserInfoAvail = false;
try {
JSONObject postjsonObject = new JSONObject(response);
JSONObject posts = postjsonObject.getJSONObject("posts");
post = posts.getJSONObject("post");
message = post.getString("message");
if (message.equalsIgnoreCase("failure")) {
isUserInfoAvail = false;
} else {
isUserInfoAvail = true;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return isUserInfoAvail;
}
public void callAddFriend_WS() {
if (NetworkAvailablity.checkNetworkStatus(AddRemoveFriendScreen.this)) {
// PREPARE URL
Constant.methodURL = "http://admin.tvdevphp.com/goalmachine/add_friend.php";
// PREPARE REQUEST PARAMETER
ArrayList<NameValuePair> requestParaList = new ArrayList<NameValuePair>();
requestParaList.add(new BasicNameValuePair("self_user_id", "1"));
requestParaList.add(new BasicNameValuePair("user_friend_id", "2"));
// CALL WEBSERVICE
WebServiceCommunicator.getInstance().registerForServerResponse(
AddRemoveFriendScreen.this);
WebServiceCommunicator.getInstance().callGetAppWebService(
Constant.showDialog, getParent(),
Constant.methodURL, getParent(), Constant.PID_ADD_REMOVE_FRIEND,
false, requestParaList);
} else {
Constant.showAlertDialog(Constant.errorTitle,
Constant.MSG_CHECK_INTERNET_SETTING, getParent(),
false);
}
}
// SERVER RESPONSE METHOD
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
}
Please suggest me how to call activtygroup from listadapter.
Make it like this you can access everything by doing like this.
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
}
class AllyListAdapter extends BaseAdapter
{
//Now you can call everything from ActivityGroup
}
}
Hope this will help you.
According to the android developper reference, you may use Fragments.
ActivityGroup is deprecated. Use the new Fragment and FragmentManager APIs instead; these are also available on older platforms through the Android compatibility package.
You can try this trick.
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(ctx instanceof ActivityGroup){
Intent intent = new Intent(ctx.getParent(),AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.getParent().startActivity(intent);
}
else{
Intent intent = new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
}
});
If it doesn't work just use internal class for your adapter in your AddRemoveFriendScreen class.
I am trying to allow certain contacts to ring even the phone is in silent mode. When the first call comes after installing the app the phone is not ringing but later on wards it is working perfectly.... Is there any problem in the code...
package com.cnu.incoming;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class IncomingCall extends BroadcastReceiver{
private Context context;
private String PhNumber;
private int ringcheck=0;
String state=null;
Bundle bundle=null;
#Override
public void onReceive(Context context, Intent intent) {
AudioManager maudio=(AudioManager)context.getSystemService(context.AUDIO_SERVICE);
bundle = intent.getExtras();
this.context = context;
if(null == bundle)
return;
Log.i("IncomingCallReceiver",bundle.toString());
state = bundle.getString(TelephonyManager.EXTRA_STATE);
Log.i("IncomingCallReceiver","State: "+ state);
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
{
check();
if(PhNumber.equals("+919876543210"))
makeitNormal();
PhNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("IncomingCallReceiver","Incomng Number: " + PhNumber);
String info = "Detect Calls Incoming number: " + PhNumber;
maudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
Log.i("baddu gadu" ,"baddu gadu");
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
makeItSilent();
}
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE))
{
makeItSilent();
}
}
private void check() {
// TODO Auto-generated method stub
AudioManager maudio=(AudioManager)context.getSystemService(context.AUDIO_SERVICE);
ringcheck=maudio.getRingerMode();
}
private void makeitNormal() {
// TODO Auto-generated method stub
AudioManager maudio=(AudioManager)context.getSystemService(context.AUDIO_SERVICE);
maudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//Toast.makeText(context, "this is baradwaj", Toast.LENGTH_LONG).show();
}
private void makeItSilent() {
// TODO Auto-generated method stub
AudioManager maudio=(AudioManager)context.getSystemService(context.AUDIO_SERVICE);
int ringer=maudio.getRingerMode();
if (ringcheck==AudioManager.RINGER_MODE_SILENT){
maudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}else if(ringcheck==AudioManager.RINGER_MODE_NORMAL){
maudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
else if(ringcheck==AudioManager.RINGER_MODE_VIBRATE){
maudio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
}
}