android studio calling button - java

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.

Related

Android Studio: ActivityNotFoundException: Wi-Fi Settings

I'm trying to open open the wifi setting programmatically in an andoird app. It works on most devices, but on an android tablet it crashes and gives me this error:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.settings/com.android.settings.wifi.WifiSettings}; have you declared this activity in your AndroidManifest.xml?
Here is my code in the main activity:
Button wifisettings = (Button) findViewById(R.id.WiFiSettings);
wifisettings.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
intent.setComponent(cn);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
If you want to call WiFiSettings from your app use this:
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
Look into this https://developer.android.com/reference/android/provider/Settings for further sttings and how to take the user there
Try adding this in your AndroidManifest.xml:
<activity
android:name="com.android.settings.wifi.WifiSettings"/>
Same issue reported by other users in comments.
Update: If it didn't work, use this line which is simpler to use:
Button wifisettings = (Button) findViewById(R.id.WiFiSettings);
wifisettings.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});

Android application swap between activitys stops

Hei guys. I am new to Android programming. I am trying to make an app that controls a rc car (Arduino). In this app are the next activities:
Button Commands
Tilt Command
Vocal Command
Instructions
About
When I open the app it suddenly stops and I don't know why. Can someone help me by looking at the code and tell me what I am doing wrong. Thanks a lot.
Button buttonCommand;
Button tiltCommand;
Button vocalCommand;
Button instructions;
Button about;
Button arduino; // Links Button
Button android; // Links Button
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
buttonCommand = (Button)findViewById(R.id.buttons);
tiltCommand = (Button)findViewById(R.id.tilt);
vocalCommand = (Button)findViewById(R.id.vocal);
instructions = (Button)findViewById(R.id.instructions);
about = (Button)findViewById(R.id.about);
arduino = (Button)findViewById(R.id.arduino);
android = (Button)findViewById(R.id.android);
}
public void onClickButton(View view){
Intent i = new Intent(getApplicationContext(),ButtonCommand.class); // ButtonCommand Activity
startActivity(i);
}
public void onClickTilt(View view){
Intent i = new Intent(getApplicationContext(),TiltCommand.class); // TiltCommand Activity
startActivity(i);
}
public void onClickVocal(View view){
Intent i = new Intent(getApplicationContext(),VocalCommand.class); // VocalCommand Activity
startActivity(i);
}
public void onClickInstructions(View view){
Intent i = new Intent(getApplicationContext(),Instructions.class); // Instructions Activity
startActivity(i);
}
public void onClickAbout(View view){
Intent i = new Intent(getApplicationContext(),About.class); // About Activity
startActivity(i);
}
public void onClickArduino(View view){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://forum.arduino.cc/"));
startActivity(intent);
}
public void onClickAndroid(View view){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://forum.xda-developers.com/"));
startActivity(intent);
}
If your app stops at the start, probably you are missing to add the registry of your activities into your AndroidManifest.xml :
<activity android:name=".ButtonCommand" />
<activity android:name=".TiltCommand" />
<activity android:name=".VocalCommand" />
<activity android:name=".Instructions" />
<activity android:name=".About" />
George, you need to create an OnClickListener for each button for example:
buttonCommand = (Button)findViewById(R.id.buttons);
buttonCommand.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),ButtonCommand.class); // ButtonCommand Activity
startActivity(i);
}
});
Plus: and the internet permission to open urls:
<uses-permission android:name="android.permission.INTERNET" />

Android: No Activity found to handle Intent (trying to add an activity to exsisting app)

Ok so I am very new to the Android programming, I am starting week 2 of this class and cannot for the life of me figure out what is going wrong. I have read/watched tons of tutorials on adding new Activities and nothing works.
Assignment: Use the Activities app and add a fourth activity
My activity is simple, 3 buttons and an image. One button makes the image visible and the other makes it invisible. Third returns back to the main.
Note: I edited the original app to have buttons on Main Activity because it had me hitting center on the d-pad which I found dumb. Another note is that Activity 2 & 3 use the same layout and do basically the same thing from what I can tell
public class MainActivity extends Activity {
String tag = "Events";
int request_Code = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---hides the title bar---
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
Button act2Butt = (Button) findViewById(R.id.act2Butt);
Button act3Butt = (Button) findViewById(R.id.act3Butt);
Button act4Butt = (Button) findViewById(R.id.act4Butt);
act2Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.ACTIVITY2"), request_Code);
}
});
act3Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.ACTIVITY2"), request_Code);
}
});
act4Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.MYACTIVITY"), request_Code);
}
});
}
/*
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
//startActivity(new Intent("net.learn2develop.ACTIVITY2"));
//startActivity(new Intent(this, Activity2.class));
startActivityForResult(new Intent(
"net.learn2develop.ACTIVITY2"),
request_Code);
}
return false;
}
*/
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_LONG).show();
}
}
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity4);
Button yesButt = (Button) findViewById(R.id.yesButton);
Button noButt = (Button) findViewById(R.id.noButton);
Button finButt = (Button) findViewById(R.id.finButton);
final ImageView img1 = (ImageView) findViewById(R.id.image1);
yesButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
img1.setVisibility(View.VISIBLE);
}
});
noButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
img1.setVisibility(View.INVISIBLE);
}
});
finButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent data = new Intent();
data.setData(Uri.parse("OMG IT WORKS"));
setResult(RESULT_OK, data);
finish();
}
});
}
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String defaultName="";
Bundle extras = getIntent().getExtras();
if (extras!=null)
{
defaultName = extras.getString("Name");
}
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username);
txt_username.setHint(defaultName);
//---get the OK button---
Button btn = (Button) findViewById(R.id.btn_OK);
//---event handler for the OK button---
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(
txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
}
I have entered the code for Main Activity, My Activity (the one I made), and Activity 2. My Activity runs great and does exactly what I want it to but if I try to access it from main it dies.
928-928/net.learn2develop.Activities E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.learn2develop.Activities, PID: 928
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=net.learn2develop.MYACTIVITY }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1765)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at net.learn2develop.Activities.MainActivity$3.onClick(MainActivity.java:48)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This code is for my last attempt and making it work before throwing my hands up. Last thing I did was make My Activity act like the other and use startActivityForResult.
Any help would help greatly. I don't know if it matters or not but I do not have a .class for My Activity in the bin directory but there is one for all the others.
If you need any more info please just ask.
Like I said before I'm really new to the whole Android area.
Edit: Manifest
<activity android:name=".MyActivity"
android:label="My Activity">
<intent-filter>
<action android:name="net.learn2develop.MYACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
You may need to add the Activity to the manifest. If you are sure you have done this, I would recommend using an Intent slightly differently.
Try using an Intent the following way:
Intent intent = new Intent(MyActivity.this, SecondActivity.class);
startActivityForResult(intent, requestCode);
The first parameter of this Intent is the current Activity. The second parameter is theActivity you wish to navigate to. Handling an Intent this way prevents a small typo in the package name which would throw that exception. As long as the Activity you are trying to navigate to is in the manifest and you have set up your Intent like the code above, everything should work fine.
Good luck and happy coding!
you need to add your activity to your manifest
<activity
android:name=".MySecondActivity"
android:label="#string/title_second_activity">
</activity>
net.learn2develop.MYACTIVITY
Android is not finiding the above activity like other engineers said,add this activity in your manifest file so JVM can find which class you are referring to.

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.

Broad cast receiver is not working

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" />

Categories