I would like to set my own activity infront the call screen. I have seen that there are many examples for this but with the older versions of android, while I want it to work with android 6.0 and above. This means that I have to deal with the permissions. I managed to grant the necessary permissions. After that I make a Class that inherits BroadcastReceiver so that I can detect when the phone is ringing, the only problem is that I can't send my activity infront of the call display. These are some of the classes I use:
public class PhoneStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Toast.makeText(context, " Receiver start ", Toast.LENGTH_SHORT).show();
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Toast.makeText(context, "Ringing State Number is -", Toast.LENGTH_SHORT).show();
Intent dialogIntent = new Intent(context, LockActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
context.startActivity(dialogIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LockActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lock_screen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+ WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
+WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
+WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
Button btnLock = (Button) findViewById(R.id.btnUnlock);
final EditText txtPass = (EditText) findViewById(R.id.txtPass);
btnLock.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String pass = txtPass.getText().toString();
if(pass.equals("pass")||pass.equals("пасс")) {
finish();
}else{
Toast.makeText(LockActivity.this, "Wrong password!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
If anything else is needed please ask!
I managed to solve it, the problem is that it takes time to start the in-built call activity, so my activity started first and the other went on top of it. Therefore I made the current thread of my activity to sleep for less than a second. The in-built activity was launched and then my activity went on top of it.
public class PhoneStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Toast.makeText(context, " Receiver start ", Toast.LENGTH_SHORT).show();
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Toast.makeText(context, "Ringing State Number is -", Toast.LENGTH_SHORT).show();
Intent dialogIntent = new Intent(context, LockActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Thread.sleep(700);
context.startActivity(dialogIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
What I want is... when an incoming call is coming it will answered automatically.
Here is my code but its not working.
public class PhoneStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Toast.makeText(context, "Incoming Call State", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Ringing State Number is -" + incomingNumber, Toast.LENGTH_SHORT).show();
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))) {
Toast.makeText(context, "Call Received State", Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Toast.makeText(context, "Call Idle State", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I hope in the RINGING function I need to do some code. But I am not getting the proper ans so I post this. Please Developers Help me out.
Thanks in advance
I have device tracker application, where user needs to login so that devices is assigned to it.
But, now I want user should not able to use that devices until user have authenticated and should be available until user sing-out from that device ?
I want to retrieve password entered by user when he unlocks the screen and want to use it for my application authentication it's self and if password do not match I will unlock screen again.
I'm trying following code but still not basically able to lock and unlock screens using password.
public class AdminSettingsActivity extends Activity {
private EditText baseURLEditText;
private Button saveBaseURL;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
saveBaseURL = (Button) findViewById(R.id.saveBaseURLBtn);
baseURLEditText = (EditText) findViewById(R.id.base_url_edit);
tv = (TextView) findViewById(R.id.text_admin_message);
tv.append(" " + DeviceTrackerApp.DEFAULT_BASE_URL);
saveBaseURL.setOnClickListener(new OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
String url = baseURLEditText.getText().toString().trim();
if (!url.isEmpty()) {
try {
if (URLUtil.isValidUrl(url)) {
new ValidateServerURL(AdminSettingsActivity.this).execute(url);
} else {
showInvalidURLToast();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
protected void showInvalidURLToast() {
// get your custom_toast.xml ayout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
// set a dummy image
ImageView image = (ImageView) layout.findViewById(R.id.image_invalid_pwd);
image.setImageResource(R.drawable.invalid_pwd);
// set a message
TextView text = (TextView) layout.findViewById(R.id.text_invalid_password);
text.setText("Invalid URL! Can't Save.");
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
public void setURLStatus(int statusCode) {
if (statusCode == 200) {
DeviceTrackerApp.setBaseURL(baseURLEditText.getText().toString());
Toast.makeText(getApplicationContext(), "Valid URL Saved Successful",
Toast.LENGTH_LONG).show();
tv.setText("\nYour Setting saved successfuly. Press back button to go home screen\n");
} else {
showInvalidURLToast();
baseURLEditText.setText("");
}
}
}
and My DeviceTrackerAdmin class is
public class DeviceTrackerAdmin extends DeviceAdminReceiver {
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
#Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
#Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
I also defined reciever in AndroidMenifest.xml
<receiver
android:name=".DeviceTrackerAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="com.abc.devicetracker.DeviceTrackerApp"
android:resource="#layout/policies" >
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" >
</action>
</intent-filter>
</meta-data>
</receiver>
But, every time onActivityResult() on
`if (resultCode == RESULT_OK)` **OR** `if (resultCode == Activity.RESULT_OK)` condition fails as `resultCode is 0 only` So for Device locking I need to root my mobile.
when u got password is correct or incorrect the password then use following code
//Get the window from the context
WindowManager wm = Context.getSystemService(Context.WINDOW_SERVICE);
//Unlock if password is incorrect
http://developer.android.com/reference/android/app/Activity.html#getWindow()
Window window = getWindow();
window.addFlags(wm.LayoutParams.FLAG_DISMISS_KEYGUARD);
//Lock device if password is correct
DevicePolicyManager mDPM;
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
I have found a github project and I'm modifying it as per my requirements.
Thanks to All for your efforts.
https://github.com/wordpress-mobile/Android-PasscodeLock
https://github.com/swapnilvkotwal/LockScreenApp
And found this answer helpful Creating an Android Lock Screen App.
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.anaekran);
Thread t = new Thread(new Runnable() {
public void run() {
String smsMsj = getIntent().getStringExtra("sms");
if(smsMsj != null){
Toast.makeText(getApplication(), smsMsj, 2).show();
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle mesaj = intent.getExtras();
SmsMessage[] smsMessage = null;
String msj = "";
if(mesaj!= null){
Object[] pdus = (Object[])mesaj.get("pdus");
smsMessage = new SmsMessage[pdus.length];
for(int i = 0; i < pdus.length; i++){
smsMessage[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msj = smsMessage[i].getMessageBody();
}
Intent mIntent = new Intent(context, SmsReceiver.class);
mIntent.putExtra("sms", msj);
}
}
}
My receiver working correctly but i have one problem when message coming i want to show on my MainAcitivty toast, so i create mIntent in receiver class, and then im use putExtra method.
But not working, sory for my bad english and thank you :)
Perhaps using explicit Intent and starting it could help you, hm? :)
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.putExtra("sms", msj);
context.startActivity(mIntent);
Your mistake is that you construct your new Intent with SmsReceiver.class (but you need to launch MainActivity) and that you do not start any activity with such an intent.
Edit 1: Also, pay attention - you are trying to run a toast inside your worker thread. This is not possible. Remove your anonymous Thread and move your toast code to your onCreate(Bundle):
protected void onCreate(Bundle saveState){
....
String smsMsj = getIntent().getStringExtra("sms");
if(smsMsj != null){
Toast.makeText(getApplication(), smsMsj, 2).show();
}
....
}
Edit 2: Moreover, your duration parameter in Toast.makeText(..) is set to 2. This does not correspond to any magic constant in Toast class. You have to use one of the constants: Toast.LENGTH_LONG or Toast.LENGTH_SHORT. So, rewrite your code to:
Toast.makeText(getApplication(), smsMsj, Toast.LENGTH_SHORT);
my problem is:
I want my application to block buttons or whole activity when there is no internet connection and unblock them when internet connection is back. I'm using BroadcastReceiver to check internet in main activity and it works well:
public class MainActivity extends BroadCast {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
// code
}
To block MainActivity I'm using ProgressDialog with method setCancelable set to false.
BroadCast Activity:
public class BroadCast extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public BroadcastReceiver mConnReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
#SuppressWarnings("deprecation")
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(currentNetworkInfo.isConnected()) {
BlockActivity(true);
}
else {
BlockActivity(false);
}
}
};
public void BlockActivity(Boolean connected)
{
final ProgressDialog pausingDialog = ProgressDialog.show(this, "", "Application waiting for internet connection...");
if (!connected)
{
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
pausingDialog.show();
pausingDialog.setCancelable(false);
}
else
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
pausingDialog.setCancelable(true);
pausingDialog.dismiss();
}
}
}
Toast information works good, but the problem is with ProgressDialog. It shows up when internet connection is gone, but it don't want to disappear when internet connection is back. How to fix it? Thanks.
Keep a global reference to your dialog so you don't keep recreating it. You should also use primitive types (boolean instead of Boolean)where possible and adhere to Java naming conventions (camelCase).
ProgressDialog pausingDialog;
public void blockActivity(boolean connected)
{
if (pausingDialog == null){
pausingDialog = new ProgressDialog (this);
pausingDialog.setMessage ("Application waiting for internet connection...");
}
if (!connected)
{
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_LONG).show();
pausingDialog.show();
pausingDialog.setCancelable(false);
}
else
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
pausingDialog.setCancelable(true);
pausingDialog.dismiss();
}
}
Simple Code In Kotlin
var pausingDialog:SweetAlertDialog?=null
fun blockActivity(connected: Boolean,context: Context) {
if (pausingDialog == null) {
pausingDialog =SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
pausingDialog!!.titleText = "Application waiting for internet connection..."
pausingDialog!!.setCancelable(false)
pausingDialog!!.setConfirmClickListener{
var MyReceiver: BroadcastReceiver?= null;
MyReceiver = com.example.myrecharge.Helper.MyReceiver()
context.registerReceiver(MyReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
}
if (!connected) {
Toast.makeText(
context,
"Disconnected",
Toast.LENGTH_LONG
).show()
pausingDialog!!.show()
Log.d("##", "onReceive: 1")
} else {
Toast.makeText(
context,
"Connected",
Toast.LENGTH_LONG
).show()
pausingDialog!!.dismiss()
}
}
I want to block a specific phone number that is in my database
I do a comparison between the number the user dialed, and the number in memory. If they are equal, I block the call.
My code:
public void onReceive(Context context, Intent intent) {
PlaceDataSQL placeDataSQL =new PlaceDataSQL(context);
ArrayList<String> getUsersPhoneNumbers= placeDataSQL.getUsersPhoneNumbers();
//TODO
//===========
//here I need to check the number
Bundle b = intent.getExtras();
String incommingNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
//String outGoingNumber = b.getString(TelephonyManager.);
Boolean find=false;
try {
for(int i=0;i<getUsersPhoneNumbers.size();i++)
{
if(incommingNumber.equals(getUsersPhoneNumbers.get(i)))
{
find=true;
break;
}
}
} catch (Exception e) {
incommingNumber="";
}
// ========================================
//here the problem
//=========================================
String phonenumber=b.getString(Intent.EXTRA_PHONE_NUMBER);
try {
for(int i=0;i<getUsersPhoneNumbers.size();i++)
{
if(phonenumber.equals(getUsersPhoneNumbers.get(i)))
{
find=true;
break;
}
}
if (!find)
return;
}catch (Exception e) {
phonenumber="";
}
if (!find)
return;
/* examine the state of the phone that caused this receiver to fire off */
String phone_state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (phone_state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
logMe("Phone Ringing: the phone is ringing, scheduling creation call answer screen activity");
Intent i = new Intent(context, CallAnswerIntentService.class);
i.putExtra("delay", 100L);
i.putExtra("number", incommingNumber);
context.startService(i);
logMe("Phone Ringing: started, time to go back to listening");
}
if (phone_state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
Intent i = new Intent(context,InCallScreenGuardService.class);
i.putExtra("delay", 100L);
i.putExtra("number", phonenumber);
logMe("Phone Offhook: starting screen guard service");
context.startService(i);
}
if (phone_state.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
Intent i = new Intent(context,InCallScreenGuardService.class);
logMe("Phone Idle: stopping screen guard service");
context.stopService(i);
}
return;
}
The problem:
I can get incoming numbers but I can't get outgoing numbers?
You will need a BroadcastReciever for this.
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
String phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i("OutgoingCallReceiver",phonenumber);
Log.i("OutgoingCallReceiver",bundle.toString());
String info = "Detect Calls sample application\nOutgoing number: " + phonenumber;
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
}
}