如何在我的短信管理员

时间:2018-04-18 09:22:51

标签: java android android-studio permissions

我是android studio的新手,在我的第一个应用程序中我想构建一个sos应用程序,我的sos应用程序专门通过短信发送一条消息与当前位置。当我第一次构建它时,它只适用于android 5.0及以下版本,它不能在6.0及以上版本中工作,现在我已经尝试查看logcat,而logcat说它需要获得发送短信的权限所以我给了它是使用本段下面的代码的权限,现在它在Android 6.0中运行,但它没有发送消息... {if(checkselfpermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION GRANTED);}

你能帮助我吗?这是我的文件

<?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

 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)

我希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

你可以试试这个: -

Manifest -

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

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

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