2

I am new to android. I am creating a android service which retrieves the current location and send it as a message to a particular number. I have almost achieved it, but when I use SMSManager to send message of the retrieved location value the app crashes(I have commented the code in the attachment). I have achieved up-to the step of retrieving the current location and display it on EditText. I have included all the permissions.Kindly help me to fix the issue of sending message of the received intent value. I have included the code of MainActivity and BroadcastService

int count=1;

@Override
protected void onResume() {
    super.onResume();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                textView.setText("\n" +intent.getExtras().get("coordinates"));

               String loc = textView.getText().toString();

                    /*
                    SmsManager sms = SmsManager.getDefault();
                    sms.sendTextMessage("7448958358", null, loc, null, null);
                    */

            }
        };
    }
    registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(broadcastReceiver != null){
        unregisterReceiver(broadcastReceiver);
    }
}
private void sendSMS(String phoneNumber, String message) {
    Toast.makeText(this, "sending", Toast.LENGTH_SHORT).show();
    }
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn_start = (Button) findViewById(R.id.button);
    btn_stop = (Button) findViewById(R.id.button2);
    textView = (TextView) findViewById(R.id.textView);
    if(!runtime_permissions())
    {
        enable_buttons();
    }
}

private void enable_buttons() {

    btn_start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i =new Intent(getApplicationContext(),BroadcastService.class);
            startService(i);
        }
    });

    btn_stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i =new Intent(getApplicationContext(),BroadcastService.class);
            stopService(i);
        }
    });

}

private boolean runtime_permissions() {
    if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){

        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.SEND_SMS,Manifest.permission.RECEIVE_SMS},100);

        return true;
    }
    return false;
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 100){
        if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
            enable_buttons();
        }else {
            runtime_permissions();
        }
    }
}

BroadcastService.java

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@SuppressLint("MissingPermission")
@Override
public void onCreate() {
    Toast.makeText(this, "Services has been started", Toast.LENGTH_SHORT).show();
    listener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            Intent i = new Intent("location_update");
            i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
            sendBroadcast(i);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    };

    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    //noinspection MissingPermission
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);

}

@Override
public void onDestroy() {
    super.onDestroy();
    if(locationManager != null){
        //noinspection MissingPermission
        locationManager.removeUpdates(listener);
    }
}

My crash log says

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.prakaash.broadcastservice, PID: 27810
              java.lang.RuntimeException: Error receiving broadcast Intent { act=location_update flg=0x10 (has extras) } in com.example.prakaash.broadcastservice.MainActivity$1@9f66542
                  at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_51117(LoadedApk.java:1300)
                  at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.$m$0(Unknown Source:4)
                  at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.run(Unknown Source:0)
                  at android.os.Handler.handleCallback(Handler.java:789)
                  at android.os.Handler.dispatchMessage(Handler.java:98)
                  at android.os.Looper.loop(Looper.java:172)
                  at android.app.ActivityThread.main(ActivityThread.java:6637)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
               Caused by: java.lang.SecurityException: Neither user 10119 nor current process has android.permission.READ_PHONE_STATE.
                  at android.os.Parcel.readException(Parcel.java:1942)
                  at android.os.Parcel.readException(Parcel.java:1888)
                  at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:867)
                  at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:330)
                  at android.telephony.SmsManager.sendTextMessage(SmsManager.java:313)
                  at com.example.prakaash.broadcastservice.MainActivity$1.onReceive(MainActivity.java:42)
                  at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_51117(LoadedApk.java:1290)
                  at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.$m$0(Unknown Source:4) 
                  at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.run(Unknown Source:0) 
                  at android.os.Handler.handleCallback(Handler.java:789) 
                  at android.os.Handler.dispatchMessage(Handler.java:98) 
                  at android.os.Looper.loop(Looper.java:172) 
                  at android.app.ActivityThread.main(ActivityThread.java:6637) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

Application terminated.

Prakaash M
  • 37
  • 8
  • Can you update your question with crash log? – Sagar May 19 '18 at 14:51
  • I have updated it.This is working perfectly in emulator but crashes only on mobile. On seeing logcat,only thing I understand is,"It is asking to include PHONE_STATE permission". Is it required for getting current location and sending it as a message? – Prakaash M May 20 '18 at 07:39

1 Answers1

0

This issue doesn't happen for all the manufacturers. The official document doesnt specify the need for requesting this permission. Some manufacturers have issues in implementation of sendTextMessage due to which READ_PHONE_STATE permission is required.

To fix the issue only workaround is to add this permission to your Manifest and requestPermissions.

Sagar
  • 23,903
  • 4
  • 62
  • 62