I'm trying to build a simple daily reminder app as my first Android
project and I'm just stucked now. Too much information from hours
watching tutorials. :)
So I would like some help to understand the code behind
my idea so hopefully someone explains this with ease :)
Three times a day I want an alarm/reminder/splash to set off for ten seconds
with different pictures and sounds depending on the alarmtime.
An ability to tap/swipe to stop it before 10 seconds.
alarm1
---alarm1time08:10
---alarm1pic1.jpg
---alarm1Sound1.mp3
alarm2
---alarm2time12:30
---alarm2pic1.jpg
---alarm2Sound1.mp3
alarm3
---alarm3time18:45
---alarm3pic1.jpg
---alarm3Sound1.mp3
So how do I do this?
I'm using Android Studio 2.3 (to slow computer for 3.x...),
Java and my phones are Lollipop 5.1 API level 22 and
Marshmallow 6.0 API level 23
This is my code that actually works without error..
But now i don't know how open an activity with my image and sounds.
I got a RED startActivity when I tried it in hRec.
MainActivity.java
package com.hlm.myreminder;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int hHour1 = 08;
int hMin1 = 10;
Calendar hCal1 = Calendar.getInstance();
hCal1.set(Calendar.HOUR_OF_DAY, hHour1);
hCal1.set(Calendar.MINUTE, hMin1);
hCal1.set(Calendar.SECOND, 0);
Log.v("hLogging","cal set");
Intent hIntent = new Intent(getApplication(),hRec.class);
PendingIntent hPi = PendingIntent.getBroadcast(getApplicationContext(),0,hIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Log.v("hLogging","intent set");
AlarmManager hAlMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
hAlMgr.setRepeating(AlarmManager.RTC_WAKEUP,hCal1.getTimeInMillis(),hAlMgr.INTERVAL_DAY,hPi);
Log.v("hLogging","am set");
// startActivity(new Intent(this, hshowreminderpic1.class)); //works
// Log.v("hLogging","goto hshowreminderpic1 done"); //works
}
}
hRec.java
package com.hlm.myreminder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class hRec extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent hIntent) {
Log.d("hLogging", "hRec:BroadcastReceiverAlarm");
// show hshowreminderpic1
/* startActivity gets RED */
// startActivity(new Intent(this, hshowreminderpic1.class));
// Log.v("hLogging","goto hshowreminderpic1 request");
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hlm.myreminder">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#drawable/h_icon72"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".hshowreminderpic1"/>
<receiver android:name=".hRec"></receiver>
</application>
</manifest>
You need to pass context to start your activity from hRec.java as hRec is not an activity.
So simply write
Intent i = new Intent(context, hshowreminderpic1.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Try using this:
context.startActivity(new Intent(this, hshowreminderpic1.class));
Related
I've used AlarmManager ,so it works every minute
every minute, service class is called
and it keeps working even after it's turned off
it's got a sound in the back of the device
the idea works when i run the app inside Android Studio on device 5.1.1
but i noticed when i disconnected the device from the cable.
alerts are irregular and audio works
other times.
//
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(getApplicationContext(), RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
1 * 60 * 100 , pendingIntent);
}
}
// ---
public class RingAlarm extends Service {
MediaPlayer sound2;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "الحمد لله", Toast.LENGTH_LONG).show();
sound2 = (MediaPlayer) MediaPlayer.create(RingAlarm.this,R.raw.a2);
sound2.start();
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0){
// TODO Auto-generated method stub
return null;
}
}
//
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ahmedco.testcode">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".RingAlarm" />
</application>
</manifest>
I have created a map activity. The application is running without crash but when I open the activity it shows only google logo but google map is not loaded. Therefore I checked runtime errors it shows following errors.
Error
V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = ViewRoot{615057f com.example.kularathna.gpstracker/com.example.kularathna.gpstracker.ticketBooking,ident = 4}, this = DecorView#dce7bbe[ticketBooking]
E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: AIzaSyBWfu7WllVlnzgXuNAWhU_Ca0U3EC2BDvc
Android Application (;): 6B:C7:FB:B3:C6:FE:D3:22:DA:14:AE:27:B6:88:FA:13:ED:82:63:BA;com.example.kularathna.gpstracker
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
Selected remote version of com.google.android.gms.googlecertificates, version >= 4
W/zygote64: Skipping duplicate class check due to unrecognized classloader
D/Surface: Surface::disconnect(this=0x7efc6d4000,api=1)
D/WindowClient: Remove from mViews: android.widget.LinearLayout{e39f9c9 V.E...... ......ID 0,0-162,75}, this = android.view.WindowManagerGlobal#7707265
Application terminated.
Following errors are showing blue color
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
W/zygote64: Skipping duplicate class check due to unrecognized classloader
Following errors are showing Brown color
E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: AIzaSyBWfu7WllVlnzgXuNAWhU_Ca0U3EC2BDvc
Android Application (;): 6B:C7:FB:B3:C6:FE:D3:22:DA:14:AE:27:B6:88:FA:13:ED:82:63:BA;com.example.kularathna.gpstracker
Xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".map">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
android:id="#+id/fragmentMap"/>
</LinearLayout>
</RelativeLayout>
map.java file
package com.example.kularathna.gpstracker;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class map extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
if (googleServicesAvailable()){
Toast.makeText(this,"Perfect",Toast.LENGTH_LONG).show();
initMap();
}else {
// No Google Map Layout
}
}
private void initMap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fragmentMap);
mapFragment.getMapAsync(this);
}
public boolean googleServicesAvailable(){
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS){
return true;
}else if (api.isUserResolvableError(isAvailable)){
Dialog dialog = api.getErrorDialog(this,isAvailable,0);
dialog.show();
}else {
Toast.makeText(this,"Can't connect to play services",Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
goToLocationZoom(39.008224,-76.8984527,15);
}
private void goToLocation(double longitude, double latitude) {
LatLng latLng = new LatLng (longitude,latitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng (latLng);
mGoogleMap.moveCamera (cameraUpdate);
}
private void goToLocationZoom(double longitude, double latitude, float zoom) {
LatLng latLng = new LatLng (longitude,latitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
mGoogleMap.moveCamera (cameraUpdate);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kularathna.gpstracker">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<permission android:name="com.example.kularathna.gpstracker.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission android:name="com.example.kularathna.gpstracker.permission.MAPS_RECEIVE"/>
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ticketBooking" />
<activity android:name=".registration" />
<activity android:name=".arrive" />
<activity android:name=".home" />
<activity android:name=".reserveSeats" />
<activity android:name=".seatSelection" />
<activity android:name=".map"></activity>
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyBWfu7WllVlnzgXuNAWhU_Ca0U3EC2BDvc"/>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version"/>
</application>
</manifest>
API Key screen shot
API key screen shot
Is the SHA key registered with the api key in the google console is same as your machine's SHA key from where you generating the APK. Try to remove the restriction of SHA key from console and run the app
Same issue happened for me, i resolved by enabling
Maps SDK for Android
Enabled API like below image,
Also make sure generate API key for your application with package name like below image,
I'm trying to implement Google Map in android using Google API, but I am getting the error
The method getFragmentManager() is undefined for the type Posisi
Here my Posisi.java :
package com.ngohung.view;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class Posisi extends Activity {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.posisi);
<<<< HERE THE PROBLEM getFragmentManager >>>>
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
}
Here my posisi.xml file :
<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"
tools:context=".Posisi" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>
I have no idea how to solve this problem...
I'm getting the following error in Android Studio logcat:
I/chromium﹕ [INFO:CONSOLE(1)] "Uncaught ReferenceError: callJS is not defined"
I have researched on stackoverflow and tried the suggested answers on similar post with no luck. here
I'm trying to execute javascript from a local html file that is loaded into a WebChromeClient by clicking on a android button. The code is taken from the Chapter 10 example in The Pragmatic Programmers "Hello Android Introducing Google's Mobile development Platform" fourth Edition book.
index.html
<html>
<head>
<script language="JavaScript">
function callJS(arg){
document.getElementById('replaceMe').innerHTML = arg;
{
</script>
</head>
<body>
<h2>WebView</h2>
<p>
Display JavaScript alert
</p>
<p>
Call Android from JavaScript
</p>
<p id="replaceMe"></p>
</body>
</html>
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "LocalBrowser";
private final Handler handler = new Handler();
private WebView webView;
private TextView textView;
private Button button;
/** Object exposed to JavaScript */
private class AndroidBridge {
#JavascriptInterface // Required in Android 4.2+
public void callAndroid(final String arg) { // must be final
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "callAndroid(" + arg + ")");
textView.setText(arg);
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the Android controls on the screen
webView = (WebView) findViewById(R.id.web_view);
textView = (TextView) findViewById(R.id.text_view);
button = (Button) findViewById(R.id.button);
// Rest of onCreate follows...
// Turn on JavaScript in the embedded browser
webView.getSettings().setJavaScriptEnabled(true);
// Expose a Java object to JavaScript in the browser
webView.addJavascriptInterface(new AndroidBridge(),
"android");
// Set up a function to be called when JavaScript tries
// to open an alert window
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(final WebView view,
final String url, final String message,
JsResult result) {
Log.d(TAG, "onJsAlert(" + view + ", " + url + ", "
+ message + ", " + result + ")");
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
result.confirm();
return true; // I handled it
}
});
// Load the web page from a local asset
webView.loadUrl("file:///android_asset/index.html");
// This function will be called when the user presses the
// button on the Android side
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.d(TAG, "onClick(" + view + ")");
if (android.os.Build.VERSION.SDK_INT < 19) {
webView.loadUrl("javascript:callJS('Hello from Android')");
}else{
webView.evaluateJavascript("javascript:callJS('Hello from Android')", null);
}
}
});
}
}
activity_main
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/web_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1.0"
android:padding="5sp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="#string/textView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:text="#string/call_javascript_from_android"
android:textSize="18sp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/text_view"
android:textSize="18sp"/>
</LinearLayout>
</LinearLayout>
Any help is greatly appreciated! Thanks in advance!
I want my program to be able to receive sms from a special number("+9856874236").
I want application to be recive SMS ,if the SMS is contain "enable wifi" ,then change wifi to enable
i 'm using this code but it working crash??
MainActivity
package com.example.sms;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
static TextView messageBox;
static String x="";
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageBox=(TextView)findViewById(R.id.messageBox);
check();
}
//How to used other or many activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static void updateMessageBox(String msg,String from)
{
messageBox.append(msg);
//Get parent phone number from database
//check parent number with ...
if(msg.equals("enable wifi"))
{
x="yes";
MainActivity objSampleClass = new MainActivity();
objSampleClass.check();
}
//context.startActivity(new Intent(context, MainActivity.class));
//Intent i=new Intent(context, p1.class);
//context.startActivity(i);
}
public void check()
{
if(x.equals("yes"))
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
else
{
}
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.sms.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>
<receiver android:name="com.example.sms.TextMessageReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name="com.example.sms.Test"
android:label="#string/title_activity_test" >
</activity>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
</manifest>
To intercept the SMS as early as possible I use the following code:
public class Communicator extends Service {
private final String TAG = this.getClass().getSimpleName();
private SMSReceiver mSMSreceiver;
private IntentFilter mIntentFilter;
#Override
public void onCreate()
{
super.onCreate();
Log.i(TAG, "Communicator started");
//SMS event receiver
mSMSreceiver = new SMSReceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
mIntentFilter.setPriority(2147483647);
registerReceiver(mSMSreceiver, mIntentFilter);
Intent intent = new Intent("android.provider.Telephony.SMS_RECEIVED");
List<ResolveInfo> infos = getPackageManager().queryBroadcastReceivers(intent, 0);
for (ResolveInfo info : infos) {
Log.i(TAG, "Receiver name:" + info.activityInfo.name + "; priority=" + info.priority);
}
}
#Override
public void onDestroy()
{
super.onDestroy();
// Unregister the SMS receiver
unregisterReceiver(mSMSreceiver);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
private class SMSReceiver extends BroadcastReceiver
{
private final String TAG = this.getClass().getSimpleName();
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extras = intent.getExtras();
String strMessage = "";
if ( extras != null )
{
Object[] smsextras = (Object[]) extras.get( "pdus" );
for ( int i = 0; i < smsextras.length; i++ )
{
SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]);
String strMsgBody = smsmsg.getMessageBody().toString();
String strMsgSrc = smsmsg.getOriginatingAddress();
strMessage += "SMS from " + strMsgSrc + " : " + strMsgBody;
Log.i(TAG, strMessage);
if (strMsgBody.contains("SomeText")) {
// perform code
this.abortBroadcast();
}
}
}
}
}
}
Remember to register the service in manifest:
<service android:name="yourpackage.Communicator" />
Now in onCreate and onDestroy start and stop the service:
startService(new Intent(this, Communicator.class));
stopService(new Intent(this, Communicator.class));
In your BroadcastReceiver use following code,
Uri uri = Uri.parse("content://sms/");
ContentResolver contentResolver = getContentResolver();
String phoneNumber = "+9856874236";
String sms = "address='"+ phoneNumber + "'";
Cursor cursor = contentResolver.query(uri, new String[] { "_id", "body" }, "read = 0 and address='" + sms, null, null);
if ( cursor.getCount() > 0 )
{
// perform action to start Wifi Connection
}
Also in AndroidManifest.xml file you need to set Priority for reading SMS by your application as follows,
<receiver android:name="com.example.sms.TextMessageReceiver" >
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>