Toast on SMS receive ANDROID STUDIO NOT WORKING - android

For the program of toast presentation on sms receive in ANDROID STUDIO,Im getting no errors...but it is not working in any of my phones(Used Samsung GT-i9082 and lenovo a6000+)..Here is my code and the manifest following respectively.. ...
package com.myapplication.siva.phoneapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity{
private BroadcastReceiver receiver;
public static final String SMS_BUNDLE = "pdus";
private static String TAG="com.myapplication.siva.phoneapp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"Inside onCreate");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
Log.i(TAG,"Inside on Receive");
try {
Toast.makeText(context, "Coming Inside",Toast.LENGTH_SHORT).show();
Log.i(TAG,"Inside try");
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();
}
}catch (Exception e)
{
Log.i(TAG,"Some Exception");
}
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapplication.siva.phoneapp" >
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<uses-permission android:name="android.permission.hardware_test"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<receiver
android:name=".MainActivity"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"> </action>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
</activity>
</application>
</manifest>

Mike M is perfectly correct your intent filter should contain action for sms, i.e., "android.provider.Telephony.SMS_RECEIVED" not something else.
Secondly you require an activity to launch am broadcast receiver from android 3.1 for security issues.

Related

google QPX on Android

I am using QP Express api to gather data on flights from one place to the other in Android. When I run the app, the request is not sent to Google. What could I be missing? I have the client authorization in the manifest as shown below. What am I not doing right?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.steve.myflights" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<meta-data
android:name="com.google.android.apps.drive.APP_ID" />/clients key
android:value="*****(my client api key)**" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Below is the MainActivity.java just in case it might be helpful
package com.example.steve.myflights;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import java.io.IOException;
import java.util.*;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.qpxExpress.QPXExpressRequestInitializer;
import com.google.api.services.qpxExpress.QPXExpress;
import com.google.api.services.qpxExpress.model.FlightInfo;
import com.google.api.services.qpxExpress.model.LegInfo;
import com.google.api.services.qpxExpress.model.PassengerCounts;
import com.google.api.services.qpxExpress.model.PricingInfo;
import com.google.api.services.qpxExpress.model.SegmentInfo;
import com.google.api.services.qpxExpress.model.SliceInfo;
import com.google.api.services.qpxExpress.model.TripOption;
import com.google.api.services.qpxExpress.model.TripOptionsRequest;
import com.google.api.services.qpxExpress.model.TripsSearchRequest;
import com.google.api.services.qpxExpress.model.SliceInput;
import com.google.api.services.qpxExpress.model.TripsSearchResponse;
public class MainActivity extends AppCompatActivity {
private EditText editTextOrigin;
private EditText editTextArrival;
private EditText editTextDestination;
private EditText editTextFlightNum;
private EditText editTextPrice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String APPLICATION_NAME = "com.example.MyFlightsApp";
final String API_KEY = "***APIKEY****";
/** Global instance of the HTTP transport. */
HttpTransport httpTransport;
/** Global instance of the JSON factory. */
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
PassengerCounts passengers= new PassengerCounts();
passengers.setAdultCount(1);
List<SliceInput> slices = new ArrayList<SliceInput>();
SliceInput slice = new SliceInput();
slice.setOrigin("NYC");
slice.setDestination("JFK");
slice.setDate("2015-11-11");
slices.add(slice);
TripOptionsRequest request= new TripOptionsRequest();
request.setSolutions(1);
request.setPassengers(passengers);
request.setSlice(slices);
TripsSearchRequest parameters = new TripsSearchRequest();
parameters.setRequest(request);
QPXExpress qpXExpress= new QPXExpress.Builder(httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME).setGoogleClientRequestInitializer(new QPXExpressRequestInitializer(API_KEY)).build();
TripsSearchResponse list= qpXExpress.trips().search(parameters).execute();
List<TripOption> tripResults=list.getTrips().getTripOption();
String id;
editTextArrival = (EditText)findViewById(R.id.ediTextArrival);
editTextOrigin = (EditText)findViewById(R.id.ediTextOrigin);
editTextDestination = (EditText)findViewById(R.id.ediTextDestination);
editTextFlightNum = (EditText)findViewById(R.id.ediTextFlightNum);
editTextPrice = (EditText)findViewById(R.id.ediTextPrice);
for(int i=0; i<tripResults.size(); i++) {
//Trip Option ID
id= tripResults.get(i).getId();
//Slice
List<SliceInfo> sliceInfo= tripResults.get(i).getSlice();
for(int j=0; j<sliceInfo.size(); j++) {
int duration= sliceInfo.get(j).getDuration();
List<SegmentInfo> segInfo= sliceInfo.get(j).getSegment();
for(int k=0; k<segInfo.size(); k++) {
FlightInfo flightInfo=segInfo.get(k).getFlight();
editTextFlightNum.setText(flightInfo.getNumber());
List<LegInfo> leg=segInfo.get(k).getLeg();
for(int l=0; l<leg.size(); l++) {
editTextArrival.setText(leg.get(1).getAircraft());
editTextDestination.setText(leg.get(1).getDestination());
editTextOrigin.setText(leg.get(1).getOrigin());
}
}
}
//Pricing
List<PricingInfo> priceInfo= tripResults.get(i).getPricing();
for(int p=0; p<priceInfo.size(); p++) {
editTextPrice.setText(priceInfo.get(p).getSaleTotal());
}
}
return;
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
// System.exit(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You should add permission to access network and know the network in your manifest file.

java.langSecurityException:Sending SMS message:uid 10057 does not have android.permission.SEND_SMS [duplicate]

This question already has an answer here:
Permission from manifest doesn't work in Android 6
(1 answer)
Closed 7 years ago.
I am trying to build a simple app to send message, but its giving error:
java.langSecurityException:Sending SMS message:uid 10057 does not
have`android.permission.SEND_SMS
even though i have added android.permission.SEND_SMS in manifest, help me solve this problem
main-activity.java
package com.example.manju.helpme;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.Edit
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
/* called when user clicks ALERT! button*/
public final static String EXTRA_MESSAGE = "com.example.HelpMe.Message";
public void sendMessage(){
String phoneNo = "5556";
String message = "hi";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failed, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
Intent intent = new Intent(this,DisplayMessageActivity.class);
String Message = e.toString();
intent.putExtra(EXTRA_MESSAGE, Message);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAlert = (Button)findViewById(R.id.btn_Alert);
Button btnAddGuardian = (Button)findViewById(R.id.btn_Add_Guardian);
Button btnRemoveGuardian = (Button)findViewById(R.id.btn_Remove_Guardian);
btnAlert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
btnAddGuardian.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnRemoveGuardian.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//no inspection Simplifiable If Statement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android Manifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.manju.helpme" >
<uses-permission android:name="android.permission.SEND_SMS"> </uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Guardians"
android:label="#string/title_activity_guardians"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.manju.helpme.MainActivity" />
</activity>
<activity
android:name=".DisplayMessageActivity"
android:label="#string/title_activity_display_message" >
</activity>
</application>
</manifest>
In my case, I changed the targeted sdk to 19 and also find that you didn't define the uses-sdk in the manifest...!
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
Try changing the uses-permission syntax like this:
<uses-permission android:name="android.permission.SEND_SMS"/>

broadCast Receiver is never called

I am trying to detect if the WiFi is connected or not by listening to the "SUPPLICANT_CONNECTION_CHANGE_ACTION" as shown below in the code. But the problem is
when i run the App i receive no notificatio from the broadCast Receiver i am registered to!!
why that is happening and how to solve it?
code:
IntentFilter intentFilter2 = new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityModule();
}
protected void ConnectivityModule() {
// TODO Auto-generated method stub
Log.d(TAG, "#interNetConnectivityModule: called");
registerReceiver(SupplicantReceiver, intentFilter2);
}
BroadcastReceiver SupplicantReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
}
}
};
Here is Example :
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// broadcast a custom intent.
public void broadcastIntent(View view)
{
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
My Broadcast Receiver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
This is how you should declare Broadcast Receiver in your Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
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" >
<Button android:id="#+id/btnStartService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/broadcast_intent"
android:onClick="broadcastIntent"/>
</LinearLayout>
Your receiver looks correctly registered (at runtime, not based on Manifest, but whatever, should be good anyway).
I'm guessing.. have you tried putting logs in onReceive method like
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "Reached this point, receiver is working");
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
Log.d(TAG, "Checking for an error in retrieving data!");
boolean myTest = intent.getBooleanExtra(EXTRA_SUPPLICANT_CONNECTED, false);
if (myTest) Log.d(TAG, "This way it worked!");
else Log.d(TAG, "This does not mean it didn't work at all! Might just be the correct value as a DISCONNECTED status");
} else Log.d(TAG, "Bizzarre error, action received was different from the one receiver was registered to! [ " + action + " ] ");
}
My guess is that you might be trying to retrieve the information in a wrong way, and with logs so strictly defined you can't see enough of what happens, but the receiver works fine

Android Sending String from another app

I am working on two app, ApplicationA and ApplicationB, ApplicationA send String to ApplicationB,and i am display the receiving string on ApplicationB Activity.now everthing is working fine,when i Click on a Button from ApplicationA and want to send a string to ApplicationB,there is popup appear and i am select the ApplicationB from this popup,i want when i click on Button from ApplicationA the popup does not appear and directly my ApplicationB open and display the recieving string,also i want to perform this task in a background services,how i can achieve this?
My ApplicationA MAinActivity:
package com.example.applicationa;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button sendstring;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendstring = (Button) findViewById(R.id.sendstring);
sendstring.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi Farhan Shah,Welcome to AppB");
sendIntent.setType("text/plain");
// startActivity(sendIntent);
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my ApplicationA Screen Shot:
When click on button the popup will appear and i am selecting ApplicationB from this popup:
This is my ApplicationB MainActivty:
package com.example.applicationb;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text_recieve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_recieve = (TextView) findViewById(R.id.text_recieve);
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
text_recieve.setText(sharedText);
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and This is my ApplicationB menifast file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicationb"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and this the ApplicationB screen shot when i am Receive the the string from ApplicationA:
Note:-
now i want to when i click on button from ApplicationA,complete process will be perform in background services,and when background services is done,then my ApplicationB activity is open with the receiving string,how i can achieve this through services,when click on button the popup will not appear to the user,please some one help me out,Thanks Alot in advance
In the intent to start your other app you have to mention its package name like:
intent.setClassName("com.farhan.appb",
"com.farhan.appb.MainActivity");
I have solved my Problem:
my MainActivity from ApplicationA:
package com.example.applicationa;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button sendstring;
EditText edit_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// startService(new Intent(MainActivity.this, MyService.class));
edit_text = (EditText) findViewById(R.id.edit_text);
sendstring = (Button) findViewById(R.id.sendstring);
sendstring.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(MainActivity.this, MyService.class));
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my Background Service class:
package com.example.applicationa;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
String et_name;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
// et_name = getIntent().getStringExtra("dealer_id");
/*
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi Farhan Shah,Welcome to AppB");
sendIntent.setType("text/plain");
// startActivity(sendIntent);
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));*/
/*player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false);*/ // Set looping
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if(intent != null){
et_name = intent.getStringExtra("et_name");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
// player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "" + et_name, Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
Intent sendIntent = new Intent();
sendIntent.setClassName("com.example.applicationb",
"com.example.applicationb.MainActivity");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi Farhan Shah,Welcome to AppB");
sendIntent.setType("text/plain");
startActivity(sendIntent);
// player.start();
}
}

Search activity won't launch?

I have implemented a search system in my app, and the search bar appears, but when enter is pressed the search activity doesn't load.
As well as this, the text typed into the search box is black. The action bar is also black, so is there a way to make it white on API 14+?
My MainActivity:
package com.liamwli.spotify.spotifycommunity;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.Toast;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
ProgressBar progress;
WebView wv;
WebSettings wvs;
String url, prefix;
SharedPreferences prefs;
SharedPreferences.Editor editor;
ActionBar ab;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
ab = getActionBar();
ab.setHomeButtonEnabled(true);
progress = (ProgressBar) findViewById(R.id.pBProgress);
wv = (WebView) findViewById(R.id.wVPage);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if (!url.contains("community.spotify.com")
&& !url.contains("facebook.com")
&& !url.contains("spotify.com")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
i.addCategory(Intent.CATEGORY_BROWSABLE);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else {
view.loadUrl(url);
}
return super.shouldOverrideUrlLoading(view, url);
}
});
wv.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
// TODO Auto-generated method stub
if (newProgress < 100
&& progress.getVisibility() == ProgressBar.GONE) {
progress.setVisibility(ProgressBar.VISIBLE);
}
progress.setProgress(newProgress);
if (newProgress == 100) {
progress.setVisibility(ProgressBar.GONE);
}
super.onProgressChanged(view, newProgress);
}
});
wvs = wv.getSettings();
if (prefs.getBoolean("javascript_enabled", true)) {
wvs.setJavaScriptEnabled(true);
wvs.setJavaScriptCanOpenWindowsAutomatically(true);
}
if (Build.VERSION.SDK_INT >= 11)
wvs.setDisplayZoomControls(true);
wvs.setSupportZoom(true);
wvs.setSupportMultipleWindows(true);
if (prefs.getBoolean("desktop_mode", false)) {
prefix = "/?device-view=desktop";
} else {
prefix = "/?device-view=mobile";
}
url = "http://community.spotify.com" + prefix;
Intent liam = getIntent();
if (liam.getAction() == Intent.ACTION_VIEW) {
Uri data = liam.getData();
URL urlurl = null;
try {
urlurl = new URL(data.getScheme(), data.getHost(),
data.getPath());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("Malformed URL Given");
}
url = urlurl.toString() + prefix;
}
if (url == null)
throw new RuntimeException("URL Null");
wv.loadUrl(url);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.activity_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the
// widget;
// expand it by default
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_back:
if (wv.canGoBack()) {
wv.goBack();
} else {
Toast.makeText(this, "Can't Go Back!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_forward:
if (wv.canGoForward()) {
wv.goForward();
} else {
Toast.makeText(this, "Can't Go Forward!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_refresh:
wv.reload();
break;
case R.id.menu_settings:
Intent i = new Intent(this, PrefActivity.class);
startActivity(i);
break;
case R.id.menu_search:
onSearchRequested();
break;
case android.R.id.home:
wv.loadUrl("http://community.spotify.com" + prefix);
break;
}
return super.onOptionsItemSelected(item);
}
}
My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.liamwli.spotify.spotifycommunity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.liamwli.spotify.spotifycommunity.StartActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.MainActivity"
android:excludeFromRecents="true"
android:exported="true"
android:label="#string/app_name"
tools:ignore="ExportedActivity" >
<intent-filter>
<action android:name="com.liamwli.spotify.spotifycommunity.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.PostUrl"
android:excludeFromRecents="true"
android:exported="false"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.liamwli.spotify.spotifycommunity.POSTURL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.PrefActivity"
android:exported="false"
android:label="#string/app_name" >
<intent-filer>
<action android:name="com.liamwli.spotify.spotifycommunity.PREFACTIVITY" />
<category android:name="android.intent.cetagory.PREFERENCE" />
</intent-filer>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.ClearData"
android:excludeFromRecents="true"
android:exported="false"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.liamwli.spotify.spotifycommunity.CLEARDATA" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.SearchActivity"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<provider
android:name="com.liamwli.spotify.spotifycommunity.MySuggestionProvider"
android:authorities="com.liamwli.spotify.spotifycommunity.MySuggestionProvider"
android:exported="true" />
</application>
</manifest>
My SearchActivity:
package com.liamwli.spotify.spotifycommunity;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.SearchRecentSuggestions;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Toast;
public class SearchActivity extends Activity {
WebView wv;
SharedPreferences prefs;
SharedPreferences.Editor editor;
String prefix;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
wv = (WebView) findViewById(R.id.wVPage);
if (prefs.getBoolean("desktop_site", false)) {
prefix = "/?device-view=desktop";
} else {
prefix = "/?device-view=mobile";
}
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
this, MySuggestionProvider.AUTHORITY,
MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
doMySearch(query);
}
}
private void doMySearch(String query) {
// TODO Auto-generated method stub
wv.loadUrl("http://community.spotify.com/t5/forums/searchpage/tab/message?q="
+ query + prefix);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.activity_main_nosearch, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_back:
if (wv.canGoBack()) {
wv.goBack();
} else {
Toast.makeText(this, "Can't Go Back!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_forward:
if (wv.canGoForward()) {
wv.goForward();
} else {
Toast.makeText(this, "Can't Go Forward!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_refresh:
wv.reload();
break;
case R.id.menu_settings:
Intent i = new Intent(this, PrefActivity.class);
startActivity(i);
break;
case android.R.id.home:
wv.loadUrl("http://community.spotify.com" + prefix);
break;
}
return super.onOptionsItemSelected(item);
}
}
I don't receive a force close - it just doesn't launch the search activity.
Also, what permission should I set for the final provider? The android system must be able to execute it,

Categories

Resources