Я новичок в Android.Я создаю службу Android, которая получает текущее местоположение и отправляет его в виде сообщения на определенный номер.Я почти достиг этого, но когда я использую SMSManager для отправки сообщения с найденным значением местоположения, приложение вылетает (я прокомментировал код во вложении).Я достиг вплоть до шага получения текущего местоположения и отображения его на EditText.Я включил все разрешения. Пожалуйста, помогите мне решить проблему отправки сообщения с полученным значением намерения.Я включил код MainActivity и 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);
}
}
В моем журнале сбоев указано
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)
Приложениепрекращено.