Broad cast receiver is not working - java

First i prompts the user to open the wifi or not.
I want to open the wifi if closed, scan all the wifi networks available and connect to certain one based on it's ssid.
I want to register a broad cast receiver to wait till the WifiManager to finish scanning results.
public class Project1 extends Activity {
/**
* Called when the activity is first created.
*/
EditText userName;
EditText passWord;
Button button;
TextView thankYou;
WifiManager wifiManager;
List<ScanResult> results1;
BroadcastReceiver receiver;
public Boolean connectToNetworK() {
Log.e("Start of connect","Debug");
Log.e("before wifi manager of connect","Debug");
if(!wifiManager.isWifiEnabled()){
Log.e("wifi is not enabled","Debug");
wifiManager.setWifiEnabled(true);
}
Log.e("after wifi manager of connect","Debug");
List<ScanResult>results =null;
Log.e("after scan result = null","Debug");
while(!wifiManager.isWifiEnabled())
{
Log.e("wifi still off","Debug");
}
Log.e("wifi is on","Debug");
Log.e("starting scan","Debug");
wifiManager.startScan();
Log.e("waiting","Debug");
if(results1!=null && !results1.isEmpty())
{
Log.e("Results1 is not emplty","Debug");
}
}
#Override
public void onStop()
{
unregisterReceiver(receiver);
}
public void onCreate(Bundle savedInstanceState) {
final Context contex = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(receiver == null){
Log.e("Registering reciver","mark");
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
Log.e("In broad cast reciver","mark");
results1 =wifiManager.getScanResults();
}
};
registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
}
if (!mWifi.isConnected()) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Open the Wifi");
alert.setMessage("Your Wifi is Currently Turned off, Would You like to turn it on?");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(connectToMobinilNetworK())
{
AfterWifiIsOn();
}
else{
Intent intent = new Intent(contex, ErrorPage.class);
startActivity(intent);}
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(contex, ErrorPage.class);
startActivity(intent);
}
});
alert.show();
} }
}
}
The list of scan resutls are always empty and the logs inside the broadcast receiver is not written.
Thanks in advance.

Do you have the correct permissions set up in your AndroidManifest? According to this guide, your permissions should look something like this:
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Related

how to unlock phone from service [duplicate]

I am doing an application which Locks the screen on shake. Now it is locking and from there it going to a broadcast receiver from there if the screen is off its entering into a service which has to turn the screen on.
Below is the broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Entered Broadcaste Reciever");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
System.out.println("SCREEN_OFF"+wasScreenOn);
wasScreenOn = false;
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", wasScreenOn);
context.startService(i);
System.out.println("jrkejhr keh");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
System.out.println("SCREEN_ON"+wasScreenOn);
}
}
And its entering to a service where i had written the intent action to go home is...
ShakeListener mShaker;
int amountOfTime = 0;
Context context1;
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
System.out.println("Enterd Service");
final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
vibe.vibrate(100);
Intent goHome = new Intent();
goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
goHome.setAction("android.intent.action.MAIN");
goHome.addCategory("android.intent.category.HOME");
startActivity(goHome);
}
});
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
It is entering into the service. But home screen is not displaying. When the service is invoked the the screen is locked.
Edit:
As some folks needs help in Unlocking device after locking programmatically,
I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin 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");
}
}
The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.
Thanks all for this helpful question!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kns"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".LockScreenActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
</uses-policies>
</device-admin>
Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:
FLAG_DISMISS_KEYGUARD
FLAG_SHOW_WHEN_LOCKED
FLAG_TURN_SCREEN_ON

Is there a way to open Wifi activity in android and get a result for successful connection in android

So here is my scenario ,
I want the user to click a button which takes him to the wifi networks screen using
startActivityForResult(Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),RESULT_CODE);
The user then selects a wifi network ,connects to it and the wifi setting activity closes and the user lands back into my application.
How do I achieve this?
android.provider.Settings gives Intent actions you can use to launch various settings screens (e.g., ACTION_WIFI_SETTINGS).
To work with button you must write:
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(intent);
}
});
For getting wifi connected callback, you must put permissions in manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And put this code in activity onCreate or some method:
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
connectivityManager.registerNetworkCallback(builder.build(),
new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
//Do your work here or restart your activity
Intent i = new Intent(this, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
}
#Override
public void onLost(Network network) {
//internet lost
}
});
try this:
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

application stops working when I try to connect to the internet with broadcasts

I'm building an application that when started, it checks if the device is connected to the internet, if not the app will show a snack bar telling the user to connect to the internet. On the other hand, if the device is connected to the internet, the app will go to another layout. I want my app to detect if the internet connection was lost after the device was detected to be connected to the internet.
This feature was working only when the app was started and after starting it , if the connection was lost the app wouldn't detect it.
Now I have registered the broadcast to the manifest file and the app keeps stopping whenever I change the wifi state.
Can you please help?
This is the WifiBroadcastReceiver:
public class WifiBroadcastReceiver extends BroadcastReceiver {
Context ctx;
public WifiBroadcastReceiver(){
super();
}
public WifiBroadcastReceiver(Context iCtx){
ctx = iCtx;
}
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra((WifiManager.EXTRA_NETWORK_INFO));
if(info != null && info.isConnected()){
((Activity)context).setContentView(R.layout.activity_home);
ctx.unregisterReceiver(this);
}
This is the main activity:
public class MainActivity extends AppCompatActivity {
Snackbar wifiSnackbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wifi = (WifiManager) getSystemService(this.WIFI_SERVICE);
if (!wifi.isWifiEnabled()) {
wifiSnackbar = Snackbar.make(findViewById(R.id.activity_main),
" not connected", Snackbar.LENGTH_INDEFINITE);
wifiSnackbar.setAction("Connect", new WifiButtonListener(this));
wifiSnackbar.show();
registerReceiver(new WifiBroadcastReceiver(this), new IntentFilter("android.net.wifi.STATE_CHANGE"));
} else {
setContentView ( R.layout.activity_home );
registerReceiver(new WifiBroadcastReceiver(this), new IntentFilter("android.net.wifi.STATE_CHANGE"));
}
The following is the WifiButtonListener:
public class WifiButtonListener implements View.OnClickListener {
Context ctx;
public WifiButtonListener(Context iCtx){
ctx = iCtx;
}
#Override
public void onClick(View view) {
WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
}
And this is the code for the registered receiver in the manifest:
<receiver android:name="WifiBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE" >
</action>
</intent-filter>
</receiver>

android studio calling button

I am trying to make an on click button which makes phone calls when pressed.
Here is my code for java:
public void CampusSafClick(View view){
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:6038994210"));
startActivity(callIntent);
}
I understand how to make onclick buttons, so that is not the issue.
I have this code in the manifest:
<uses-permission android:name="android.permision.CALL_PHONE"></uses-permission>
I keep getting the error Unfortunately your app has stop working.
Here is the working code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialContactPhone("123123123");
}
});
}
private void dialContactPhone(final String phoneNumber) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNumber, null)));
}
You need Action_Dial,
use below code it will open Dealer with number specified.
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
The tel: prefix is required, otherwhise the following exception will be thrown: java.lang.IllegalStateException: Could not execute method of the activity.
Action_Dial doesn't require any permission.
If you want to initiate the call directly without user's interaction, you can use action Intent.ACTION_CALL. In this case, you must add the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
I need to enter code above the application list on the manifest:
<uses-permission android:name="android.permission.CALL_PHONE"/>
You can use the following code
intent =new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+251999999999"));
startActivity(intent);
and include in manifest file
<uses-permission android:name="android.permission.CALL_PHONE"/>
ivCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (serviceListDates.get(position).getUser_mobile().length() != 0) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("NKA SERVICE");
alertDialog.setMessage("Do you want to Call ?");
alertDialog.setIcon(R.drawable.call_icon);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((DeliveredServiceOilActivity) mContext).callPhoneNumber
(serviceListDates.get(position).getUser_mobile());
}
});`enter code here
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
} else
AlertUtils.SHOW_TOAST(mContext, mContext.getString(R.string.please_add_number));
}
});
For make a call using android, It can be implement using Intents.
public void MakePhoneCall(View view){
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9961907453"));
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
I have this code in the manifest:
<uses-permission android:name="android.permision.CALL_PHONE"></uses-permission>
If you are using SDK version greater than Lolipop then you should include request permission.

How to call onReceive() to reject calls?

I've managed to write the code to block incoming calls, but it's in a different class, and I want to execute it when a user presses "yes" on the dialog box. How do I call onReceive()? What intent do I pass as the argument?
Here's the code of MainActivity -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activateButton = (Button)findViewById(R.id.activate);
activateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogBox();
}
});
}
protected void DialogBox() {
box = new AlertDialog.Builder(this);
box.setTitle("Reject incoming calls?").
setMessage("On activation, your phone will reject all incoming calls").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//BLOCK CALLS
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = box.create();
alert.show();
}
And here's the class that extends BroadcastReceiver. onReceive holds the code to reject the call.
public class RejectCall extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
ITelephony telephonyService;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(tm);
Bundle bundle = intent.getExtras();
String phoneNumber = bundle.getString("incoming_number");
Log.d("INCOMING", phoneNumber);
if ((phoneNumber != null)) {
telephonyService.endCall();
Log.d("HANG UP", phoneNumber);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Also, to perform an action as such, what permissions will I have to declare in AndroidManifest?
Note - I've gone through similar questions, but none of them seem to be calling onReceive(), hence the question.
Thank you!
You have to register your broadcast receiver in the android manifest fileas follows.
<receiver android:name=".RejectCall">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
Also, you will have to give the following permission
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Putting the above 2 pieces of code in your android manifest should trigger the onRecieve() of the reject call reciever.

Categories