如何在我的短信管理器中添加权限 [英] how to add permission in my sms manager

查看:47
本文介绍了如何在我的短信管理器中添加权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 android studio 非常陌生,在我的第一个应用程序中,我想构建一个 sos 应用程序,我的 sos 应用程序专门通过短信发送带有当前位置的消息.当我第一次构建它时,它只能在 android 5.0 及以下版本上运行,在 6.0 及以下版本中不起作用,现在我试图查看 logcat,logcat 说它需要发送短信的权限,所以我给了它使用本段下方的代码获得许可,现在它在 android 6.0 中运行,但它不发送消息... {if(checkselfpermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION GRANTED);}

I'm very new to android studio and in my first app I want to build an sos app, my sos app specifically sends a message via sms with the current location. When I first built it, it only works on android 5.0 and down, it will not work in 6.0 and up and now I've tried to look at the logcat and the logcat says it needs a permission to send sms so I gave it a permission using the code below this paragraph and now it runs in android 6.0 but it's not sending messages... {if(checkselfpermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION GRANTED);}

你能帮我吗,这是我的清单我的文件

can you help me here is my manifest my file

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/sos"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         ATTENTION: This was auto-generated to add Google Play services to your project for
         App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information.
    -->
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".DisplayContactActivity"
        android:label="@string/title_activity_display_contact"
        android:parentActivityName=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".EditContactActivity"
        android:label="@string/title_activity_edit_contact"
        android:parentActivityName=".DisplayContactActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".LogInActivity"
        android:label="@string/title_activity_log_in"
        android:parentActivityName=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>

这是我的主要活动.

         public class MainActivity extends AppCompatActivity {
         private static final int PERMISSION_SEND_SMS = 1;

ContactDbAdapter contactDbAdapter;

private GoogleApiClient client;
EditText messageText;
UserDbAdapter userDbAdapter;
Cursor cursor;
TextView locationText;

@Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
    return super.checkUriPermission(uri, pid, uid, modeFlags);
}





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);




    userDbAdapter = new UserDbAdapter(this);
    messageText = (EditText) findViewById(R.id.messageText);
    locationText = (TextView) findViewById(R.id.locationTextView);

    try {
        userDbAdapter.open();
    } catch (SQLException error) {
        Log.e("mytag", "Error open userDbAdapter\n");
    }


    contactDbAdapter = new ContactDbAdapter(this);
    try {
        contactDbAdapter.open();
    } catch (SQLException error) {
        Log.e("mytag", "Error open contactDbAdapter\n");
    }
    cursor = contactDbAdapter.getContacts();


    final Button sos = (Button) findViewById(R.id.redbutton);
    final Button finish = (Button) findViewById(R.id.greenbutton);

    final CountDownTimer timer = new CountDownTimer(3999, 100) {
        public void onTick(long millisUntilFinished) {
            assert sos != null;
            sos.setText("" + ((int) (millisUntilFinished) / 1000));
        }
        @TargetApi(Build.VERSION_CODES.M)
        public void onFinish() {
            sos.setVisibility(View.GONE);
            finish.setVisibility(View.VISIBLE);
            finish.setText("finish");
            SmsManager smsManager = SmsManager.getDefault();
            cursor = contactDbAdapter.getContacts();

            String msg = messageText.getText().toString() + "@" + locationText.getText().toString();
            Log.e("mytag", msg);

            if(cursor.moveToFirst()){

                do{
                    if (checkSelfPermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION_GRANTED);
                    String number=cursor.getString(cursor.getColumnIndex(contactDbAdapter.PHONE_NUM));
                    smsManager.sendTextMessage(number, null, msg, null, null);
                }while(cursor.moveToNext());
            }

        }
    };

    sos.setTag(1);
    sos.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    final int status = (Integer) v.getTag();
                    if (status != 1) {
                        sos.setText("sos");
                        sos.setTag(1);
                        timer.cancel();
                    } else {
                        sos.setTag(0);
                        timer.start();
                    }

                }

            }
    );
    finish.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    sos.setVisibility(View.VISIBLE);
                    finish.setVisibility(View.GONE);
                    sos.callOnClick();
                }

            }
    );

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();


}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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();

    //noinspection SimplifiableIfStatement

    switch (id) {

        case R.id.contact:
            Intent contactIntent = new Intent(getApplicationContext(), LogInActivity.class);
            startActivity(contactIntent);
            return true;
        case R.id.message:
            Intent messageIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
            startActivity(messageIntent);
        default:
            break;
    }

    return super.onOptionsItemSelected(item);
}


@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app deep link URI is correct.
            Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
    );
    AppIndex.AppIndexApi.start(client, viewAction);
}

@Override
public  void onResume() {
    super.onResume();
    // refresh user message
    cursor = userDbAdapter.getUsers();
    if (cursor.moveToFirst()) {
        messageText.setText(cursor.getString(cursor.getColumnIndex(userDbAdapter.MESSAGE)));
    }
    // Acquire a reference to the system Location Manager
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
        return;
    }
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            locationText.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());



        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }
        public void onProviderDisabled(String provider) {


        }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if(loc != null) {

        // messageText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
        locationText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());



    }


}

@Override
public void onStop() {
    super.onStop();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app deep link URI is correct.
            Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
    );
    AppIndex.AppIndexApi.end(client, viewAction);
    client.disconnect();
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (cursor != null) {
        cursor.close();
    }
}

这也是在我授权在android 6.0上运行之前出现的logcat

this is also the logcat that appeared before I gave the permission to run it on android 6.0

 Process: com.cse4471.osu.sos_osu, PID: 23011
java.lang.SecurityException: Sending SMS message: uid 10179 does not have android.permission.SEND_SMS.
    at android.os.Parcel.readException(Parcel.java:1620)
    at android.os.Parcel.readException(Parcel.java:1573)
    at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:842)
    at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:317)
    at android.telephony.SmsManager.sendTextMessage(SmsManager.java:300)
    at com.cse4471.osu.sos_osu.MainActivity$1.onFinish(MainActivity.java:119)
    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5628)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:853)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:737)

希望你能帮我解决这个问题.

I hope you can help me with this.

推荐答案

你可以试试这个 :-

Manifest中添加-

<uses-permission android:name="android.permission.SEND_SMS" />

并在您的活动中使用此运行时权限

And use this runtime permission in your activity

 ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},1);

这篇关于如何在我的短信管理器中添加权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆