How to activate "Share" button in android app? - java

i want to add "Share" button to my android app.
Like that
I added "Share" button, but button is not active. I click, but nothing happens.
My code in MainActivity.java:
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share_menu, menu);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.share_menu);
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share_menu).getActionProvider();
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return true;
}
{
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
I want to share text in my first tab (first_tab.xml) or second tab (second_tab.xml).
Code in tab (xml) (If need):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_color"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >
<TextView
android:id="#+id/section_label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/text"
android:textColor="#color/text_color" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="#drawable/sprite" />

Add a Button and on click of the Button add this code:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
Useful links:
For basic sharing
For customization

Create a button with an id share and add the following code snippet.
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Your body here";
String shareSub = "Your subject here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
});
The above code snippet will open the share chooser on share button click action.
However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

in kotlin :
val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener :
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}

Kotlin
Inside the click listener needed to add this module for sharing text via applications like whatsApp, email, Slack..
shareOptionClicked.setOnClickListener{
val shareData = Intent(Intent.ACTION_SEND)
shareData.type = "text/plain"
val dataToShare = "Text from my application"
shareData.putExtra(Intent.EXTRA_SUBJECT, "Subject from my application")
shareData.putExtra(Intent.EXTRA_TEXT, dataToShare)
startActivity(Intent.createChooser(shareData, "Share Via"))
}

Related

How to use ACTION_SET_TIMER intent on android studio

I'm trying to set a timer on the phone (not in the app I created) using ACTION_SET_TIMER intent and I'm not sure why it's not working when I click the button it either restarts the app or crashes it. Thanks for the help!
<Button
android:id="#+id/timer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:onClick="startTimer"
android:text="#string/timer_note"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/camera_button"
/>
public void startTimer(View view) {
String searchFor = ((EditText) findViewById(R.id.share_edittext)).getText().toString();
String strNew = searchFor.replaceFirst("You ordered a ", "");
int seconds = 10;
Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
.putExtra(AlarmClock.EXTRA_MESSAGE, strNew)
.putExtra(AlarmClock.EXTRA_LENGTH, seconds)
.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
else {
Log.d("ImplicitIntents", "Can't handle this intent!");
}
}
After further digging I realized I needed to add a permission to the Manifest.XML file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.homework">
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />

Android O Pinned Shortcuts - CREATE_SHORTCUT intent filter

In the documentation for the new "Pinned Shortcuts" feature in Android O, they mention that "You can also create a specialized activity that helps users create shortcuts, complete with custom options and a confirmation button".
I tried following the documentation, but when I tried to create a new shortcut I only saw the default dialog, and not my activity.
Here's the declaration in the Manifest:
<activity android:name=".ShortcutActivity">
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT"/>
</intent-filter>
</activity>
P.S
In the documentation they also shows an example in the Gmail app - how do I get to that screen? I wanted to see the flow but I couldn't find it.
You have to create a new activity as dialog, then you can add whatever options you want on that dialog and handle as you want the addShortcut method.
I tried that code to add and remove a dynamical shortcut and it worked.
AndroidManifest.xml
<activity android:name=".DialogActivity"
android:excludeFromRecents="true"
android:theme="#style/Theme.AppCompat.Dialog"
>
...
</activity>
DialogActivity.java
public class DialogActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
this.setFinishOnTouchOutside(false);
findViewById(R.id.add_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addShortcut();
}
});
findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
...
}
activity_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_dialog"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.metax.myapplication.DialogActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you want to add shortcut?"/>
<Button
android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_alignParentStart="true"
android:text="No thanks"/>
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_alignParentEnd="true"
android:text="Add me"/>
</RelativeLayout>
In you Java class insert
ShortcutManager sM = c.getSystemService(ShortcutManager.class);
Intent intent2 = new Intent(c.getApplicationContext(), ShortcutActivity.class);
intent2.setAction(Intent.ACTION_VIEW);
ShortcutInfo shortcut2 = new ShortcutInfo.Builder(c,MSG_SHORCUT_CUSTOM)
.setIntent(intent2)
.setShortLabel("ShortLabel")
.setLongLabel("LongLaber")
.setDisabledMessage("DisabledMessage")
.setIcon(Icon.createWithResource(c, R.mipmap.ic_add_outline_short))
.build();
listshortcut.add(shortcut2);
Intent pinnedShortcutCallbackIntent = mShortcutManager.createShortcutResultIntent(shortcut2);
PendingIntent successCallback = PendingIntent.getBroadcast(context, 0, pinnedShortcutCallbackIntent, 0);
mShortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.getIntentSender());
sM.setDynamicShortcuts(listshortcut);
To launch your shortcut activity with action as ACTION_CREATE_SHORTCUT, long tap on app icon, and press widget icon, you ll notice a 1x1 widget, on tap of which your desired activity would be launched.
Also you can explicitly fire that intent from your app as well on some desired action.
Create a new resource file: res/xml/shortcuts.xml. This is how you create shortcuts,After you have done the nessicary changes in manifest
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="compose"
android:enabled="true"
android:icon="#drawable/compose_icon"
android:shortcutShortLabel="#string/compose_shortcut_short_label1"
android:shortcutLongLabel="#string/compose_shortcut_long_label1"
android:shortcutDisabledMessage="#string/compose_disabled_message1">
<intent
android:action="android.intent.action.VIEW"
android:targetPackage="your package"
android:targetClass="com.example.myapplication.ComposeActivity" />
</shortcut>
<!-- Specify more shortcuts here. -->
</shortcuts>
In manifest add this to the activity tag,
<meta-data android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
If you want to read more refer this doc it explains about pinned shortcuts, static and dynamic shortcuts.
Here is an example from google, in their samples repo

How to make clickable widget [Android]

I've created a widget, and on click an Activity has to be launched, I followed the answer to this question [Clickable widgets in android].
However, on click I am unable to get any response, here is the java code to my widget:
Widget.java
public class Widget extends AppWidgetProvider
{
private static String YOUR_AWESOME_ACTION = "YourAwesomeAction";
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
Intent intent = new Intent(context, HomeTeamSelector.class);
intent.setAction(YOUR_AWESOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.widgetLayout, pendingIntent);
}
#Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if (intent.getAction().equals(YOUR_AWESOME_ACTION))
{
Intent x = new Intent(context,HomeTeamSelector.class);
context.startActivity(x);
}
}
}
This is the code to the xml file:
widget.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/widgetLayout"
android:layout_height="match_parent"
android:transitionGroup="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name_extra"
android:id="#+id/textView"
android:layout_centerInParent="true"
android:textColor="#color/colorPrimary"
android:textSize="30sp" />
</RelativeLayout>
The widget is rendered, however I am unable to get any response on click, what is possibly causing this, and how to fix?
try to add AppWidgetProvider receiver in AndroidMenifest.xml like
<receiver
android:name=".Widget"
android:label="#string/widget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget" />
</receiver>

Android - Widget Disappears immediately when placed

I'm trying to add a widget into my app and I am facing a problem. Whenever I grab the widget and place it on my homescreen, it just disappears. I can only see it for about 0.5 seconds. Here is the code:
Manifest.xml
<receiver
android:label="MyApp"
android:name=".widget.MyWidgetProvider" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
MyWidgetProvider.java
public class MyWidgetProvider extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//IDs
for (int i=0; i<appWidgetIds.length; i++) {
int currentWidgetId = appWidgetIds[i];
// Create data
SharedPreferences prefs = context.getSharedPreferences("com.example.app_preferences", 0);
int number = prefs.getInt("progress", 0);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.appwidget);
Log.w("WidgetExample", String.valueOf(number));
// Set the text
remoteViews.setTextViewText(R.id.widgettext, String.valueOf(number));
// Register an onClickListener
Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.widgettext, pendingIntent);
appWidgetManager.updateAppWidget(currentWidgetId, remoteViews);
Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).show();
}
}
}
appwidget.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widgetlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/widgetimage" >
<TextView
android:id="#+id/widgettext"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
widget_info.xml
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:updatePeriodMillis="86400000"
android:minWidth="120dp"
android:minHeight="50dp"
android:initialLayout="#layout/appwidget"
android:previewImage="#drawable/widgetimage"
android:configure="com.example.app.widget.MyWidgetProvider" >
</appwidget-provider>
you can see the last line of the java file contains a toast. This toast actually gets called and there are no errors whatsoever in the logcat.
Thanks!
You're android:configure element must refer to an activity that will allow configuration of your widget. This activity must set result to RESULT_OK, otherwise configuration is cancelled and widget is removed.
I suppose referring to your widget provider, not an activity, has the same effect of returning RESULT_CANCEL from the configuration activity.
If you don't have a configuration activity, simply remove this entry and the widget will be added without trying to open such.
Another possibility other than 3c71's answer is that you might have forgotten to use the two-parameter version of setResult(int resultCode, Intent data). The data parameter has to include an EXTRA which identifies the widget ID.
Intent intent = new Intent();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, intent);
sendBroadcast(intent);
The widget ID is provided to the configuration activity as an EXTRA in the Intent that is supplied to the activity when it is called. Retrieve it and store it like this:
mAppWidgetId = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

Send message using content of a editText

I'm trying to send a message from my app using as SMS content the content of a editText. I tryed in this way so far:
Uri uri = Uri.parse("smsto:0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
String content = edit.getText().toString();
it.putExtra("sms_body", content);
startActivity(it);
but when the activity starts there is no content in the message.. isn't possible do something like that?
Try to send message like this
String phoneNo = "080000123";
String sms = textsms.getText().toString();
try
{
android.telephony.SmsManager smsmanager = android.telephony.SmsManager.getDefault();
smsmanager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
I tried using the same code of yours, but within a method call. This is because if you have more than 1 messaging app installed on your device you will have to manually select the app that you are going to send your message with.
In my case I have whatsapp, messaging, etc. So having your code in the onCreate(), it will only fail as there is no option selected by the user...But when I have this code within a method body and I trigger with a button or any other even similarly, it works fine(only thing is you will have to select the app-you can make any of the app as default so that the next time you don't have to do this manually).
My MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send(View v)
{
Uri uri = Uri.parse("smsto:9999999999");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
EditText edit = (EditText) findViewById(R.id.editText1);
String content = edit.getText().toString();
it.putExtra("sms_body", content);
startActivity(it);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
My activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="send" />
</LinearLayout>

Categories