The Service not lunching after device reboot ...! - android

hey i have service its wallpaper service (not live wallpaper) so when I enter the app i have 5 radio buttons every button decide the time that the wallpaper changes and I have a button that triggers the service and i got response from my server even when i close the app but.... when i restart the device i get 1 response only and the wallpaper not changing lets say i was choised for every 4 second to change just when i reboot it stops and like i said i receive just one response from my server and stops even the wallpaper don't change with this response take a look at my code you will understand more (I used receiver and boot primission but ... );
MainActivity;
private final static int INTERVAL = 4000; //10 min
private final static int INTERVAL2 = 1000*60*30; // 30 min
private final static int INTERVAL3 = 1000 * 60 * 120; // 2 hours
private final static int INTERVAL4 = 1000 * 60 * 360; // 6 hours min
private final static int INTERVAL5 = 1000 * 60 * 1440; // 1 day
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rd1 = (RadioButton) findViewById(R.id.radioButton);
rd2 = (RadioButton) findViewById(R.id.radioButton2);
rd3 = (RadioButton) findViewById(R.id.radioButton3);
rd4 = (RadioButton) findViewById(R.id.radioButton4);
rd5 = (RadioButton) findViewById(R.id.radioButton5);
radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
mHandler = new Handler();
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this , WallService.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
if (rd1.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL, pintent);
} else if (rd2.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL2, pintent);
}else if (rd3.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL3, pintent);
}else if (rd4.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL4, pintent);
}else if (rd5.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), INTERVAL5, pintent);
}
}
});
}
service
String forecastJsonStr;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
final Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("yay.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
DataOutputStream wr = new DataOutputStream(
urlConnection.getOutputStream());
wr.write("method=get_random_wallpaper".getBytes());
wr.flush();
wr.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("hey", buffer.toString());
}
if (buffer.length() == 0) {
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
}
});
thread1.start();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap result = Picasso.with(getBaseContext())
.load(hostName + hostWallpaperName + forecastJsonStr)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
receiver
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, WallService.class);
context.startService(pushIntent);
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.lol8">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".BootCompletedIntentReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".WallService"
android:enabled="true"
android:exported="true">
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

After device reboot alarms set in Alarm manager are cleared - docs
You need to initialize Alarm manager again in your on BOOT_COMPLETED receiver. You can use sharedPrefference to store the time you need to set your alarms
In onClick of the activity add
SharedPreference preference = PreferenceManager.getDefaultSharedPreference(this);
preference.edit.putInt("timeInterval",INTERVAL).apply;
Then in onReceive in the receiver:
SharedPreference preference =
PreferenceManager.getDefaultSharedPreference(this);
int interval = preference.getInt("timeInterval", 4000);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),interval, pintent);

Create a receiver and register like this in manifest, then onReceive() you need to start your service again
<receiver
android:enabled="true"
android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

Related

Alarmmanager working sometimes on device

The alarmmanager is working perfectly on emulator but not on physical device.
It works sometimes on the device. Please help. i cant find why its not working on device. Is there a bug?
The same code was working fine earlier.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wim.wimonandroid"
android:versionCode="94"
android:versionName="10.1" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<application
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:screenOrientation="portrait"
android:name=".wimOnAndroid"
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=".Compas"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name=".TutorialZoomActivity1"
android:label="#string/ramadan" >
</activity>
<activity
android:name=".AlarmListView"
android:label="#string/app_name3" >
</activity>
<activity
android:name=".wimRss"
android:label="#string/app_name1" >
</activity>
<activity
android:name=".CityListView"
android:label="#string/app_name4" >
</activity>
<activity
android:name=".jummah"
android:label="#string/jummah" >
</activity>
<activity
android:name=".settings"
android:label="#string/settings" >
</activity>
<activity
android:name=".QA"
android:label="#string/QA" >
</activity>
<activity
android:name=".SendEmailActivity"
android:label="#string/app_name_Sendmail" >
</activity>
<activity
android:name=".Touch"
android:label="#string/app_name" >
</activity>
<activity
android:name=".compass"
android:label="#string/compass" >
</activity>
<activity
android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name=".sehri"
android:label="sehri" >
</activity>
<activity
android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name=".iftari"
android:label="iftari" >
</activity>
<activity
android:name=".felles"
android:label="felles" >
</activity>
<!-- <service android:enabled="true" android:name=".AlarmService" /> -->
<service android:name=".MyAlarmService" >
</service>
<service android:name=".UpdateWidgetService" >
</service>
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".MyBroadcastreceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<data android:scheme="package" />
</intent-filter>
</receiver>
<receiver
android:name=".wimWidget"
android:label="#string/app_nameWid" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/hello_widget_provider" />
</receiver>
<activity
android:name=".SehriActivity"
android:label="#string/title_activity_sehri" >
</activity>
</application>
package com.wim.wimonandroid;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;
public class MyAlarmService extends Service {
MediaPlayer player;
String readString = new String("");
String readAlarm = new String("");
String readSpilt = new String("");
String readForste = new String("");
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
#Override
public void onCreate() {
Log.v("tid", "MyAlarmService - onCreate()" );
try {
readFile(); //sjekker om Alarm er slått på eller ei
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
hent(); //setter neste alarm
} catch (IOException e) {
e.printStackTrace();
}
if(readString.equals("2") ){
Log.v("tid", "MyAlarmService - onCreate - Kaller onDestroy()" );
onDestroy() ;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v("tid", "MyAlarmService - onDestroy");
//writeFile(2);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("tid", "MyAlarmService - onStartCommand()");
String forste = new String("");
try {
readFile(); // Sjekker om alarm er på eller ei.
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
forste = readForste();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) ; //1300
int minutes = cal.get(Calendar.MINUTE);
Log.v("tid", "MyAlarmService - onStartCommand - readAlarm: " +
readAlarm);
AudioManager am =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
Log.v("tid","Silent mode");
break;
case AudioManager.RINGER_MODE_VIBRATE:
Log.v("tid","Vibrate mode");
break;
case AudioManager.RINGER_MODE_NORMAL:
Log.v("tid","Normal mode - onStart");
// if(Integer.parseInt(readAlarm.trim()) == 0){
if(readAlarm.equals("0")){
Log.i("tid","Normal mode - door - Minutter: " + minutter);
am.setStreamVolume(AudioManager.STREAM_MUSIC,
am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
player = MediaPlayer.create(this, R.raw.door);
player.setLooping(false); // Set looping
player.setVolume(1, 1);
player.start();
player.release();
Runnable r = new Runnable() {
public void run(){
}
};
Handler h = new Handler();
h.postDelayed(r, 60000);
//alarmHjelp.restart();
}
//else if(Integer.parseInt(readAlarm.trim()) == 1){
else if(readAlarm.equals("1")){
Log.i("tid","Normal mode - azaan");
am.setStreamVolume(AudioManager.STREAM_MUSIC,
am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
player = MediaPlayer.create(this, R.raw.azan);
player.setLooping(false); // Set looping
player.setVolume(1, 1);
player.start();
player.release();
Runnable r = new Runnable() {
public void run(){
}
};
Handler h = new Handler();
h.postDelayed(r, 60000);
}
break;
}
if(readAlarm.equals("0") || readAlarm.equals("1")){
Log.i("tid","vibrasjon");
Vibrator v = (Vibrator)
getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(4000);
Toast.makeText(getApplicationContext(), "Tid for bønn..." ,
Toast.LENGTH_LONG).show();
}
}
try {
hent(); //setter neste alarm
} catch (IOException e) {
e.printStackTrace();
}
//} // 2 er lydløs
Log.v("tid","MyAlarmService - OnStartCommand - Start sticky");
return START_STICKY;
}
public void hent() throws IOException{
Log.v("tid", "MyAlarmService - hent()");
int alarmH = 0;
int alarmM = 0;
Calendar cal2 = Calendar.getInstance();
int hour = cal2.get(Calendar.HOUR_OF_DAY) ;
int minutes = cal2.get(Calendar.MINUTE);
try {
checkBy = readCity();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tider = new String("");
Log.v("tid", "MyAlarmService - hent() - By: " + checkBy);
//Setting alarm every second hour
alarmH = alarmH + 2;
Intent myIntent = new Intent(this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
if(nesteDag == 1)
{
Log.v("tid", "MyAlarmService - hent() - nestedag");
cal.add( Calendar.DATE, 1 );
}
cal.set(Calendar.HOUR_OF_DAY, alarmH);
cal.set(Calendar.MINUTE, alarmM);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
Log.i("tid", "MyAlarmService - hent() - Neste alarm: " + alarmH +
":" + alarmM);
}
}
public void readFile() throws IOException{
Log.v("tid", "MyAlarmService - readFile() - readAlarm: " + readAlarm);
// open the file for reading
InputStream instream = openFileInput("alarm.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while (( readAlarm = buffreader.readLine()) != null) {
Log.v("tid", "readAlarm: " + readAlarm);
break;
}
instream.close();
if(readAlarm == null){
Log.v("tid", "MyAlarmService - readFile - readAlarm er NULL");
readAlarm = "2";
writeFile(2);
Log.v("tid", "MyAlarmService - readFile - readAlarm (ny verdi):
" + readAlarm);
}
}
public void onBackPressed()
{
this.startActivity(new Intent(this,wimOnAndroid.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
}

Android NDEF message with two activities and wrong intent content

I'm new to NFC with Android and I'm trying to make a kind of messaging app with NFC.
I have a first activity that sends the content of an EditText view to the other phone when beaming and displays the incoming message on a TextView on the other phone. This works fine.
I have another activity which is used to add a contact to the contacts register, it should work as the following:
A wants to add B as a contact,
A goes to the AddContactActivity, enters the name of the contact in the EditText view,
then B touches A's phone (on the same activity) and sends their identifier (public key, for further encryption).
My problem is that even though the code concerning the sending via NFC is basically the same between the two activities, when I beam on the second activity (AddContactActivity), the action of the intent sent is ACTION_MAIN instead of ACTION_NDEF_DISCOVERED, which has the effect of opening the first activity and thus not going through the right treatment.
Here is the code of the MainActivity:
public class MainActivity extends Activity {
private TextView mTextView;
private EditText mEdit;
NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
mTextView = (TextView)findViewById(R.id.retour);
mEdit = (EditText)findViewById(R.id.editText);
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
#Override public NdefMessage createNdefMessage(NfcEvent event) {
String stringOut = mEdit.getText().toString();
byte[] bytesOut = stringOut.getBytes();
NdefRecord ndefRecordOut = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"text/plain".getBytes(),
new byte[] {},
bytesOut);
NdefMessage ndefMessageout = new NdefMessage(ndefRecordOut);
return ndefMessageout;
}
}, this);
checkAndProcessBeamIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
}
private void checkAndProcessBeamIntent(Intent intent) {
String action = intent.getAction();
if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)){
Parcelable[] parcelables =
intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage inNdefMessage = (NdefMessage)parcelables[0];
NdefRecord[] inNdefRecords = inNdefMessage.getRecords();
NdefRecord NdefRecord_0 = inNdefRecords[0];
String inMsg = new String(NdefRecord_0.getPayload());
mTextView.setText(inMsg);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(MainActivity.this,
intent.getAction().toString(),
Toast.LENGTH_LONG).show();
checkAndProcessBeamIntent(intent);
}
#Override
public void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public void generateKeys(){
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.YEAR, 1);
Date end = cal.getTime();
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
try {
kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext())
.setAlias("Keys")
.setStartDate(now)
.setEndDate(end)
.setSerialNumber(BigInteger.valueOf(1))
.setSubject(new X500Principal("CN=test1"))
.build());
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
kpg.generateKeyPair();
}
public void goToAddContact(View view) {
Intent intent = new Intent(this, AddContactActivity.class);
intent.setAction("NewActivity");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
}
Here is the code of the AddContactActivity:
public class AddContactActivity extends Activity{
NfcAdapter nfcAdapter;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
editText = (EditText)findViewById(R.id.editText);
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
Intent intent = getIntent();
nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
#Override public NdefMessage createNdefMessage(NfcEvent event) {
String stringOut = getMyPublicKey();
byte[] bytesOut = stringOut.getBytes();
NdefRecord ndefRecordOut = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"text/plain".getBytes(),
new byte[] {},
bytesOut);
NdefMessage ndefMessageout = new NdefMessage(ndefRecordOut);
return ndefMessageout;
}
}, this);
checkAndProcessBeamIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Toast.makeText(AddContactActivity.this,
"onResume : "+intent.getAction().toString(),
Toast.LENGTH_LONG).show();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
}
public void addContactDataBase(String publicKey){
SQLiteHelper sqLiteHelper = new SQLiteHelper(this);
sqLiteHelper.addUser(new User(editText.getText().toString(), publicKey));
}
public void checkUserInDataBase(String publicKey){
SQLiteHelper sqLiteHelper = new SQLiteHelper(this);
User u = sqLiteHelper.getUser(publicKey);
Toast.makeText(AddContactActivity.this,
""+u.getName(),
Toast.LENGTH_LONG).show();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(AddContactActivity.this,
"OnNewIntent : "+intent.getAction().toString(),
Toast.LENGTH_LONG).show();
checkAndProcessBeamIntent(intent);
}
#Override
public void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
private void checkAndProcessBeamIntent(Intent intent) {
String action = intent.getAction();
if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)){
Toast.makeText(AddContactActivity.this,
"COUCOU",
Toast.LENGTH_LONG).show();
Parcelable[] parcelables =
intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage inNdefMessage = (NdefMessage)parcelables[0];
NdefRecord[] inNdefRecords = inNdefMessage.getRecords();
NdefRecord NdefRecord_0 = inNdefRecords[0];
String inMsg = new String(NdefRecord_0.getPayload());
addContactDataBase(inMsg);
checkUserInDataBase(inMsg);
}
}
public String getMyPublicKey(){
KeyStore ks = null;
RSAPublicKey publicKey = null;
try {
ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry("Keys", null);
publicKey = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
}
return publicKey.toString();
}
}
And here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bsauzet.testnfc" >
<uses-permission android:name="android.permission.NFC" />
<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.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddContactActivity"
android:label="#string/title_activity_add_contact"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
</manifest>
Check your appCompat libraries. Corruptness of appCompat libraries may cause wrong intent exceptions. Especially when you move your project from another PC or workspace (and/or IDE).
Getting an intent with ACTION_MAIN instead of ACTION_NDEF_DISCOVERED upon receiving an NFC event is a typical indication that an NDEF message containing an Android Application Record (AAR) was received and that the datatype of the first record of the NDEF message was not matched by any intent filter.
Your CreateNdefMessageCallback.createNdefMessage() method clearly does not add an AAR to the NDEF message. Consequently, the only reason why you would still receive an NDEF message containing an AAR would be that the createNdefMessage() raises an unhandled exception. In that case, the NFC stack will automatically generate an NDEF message containing a Play Store link and an AAR.
The most likely place that could cause createNdefmessage() to raise an unhandled exception is getMyPublicKey() (as that's the only part that differs between MainActivity and AddContactActivity).
So we can track the problem down to this part of your code:
ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry("Keys", null);
publicKey = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
This code either
raises an unhandled runtime exception (e.g. if ks, keyEntry, or keyEntry.getCertificate() is null, or if ks.getEntry("Keys", null) cannot be cast to a KeyStore.PrivateKeyEntry), or
raises any of the handled exceptions, which causes publicKey to be null which results in an unhandled NullPointerException upon trying to invoke the toString() (in return publicKey.toString();).

Sim Tracking in android

I am doing a app on sim tracking but unable to get result
here is the main activity
public class MainActivity extends Activity {
String FILENAME = "old_file.txt";
int simstatus;
String simNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (simstatus != TelephonyManager.SIM_STATE_ABSENT) {
System.out.println("--------SIM Present:" + simstatus);
simNo = tManager.getSimSerialNumber();
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(simNo.getBytes());
System.out.println("---------Data written to files is:"
+ simNo);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Reciever
public class SimDataReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
System.out.println("Reciever Started");
Intent CompareSimServiceIntent = new Intent(context,demo.class);
context.startService(CompareSimServiceIntent);
}
}
}
and the service..
String FILENAME = "old_file.txt";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, final int startId) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//run your service
// Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine();
System.out.println("---Data Read From File is:" + data);
String newsiminfo = tManager.getSimSerialNumber();
System.out.println("---New SIM no is:" + newsiminfo);
if (data.equals(tManager.getSimSerialNumber())) {
System.out.println("------Old sim Present:");
// Toast.makeText(this, "Old SIM", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(this, "New SIM", Toast.LENGTH_LONG).show();
SmsManager smsMngr = SmsManager.getDefault();
String destinationaddress = "8281306132";
String scAddress = null;
String text = "New Sim Is Inserted In Your Device";
PendingIntent sentIntent = null;
PendingIntent deliveryIntent = null;
smsMngr.sendTextMessage(destinationaddress, scAddress, text,
sentIntent, deliveryIntent);
System.out.println("-----SMS Send");
}
} catch (Exception e) {
}
}
}, 1*60*1000);
return startId;
}
}
pls help me to find the solution....
I have found similar kind of problem, when working on same kind of project.
I was also not able to track the sim after the device reboot. The problem I found here was that I was invoking the sim tracking immediately after the device reboot. But the system takes 15 to 20 seconds to load resources. The sim was not getting launched immendiately after the device reboot, so my receiver was unable to track the sim.
So, I delayed the sim tracking for 20 seconds after the device reboot. Try to delay the sim tracking and check if it works.
Edit-
Your Receiver should be like this,
public class SimDataReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Reciever Started");
Log.d("BOOT COMPLETE","Receiver Called");
Intent CompareSimServiceIntent = new Intent(context,demo.class);
context.startService(CompareSimServiceIntent);
}
}
and in Manifest file, replace your code with this,
<receiver android:name=".SimDataReciever"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Now, check whether the messages are shown in the logcat or not.

My IntentService doesn't seem to return an answer, or it isn't called at all?

I've got a problem with my IntentService - my intention is to outsource the networking and processing from the activity (I previously used an AsyncTask which worked excellent, however I also want to extend it to a widget).
The thing is, I don't get any result from the service - it almost seems like it never gets called (or something is wrong in the code that's supposed to retreive the data)...
Can someone with more experience in using services than me take a look and spot the obvious (or hidden) errors I've made?
Would be greatly appreciated!
Contents of the service:
public class StateCheckerService extends IntentService {
public StateCheckerService() {
super("StateCheckerService");
// TODO Auto-generated constructor stub
}
String pageContent;
public static final String API_URL = "http://omegav.no/api/dooropen.php", INTENT_ACTION="omegavdoor.FETCH_COMPLETE", EXTRA_STATUS="status", EXTRA_TIME="time", KEY_STATUS="";
SharedPreferences settings;
private int timeMins = 0, timeoutMillis = 5000, resultCode;
int status_code = 0;
public void onCreate() {
super.onCreate();
// Declares the SharedPreferences object to use
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(null, resultCode, resultCode);
return START_FLAG_RETRY;
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (checkConnection()) {
// Start process of retrieving status
try {
getData();
} catch (IOException e) {
returnResult(11);
} finally {
returnResult(resultCode);
}
} else {
// Notify the user of missing connection
returnResult(0); // Error: connection unavailable
}
}
private boolean checkConnection() {
// Declare connection manager and NetworkInfo objects
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
// Check network connection
if (activeInfo != null && activeInfo.isConnected()) {
return true;
} else {
return false;
}
}
/** Function to get data from the remote server */
public void getData() throws IOException {
// Create URL object to connect to
URL url = new URL(API_URL);
// Open new HTTP connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Set a connection timeout to prevent app lockup if it can't reach the server
urlConnection.setConnectTimeout(timeoutMillis);
// Attempt to connect and retrieve data
try { // Return exception if the stream is unreachable
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// Process the contents of the stream
readStream(in);
}
finally {
// Disconnect after retrieving data
urlConnection.disconnect();
}
}
public void readStream(InputStream input) throws IOException {
// Reads the content of the page
try {
// String length varies with the time value - read some extra to avoid missing the end
pageContent = readIt(input, 40);
// Remove the extra white spaces at the end
} catch (UnsupportedEncodingException e) {
resultCode = 10;
}
if (pageContent == null) {
// Stop further processing (and cause the UI to report error)
resultCode = 13;
} else {
// Checks to see whether the "open" flag exists
if (pageContent.charAt(9) == '1') {
// Find out how long it's been open
int openTime = Integer.parseInt(pageContent.substring(20, pageContent.lastIndexOf("}")));
// Convert from seconds to minutes
timeMins = openTime / 60;
if (timeMins > 0) {
resultCode = 1; // Display how long it's been open
} else {
resultCode = 2; // If it just opened
}
} else {
// Find out how long it's been closed
int closedTime = Integer.parseInt(pageContent.substring(19, pageContent.lastIndexOf("}"))); // TODO: change 19 to 20 to support the API change
// Convert from seconds to minutes
timeMins = closedTime / 60;
if (timeMins > 0) {
resultCode = 3; // Display how long it's been open
} else {
resultCode = 4; // If it just closed
}
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
// Initialize reader object
Reader reader = null;
// Decode the input stream
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
private void returnResult(int resultCode) {
Intent resultIntent = new Intent();
resultIntent.setAction(INTENT_ACTION);
resultIntent.putExtra(EXTRA_STATUS, resultCode)
.putExtra(EXTRA_TIME, timeMins);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Contents of the calling activity:
public class StateChecker extends Activity {
String pageContent;
boolean doorIsOpen = false, notFirstRun = false, error = false;
private static final int transitionDuration = 250;
private ResponseReceiver receiver;
TransitionDrawable transition;
TextView text_doorState;
Button button_getState;
ProgressBar door_progress;
LinearLayout background;
int timeMins;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the XML layout
setContentView(R.layout.state_checker);
// Declare the views to be adressed
text_doorState = (TextView) findViewById(R.id.tv_doorState);
button_getState = (Button) findViewById(R.id.button_refreshState);
door_progress = (ProgressBar) findViewById(R.id.doorState_progressBar);
background = (LinearLayout) findViewById(R.id.doorStateView);
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
}
/** Receiver class to listen to and handle result from checker service */
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = StateCheckerService.INTENT_ACTION;
#Override
public void onReceive(Context context, Intent intent) {
int result = intent.getIntExtra(StateCheckerService.EXTRA_STATUS, 0);
timeMins = intent.getIntExtra(StateCheckerService.EXTRA_TIME, 0);
Toast.makeText(context, "Result received", Toast.LENGTH_SHORT).show();
processResult(result);
}
}
public void onStart() {
super.onStart();
// Checks the door status on app launch
go();
}
public void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
private void go() {
// Update text and progress bar to indicate it's working
text_doorState.setText(R.string.text_stateUpdating);
door_progress.setVisibility(View.VISIBLE);
// Fade the color back to grey if it is something else
if (notFirstRun) {
transition.reverseTransition(transitionDuration);
}
if (checkConnection()) {
Intent intent = new Intent(this, StateCheckerService.class);
startService(intent);
notify("service started");
} else {
// Notify the user of missing connection
notify(getString(R.string.error_connection_unavailable));
}
}
private boolean checkConnection() {
// Declare connection manager and NetworkInfo objects
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
// Check network connection
if (activeInfo != null && activeInfo.isConnected()) {
return true;
} else {
return false;
}
}
protected void processResult(Integer resultCode) {
switch (resultCode) {
case 1:
if (timeMins < 60) {
// Notify of open door and display minutes
notify(getString(R.string.text_stateOpenMins, timeMins));
} else {
// If it's been more than an hour, display the time in hours
int openTimeHours = timeMins / 60;
int remainder = timeMins - (openTimeHours * 60);
notify(getString(R.string.text_stateOpenHours, openTimeHours, remainder));
}
break;
case 2:
// Notify of open door (just opened)
notify(getString(R.string.text_stateOpenNow));
break;
case 3:
if (timeMins < 60) {
// Notify of closed door and display minutes
notify(getString(R.string.text_stateClosedMins, timeMins));
} else {
// If it's been more than an hour, display the time in hours
int closedTimeHours = timeMins / 60;
int remainder = timeMins - (closedTimeHours * 60);
notify(getString(R.string.text_stateClosedHours, closedTimeHours, remainder));
}
break;
case 4:
// Notify of closed door (just closed
notify(getString(R.string.text_stateClosedNow));
break;
case 10:
// Error message: unsupported stream format
notify(getString(R.string.error_stream_unsupported));
break;
case 11:
// Error message: connection failed
notify(getString(R.string.error_connection_failed));
break;
// Case 12 reserved
case 13:
// Error message: null data stream
notify(getString(R.string.error_stream_retrieve));
break;
}
if (resultCode >= 10) {
error = true;
} else {
error = false;
}
updateDisplay();
}
protected void updateDisplay() {
door_progress.setVisibility(View.GONE);
if (!error) {
/** Update the UI to reflect the door state */
if(doorIsOpen) {
// Update the text view to display an open door state
text_doorState.setText(getString(R.string.text_stateOpen));
// Change the background color
background.setBackgroundResource(R.drawable.trans_open);
transition = (TransitionDrawable) background.getBackground();
transition.startTransition(transitionDuration);
} else {
// Update the text view to display a closed door state
text_doorState.setText(getString(R.string.text_stateClosed));
// Change the background color
background.setBackgroundResource(R.drawable.trans_close);
transition = (TransitionDrawable) background.getBackground();
transition.startTransition(transitionDuration);
}
// Indicates that the app has gone through a successful execution
notFirstRun = true;
} else {
// If it failed to execute, display error message
text_doorState.setText(R.string.text_stateFailed);
// Revert to grey background
background.setBackgroundResource(R.drawable.background);
}
}
/** Helper class used to display toast notifications */
private void notify(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Edit (AndroidManifest):
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tovine.omegavdoor.widget"
android:versionCode="5"
android:versionName="1.0.1" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Settings"
android:label="#string/title_activity_settings" >
</activity>
<activity
android:name=".StateChecker"
android:configChanges="orientation|screenSize"
android:title="#string/app_name"
android:windowSoftInputMode="stateAlwaysHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
<receiver
android:name=".WidgetStateProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="omegavdoor.FETCH_COMPLETE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/doorwidget" />
</receiver>
<service android:name="tovine.omegavdoor.widget.WidgetUpdateService">
<intent-filter>
<action android:name="omegavdoor.FETCH_COMPLETE" />
</intent-filter>
</service>
<service android:name="tovine.omegavdoor.widget.StateCheckerService"
android:process=":checker_process">
</service>
-->
<!-- <activity
android:name="Probability"
android:label="#string/title_activity_probability" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="StateChecker" />
</activity>
<activity
android:name=".LoadWebImg"
android:label="TestClass" /> -->
</application>
</manifest>
I can be wrong but it seems your returnResult() function doesn't send anything. Maybe you forgot to add sendBroadcst(resultIntent); call to it?
For intent service we does not need to implement/override the method onStartCommand
So remove the following coding
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(null, resultCode, resultCode);
return START_FLAG_RETRY;
}
from the "Contents of the service"
Then try it.

Why onPushMessageReceived() is not called in Geoloqi API in Android?

In my android app i am using Latest Geoloqi API to implement Geofence concept.when user entered into some region he has notify, for that purpose i am using Push Notifications.in GeoReceiver class three callback methods are calling but not onPushMessageReceived().please help me how to do it?
I am creating trigger with current location is it required to enter into region manually or since i am already in the location its not calling?
Note:I ve given required credentials in assets/geoloqi.properties file.when app is launched in logcat "Successfully registered for the C2DM service" msg also displayed.my code:
GeoloqiExampleActivity.java
public class GeoloqiExampleActivity extends Activity{
String TAG = "Geoloqi Example";
private LQService mService;
private boolean mBound;
GeoReceiver geoReceiver = new GeoReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, LQService.class);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
// Bind to the tracking service so we can call public methods on it
Intent intent = new Intent(this, LQService.class);
bindService(intent, mConnection, 0);
// Wire up the sample location receiver
final IntentFilter filter = new IntentFilter();
filter.addAction(GeoReceiver.ACTION_LOCATION_CHANGED);
filter.addAction(GeoReceiver.ACTION_TRACKER_PROFILE_CHANGED);
filter.addAction(GeoReceiver.ACTION_LOCATION_UPLOADED);
filter.addAction(GeoReceiver.ACTION_PUSH_MESSAGE_RECEIVED);
registerReceiver(geoReceiver, filter);
}
#Override
public void onPause() {
super.onPause();
// Unbind from LQService
if (mBound) {
unbindService(mConnection);
mBound = false;
}
// Unregister our location receiver
unregisterReceiver(geoReceiver);
}
public void sendRequest() {
// Performing a Trigger POST request
if (mService != null) {
LQSession session = mService.getSession();
LQTracker tracker = mService.getTracker();
tracker.setSession(session);
// Build your request
JSONObject trigger = new JSONObject();
try {
trigger.put("text", "Popcornapps");
trigger.put("type", "message");
trigger.put("latitude", 17.42557068);
trigger.put("longitude", 78.42022822);
trigger.put("radius", 500);
trigger.put("place_name", "Banjara Hills");
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
// Send the request
session.runPostRequest("trigger/create", trigger, new OnRunApiRequestListener() {
#Override
public void onSuccess(LQSession session, HttpResponse response) {
Toast.makeText(GeoloqiExampleActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
String result = s.toString().trim();
Log.d("On success Result", result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(LQSession session, LQException e) {
Log.e(TAG, e.getMessage());
Toast.makeText(GeoloqiExampleActivity.this, "Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(LQSession session, HttpResponse response, StatusLine status) {
Toast.makeText(GeoloqiExampleActivity.this, "Complete", Toast.LENGTH_LONG).show();
}
});
} else{
Toast.makeText(this, "service null", Toast.LENGTH_LONG).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
// We've bound to LocalService, cast the IBinder and get LocalService instance.
LQBinder binder = (LQBinder) service;
mService = binder.getService();
mBound = true;
sendRequest();//Sending API Request
} catch (ClassCastException e) {
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
}
GeoReceiver.java
public class GeoReceiver extends LQBroadcastReceiver {
#Override
public void onLocationChanged(Context arg0, Location arg1) {
Toast.makeText(arg0, "Loc Changed ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPushMessageReceived(Context context, Bundle data) {
Toast.makeText(context, "Push Msg Received ", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationUploaded(Context arg0, int arg1) {
Toast.makeText(arg0, "Location Uploaded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onTrackerProfileChanged(Context arg0, LQTrackerProfile oldp,
LQTrackerProfile newp) {
Toast.makeText(arg0, "onTrackerProfileChanged ",Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pop.geoloqi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<permission
android:name="com.pop.geoloqi.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.pop.geoloqi.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".GeoloqiExampleActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.geoloqi.android.sdk.service.LQService"
android:exported="false" />
<receiver
android:name=".GeoReceiver"
android:enabled="false"
android:exported="false" >
<intent-filter>
<action android:name="com.geoloqi.android.sdk.action.LOCATION_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="com.geoloqi.android.sdk.receiver.LQDeviceMessagingReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.pop.geoloqi" />
</intent-filter>
</receiver>
</application>
</manifest>
There was a bug in earlier versions of the Geoloqi Android SDK. If you update to the latest version this problem should be resolved.

Categories

Resources