0

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>

and here is my main activity.

         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();
    }
}

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.

LJ Ca-ong
  • 23
  • 1
  • 7
  • 2
    Possible duplicate of [Android permission doesn't work even if I have declared it](https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it) – AskNilesh Apr 18 '18 at 09:23
  • https://stackoverflow.com/questions/34057030/android-android-permission-send-sms-not-working – AskNilesh Apr 18 '18 at 09:24
  • You need to ask **[`runtime permission`](https://developer.android.com/training/permissions/requesting.html)** – AskNilesh Apr 18 '18 at 09:24
  • sir it says now an error saying "wrong 1st argument type. Found: 'android.os.CountDownTimer', Required:'android.app.Activity' – LJ Ca-ong Apr 18 '18 at 09:44
  • pass context of your activity like this try this **`ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.SEND_SMS},1);`** – AskNilesh Apr 18 '18 at 09:47
  • 1
    sir it worked... – LJ Ca-ong Apr 18 '18 at 09:51
  • sir can i email you... or you can email me ... @ jayson.loveboo@gmail.com.. because i want to ask you something ..if its okay with you sir – LJ Ca-ong Apr 18 '18 at 09:52

1 Answers1

0

You can try this :-

Add it in 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);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Janvi Vyas
  • 732
  • 5
  • 16