How can this effect be achieved? Imagine that I have an application icon on the android desktop, and when a message arrives, I get a shortcut with this message from this icon. From you I need to know how to implement such a thing, such as a widget or a shortcut? 
|
1 answer
You can do this (I have a rather primitive example here, so change the design to your taste, for example, you can replace Toast with something like that :) ).
Create a custom layout to display the message:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/custom_toast_container" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="8dp" android:background="#DAAA" > <ImageView android:src="@mipmap/ic_cat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="8dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFF" /> </LinearLayout> Create a service to receive a message:
public class ToastService extends IntentService { Handler mHandler; public ToastService() { super("ToastService"); mHandler = new Handler(); } @Override protected void onHandleIntent(Intent intent) { String message = intent.getStringExtra("task"); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.post(new DisplayToast(this, message)); } } Add it to the manifest:
<application> ... <service android:name=".ToastService" android:exported="false"/> </application> And create a stream to display the message:
public class DisplayToast implements Runnable { private final Context mContext; String mText; public DisplayToast(Context mContext, String text){ this.mContext = mContext; mText = text; } public void run(){ LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_toast, null); View container = layout.findViewById( R.id.custom_toast_container); TextView text = (TextView) container.findViewById(R.id.text); text.setText("Вы получили новое сообщение: " + mText); Toast toast = new Toast(mContext); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } } And accordingly, to test the work you can create an intention in the same application in any activity:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Запускаем свой IntentService Intent intentMyIntentService = new Intent(this, ToastService.class); startService(intentMyIntentService.putExtra("task", "не забудь покормить кота!")); } After starting, you can minimize the application and get the message on the main screen:
|
