I want to perform tasks in the background in my app without open ui. You have to bring text from any other app into your app through shareTo method.
here is my code in AndroidManifest.xml
.
.
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
.
.
.
<receiver
android:name=".TextShareReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</receiver>
<service
android:name=".TextService"
android:enabled="true"
android:exported="false" />
BroadcastReceiver Code--
public class TextShareReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Intent.ACTION_SEND.equals(intent.getAction())) {
String type = intent.getType();
if ("text/plain".equals(type)) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Process the received text/plain data here
Log.d("ShareReceiver", "Received shared text/plain data: " + sharedText);
Intent serviceIntent = new Intent(context, TextService.class);
serviceIntent.putExtra("text_data", sharedText);
context.startService(serviceIntent);
}
}
}
}
}
Service Code--
public class TextService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String textData = intent.getStringExtra("text_data");
if (textData != null) {
// Process the received text/plain data here
Log.d("YourService", "Received text/plain data: " + textData);
// I want to save this text in the database through service.
}
}
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
With this code I am not able to show the icon of my app in the shareTo option.
When I do it in the intent filter activity, the app icon shows up.
<activity
android:name=".ReceiverActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
I want to perform a task without opening the activity.