안드로이드 자바파일로 전화번호 불러오기
본문
안녕하세요 베르만님 답변 항상 감사합니다
전화번호 불러오기 알려주신 소스를 여기저기 삽입해 봣는데
계속 에러가 생겨서요.... 다시한번 부탁 드립니다..
public class zzzzzz extends AppCompatActivity {
TextView txtview;
phpdo task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zzzzzz);
public class Test
{
public static String myPhoneNumber() {
String myNumber = null;
TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try{
myNumber = mgr.getLine1Number();
myNumber = myNumber.replace("+82", "0");
}catch(Exception e){}
return myNumber;
}
}
String id = myPhoneNumber();
String name = "";
task = new phpdo();
txtview = (TextView) findViewById(R.id.txtView);
task.execute(id, name);
}
이렇게 하면 위의 빨간색 부분에 오류가 발생 되구요
public class zzzzzz extends AppCompatActivity {
TextView txtview;
phpdo task;
public class Test
{
public static String myPhoneNumber() {
String myNumber = null;
TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try{
myNumber = mgr.getLine1Number();
myNumber = myNumber.replace("+82", "0");
}catch(Exception e){}
return myNumber;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zzzzzz);
String id = myPhoneNumber();
String name = "";
task = new phpdo();
txtview = (TextView) findViewById(R.id.txtView);
task.execute(id, name);
}
이렇게 하면 위의 빨간색 부분에 오류가 발생 되구요
public class Test
{
public static String myPhoneNumber() {
String myNumber = null;
TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try{
myNumber = mgr.getLine1Number();
myNumber = myNumber.replace("+82", "0");
}catch(Exception e){}
return myNumber;
}
}
public class zzzzzz extends AppCompatActivity {
TextView txtview;
phpdo task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zzzzzz);
String id = myPhoneNumber();
String name = "";
task = new phpdo();
txtview = (TextView) findViewById(R.id.txtView);
task.execute(id, name);
}
이렇게 하면 위의 빨간색 부분에 오류가 발생 됩니다..
어떻게 해야 할까요???
답변 3
3가지 방법 모두 syntax error(구문에러) 입니다.
바로 직전에 답변 달아드린 것으로
아얘 교체를 해보세요.
그리고 문법적으로 학습을 하셔야 할것 같습니다.
한가지 궁금한 점이
왜 동작 확인도 제대로 안되었는데, 채택하시고 또 같은질문 올리시고 하는지
이해가 잘 가지 않습니다.
베르만님 댓글쓰지 글자 제한때문에 답변글로 올립니다..
현재 만들고 있는 자바 소스 입니다
알려주신 바대로 적용 하면
전화번호 가져오는 소스 중에 static getSystemService 두 부분에 빨간색 밑줄이 쳐집니다..
package call.exam.jsh.telepo;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.os.AsyncTask;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import static android.R.attr.name;
import static call.exam.jsh.telepo.MainActivity.Test.myPhoneNumber;
import static call.exam.jsh.telepo.R.layout.activity_main;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button1;
Button button2;
Button button3;
TextView txtview;
phpdo task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
String id = myPhoneNumber();
String name = "";
task = new phpdo();
txtview = (TextView) findViewById(R.id.txtView);
task.execute(id, name);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.Button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Pop.class));
}
});
button3 = (Button) findViewById(R.id.Button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Pop1.class));
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 사용자의 OS 버전이 마시멜로우 이상인지 체크한다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/** * 사용자 단말기의 권한 중 "전화걸기" 권한이 허용되어 있는지 확인한다. * Android는 C언어 기반으로 만들어졌기 때문에 Boolean 타입보다 Int 타입을 사용한다.
*
*/
int permissionResult = checkSelfPermission(Manifest.permission.CALL_PHONE);
/** * 패키지는 안드로이드 어플리케이션의 아이디이다. * 현재 어플리케이션이 CALL_PHONE에 대해 거부되어있는지 확인한다. */
if (permissionResult == PackageManager.PERMISSION_DENIED) {
/** * 사용자가 CALL_PHONE 권한을 거부한 적이 있는지 확인한다. * 거부한적이 있으면 True를 리턴하고 * 거부한적이 없으면 False를 리턴한다. */
if (shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("권한이 필요합니다.")
.setMessage("이 기능을 사용하기 위해서는 단말기의 \"전화걸기\" 권한이 필요합니다. 계속 하시겠습니까?")
.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/** * 새로운 인스턴스(onClickListener)를 생성했기 때문에 * 버전체크를 다시 해준다. */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// CALL_PHONE 권한을 Android OS에 요청한다.
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1000);
}
}
})
.setNegativeButton("아니요", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "기능을 취소했습니다", Toast.LENGTH_SHORT).show();
}
})
.create()
.show();
}
// 최초로 권한을 요청할 때
else {
// CALL_PHONE 권한을 Android OS에 요청한다.
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1000);
}
}
// CALL_PHONE의 권한이 있을 때
else {
// 즉시 실행
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:*** 개인정보보호를 위한 휴대폰번호 노출방지 ***"));
startActivity(intent);
}
}
// 마시멜로우 미만의 버전일 때
else {
// 즉시 실행
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:*** 개인정보보호를 위한 휴대폰번호 노출방지 ***"));
startActivity(intent);
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 사용자의 OS 버전이 마시멜로우 이상인지 체크한다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/** * 사용자 단말기의 권한 중 "전화걸기" 권한이 허용되어 있는지 확인한다. * Android는 C언어 기반으로 만들어졌기 때문에 Boolean 타입보다 Int 타입을 사용한다.
*
*/
int permissionResult = checkSelfPermission(Manifest.permission.CALL_PHONE);
/** * 패키지는 안드로이드 어플리케이션의 아이디이다. * 현재 어플리케이션이 CALL_PHONE에 대해 거부되어있는지 확인한다. */
if (permissionResult == PackageManager.PERMISSION_DENIED) {
/** * 사용자가 CALL_PHONE 권한을 거부한 적이 있는지 확인한다. * 거부한적이 있으면 True를 리턴하고 * 거부한적이 없으면 False를 리턴한다. */
if (shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("권한이 필요합니다.")
.setMessage("이 기능을 사용하기 위해서는 단말기의 \"전화걸기\" 권한이 필요합니다. 계속 하시겠습니까?")
.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/** * 새로운 인스턴스(onClickListener)를 생성했기 때문에 * 버전체크를 다시 해준다. */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// CALL_PHONE 권한을 Android OS에 요청한다.
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1000);
}
}
})
.setNegativeButton("아니요", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "기능을 취소했습니다", Toast.LENGTH_SHORT).show();
}
})
.create()
.show();
}
// 최초로 권한을 요청할 때
else {
// CALL_PHONE 권한을 Android OS에 요청한다.
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1000);
}
}
// CALL_PHONE의 권한이 있을 때
else {
// 즉시 실행
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:*** 개인정보보호를 위한 전화번호 노출방지 ***"));
startActivity(intent);
}
}
// 마시멜로우 미만의 버전일 때
else {
// 즉시 실행
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:*** 개인정보보호를 위한 전화번호 노출방지 ***"));
startActivity(intent);
}
}
});
}
public class Test
{
public static String myPhoneNumber() {
String myNumber = null;
TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try{
myNumber = mgr.getLine1Number();
myNumber = myNumber.replace("+82", "0");
}catch(Exception e){}
return myNumber;
}
}
private class phpdo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... arg0) {
try {
String id = arg0[0];
String link = "http://sun7684.dothome.co.kr/testquery.php?ID=" + id + "&NAME=" + name;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
//txtview.setText("Login Successful");
txtview.setText(result);
}
}
}
중복 질문이군요
static 변수특성상 내장 변수, 객체들을 사용할 수 없습니다
아래 소스를 사용하세요
다른 오류가 발생하면
질문올려주세요 답변해드리겠습니다.
String id = myPhoneNumber(MainActivity.this);
public static String myPhoneNumber(Context context) {
String myNumber = null;
TelephonyManager mgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
myNumber = mgr.getLine1Number();
myNumber = myNumber.replace("+82", "0");
}catch(Exception e){}
return myNumber;
}
}
exception
[ɪk|sepʃn] Eng
1.exception
[명사] (일반적인 상황의) 예외
2.make an exception
예외를 허락하다
3.take exception to something
~에 이의를 제기하다; ~에 화를 내다
4.without exception
예외 없이
5.with the exception of
~은 제외하고[~ 외에는]
6.예외 例外
exception
7.격외 格外
exception, speciality
8.ex.
examination; examined; example; except; exception; exchange; excursion; executed
9.제각 除却
exception; elimination. 제각하다 exclude; except; eliminate; disregard.
10.예외사항
(전력) exception
1.exception
[명사] (일반적인 상황의) 예외
2.make an exception
예외를 허락하다
3.take exception to something
~에 이의를 제기하다; ~에 화를 내다
4.without exception
예외 없이
5.with the exception of
~은 제외하고[~ 외에는]
6.예외 例外
exception
7.격외 格外
exception, speciality
8.ex.
examination; examined; example; except; exception; exchange; excursion; executed
9.제각 除却
exception; elimination. 제각하다 exclude; except; eliminate; disregard.
10.예외사항
(전력) exception
{"mean":["exception<br></br>[명사]\n\t\t\t\t (일반적인 상황의) 예외","make an exception<br></br>예외를 허락하다","take exception to something<br></br>~에 이의를 제기하다; ~에 화를 내다","without exception<br></br>예외 없이","with the exception of<br></br>~은 제외하고[~ 외에는]","예외\n\t\t\t \t例外<br></br>exception","격외\n\t\t\t \t格外<br></br>exception, speciality","ex.<br></br>examination; examined; example; except; exception; exchange; excursion; executed","제각\n\t\t\t \t除却<br></br>exception; elimination. 제각하다 exclude; except; eliminate; disregard.","예외사항<br></br>(전력)\n\t \t\texception"],"word":"\n\t\t\t\t\t\t\t\t\texception\n\t\t\t \t\t\t\n\t\t\t\t \t\n\t\t\t\t ","soundUrl":"http://dic.dn.naver.com/v?_lsu_sa_=30b85a5aedeb39c60195c1f433240dfecd48696536041fa66e92aa7eeb5d6b21895cf7e06895697cd97d66c58c25209c075a59d4740f7a8366b08c6cb6e71e286cdcfa814244cb2b187b19ab1223d19ce22420a735b655ec2e9ea3c95bcf49fb3d67f803261ac21327cbd2806fa893c79de7944ae8f6333ab4b6863e242ffabf","phoneticSymbol":"[ɪk|sepʃn]"}
답변을 작성하시기 전에 로그인 해주세요.