Может кто поможет. Дело в ограничениях запущенных с Android Oreo (API 26). Пытаюсь добиться следующего: при свернутой активности отслеживать изменения системного буфера обмена (например копирование адреса страницы), а далее с помощью моего приложения уже обрабатывать данный текст взятый из буфера (например вывести в toast на экран). Если компилирую код на старые API до 26, то всё работает, а вот на свежих версиях приложение вылетает в ошибку. Ниже мой код.
// This my MainActivity.java
package com.example.service;
import static android.app.PendingIntent.getActivity;
import static java.security.AccessController.getContext;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private boolean mPopupShowing = false;
private Runnable mPopupRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onBtnClickNEW(View view) {
/* startService(new Intent(this, ClipboardService.class)
.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));*/
if (Build.VERSION.SDK_INT >= 26) {
System.out.println("SDK_INT >= 26 " ); // 05
startForegroundService(new Intent(this, ClipboardService.class));
}
else {
System.out.println("SDK_INT < 26 " ); // 05
startService(new Intent(this, ClipboardService.class));
}
}
public void onBtnClickSTOP(View view) {
stopService(new Intent(this, ClipboardService.class));
}
public void onBtnClickALERT(View view) {
Toast toast = Toast.makeText(getApplicationContext(),"Check clipboard!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, toast.getXOffset() / 2, toast.getYOffset() / 2);
TextView textView = new TextView(getApplicationContext());
textView.setBackgroundColor(Color.DKGRAY);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
Typeface typeface = Typeface.create("serif", Typeface.BOLD);
textView.setTypeface(typeface);
textView.setPadding(10, 10, 10, 10);
textView.setText("Check clipboard!");
toast.setView(textView);
toast.show();
}
}
// This my service "ClipboardService"
package com.example.service;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.IBinder;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class ClipboardService extends Service {
private Handler mPopupHandler;
private Runnable mPopupRunnable;
private final ClipboardManager.OnPrimaryClipChangedListener mClipboardListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
ClipboardManager clipboardManager = null;
clipboardManager = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
ClipData clipData = clipboardManager.getPrimaryClip();
ClipData.Item item = clipData.getItemAt(0);
CharSequence text = item.getText();
showPopup(text.toString());
}
};
@Override
public void onCreate() {
super.onCreate();
mPopupHandler = new Handler();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// регистрация слушателя буфера обмена
System.out.println("onStartCommand");
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.addPrimaryClipChangedListener(mClipboardListener);
return START_STICKY;
}
private void showPopup(String text) {
Toast toast = Toast.makeText(getApplicationContext(),text, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, toast.getXOffset() / 2, toast.getYOffset() / 2);
TextView textView = new TextView(getApplicationContext());
textView.setBackgroundColor(Color.DKGRAY);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
Typeface typeface = Typeface.create("serif", Typeface.BOLD);
textView.setTypeface(typeface);
textView.setPadding(10, 10, 10, 10);
textView.setText(text);
toast.setView(textView);
toast.show();
System.out.println(text);
}
@Override
public void onDestroy() {
ClipboardManager clipboardManager=(ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.removePrimaryClipChangedListener(mClipboardListener);
if(mPopupHandler != null && mPopupRunnable != null) {
mPopupHandler.removeCallbacks(mPopupRunnable);
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
// This my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"\>
<TextView
android:id="@+id/textView"
android:layout_width="243dp"
android:layout_height="51dp"
android:text="Hello World!"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.526"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.068" />
<Button
android:id="@+id/button"
android:layout_width="184dp"
android:layout_height="134dp"
android:layout_marginStart="112dp"
android:layout_marginTop="28dp"
android:onClick="onBtnClickNEW"
android:text="Start"
android:textColor="#215915"
android:textSize="34sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button
android:id="@+id/button2"
android:layout_width="186dp"
android:layout_height="122dp"
android:layout_marginStart="112dp"
android:layout_marginTop="12dp"
android:onClick="onBtnClickSTOP"
android:text="Stop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<EditText
android:id="@+id/editTextTextMultiLine"
android:layout_width="258dp"
android:layout_height="100dp"
android:layout_marginStart="76dp"
android:layout_marginTop="28dp"
android:background="#D1EDAA"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button2"
tools:text="1234" />
<Button
android:id="@+id/button3"
android:layout_width="121dp"
android:layout_height="77dp"
android:layout_marginStart="144dp"
android:layout_marginTop="28dp"
android:text="Alert"
android:onClick="onBtnClickALERT"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextMultiLine" />
</androidx.constraintlayout.widget.ConstraintLayout>
javaclipboardtoastandroid-8.0-oreoforeground-service
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Service"
tools:targetApi="31">
<service
android:name=".ClipboardService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>