I am new to android .I am getting a runtime exception says "Error receiving broadcast Intent ACTION_POWER_DISCONNECTED ".I instantiate my receiver in onCreate() of my activity then I register my receiver in onResume() and unregistered it in onPause() methods.
Actually i want to set text Charging and Not Charging according to the charging mode of my app
package com.example.mrfrag.firebattery;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends AppCompatActivity{
TextView batteryplus,temp,setting,plug,charging,battery;
private BroadcastReceiver mReceiver;
IntentFilter ifilter =new IntentFilter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
batteryplus= findViewById(R.id.batteryplus);
temp = findViewById(R.id.temp);
setting= findViewById(R.id.setting);
plug= findViewById(R.id.plug);
charging= findViewById(R.id.charging);
battery= findViewById(R.id.battery);
mReceiver=new PowerConnectionReceiver();
ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
ifilter.addAction(Intent.ACTION_BATTERY_CHANGED);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, ifilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
public class PowerConnectionReceiver extends BroadcastReceiver {
public PowerConnectionReceiver(){
}
#Override
public void onReceive(Context context, Intent batteryStatus) {
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS,
-1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
||
status == BatteryManager.BATTERY_STATUS_FULL;
if (isCharging) {
plug.setText("CHARGING");
} else {
plug.setText("NOT CHARGING");
}
int health =
batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
batteryplus.setText(ConvoHealth(health));
String technology =
batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
setting.setText(technology);
float tpr = ((float)
batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0)) / 10.0f;
temp.setText( String.valueOf(tpr) + "°C / " +
String.valueOf(tpr*1.8+32)+"F"+"\n");
int voltage =
batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
charging.setText(voltage+ " mV");
int mah = batteryStatus.getIntExtra(String.valueOf
(BatteryManager.BATTERY_PROPERTY_CAPACITY),0);
battery.setText(mah+ " Mah");
}
}
private String ConvoHealth(int health){
String result;
switch(health){
case BatteryManager.BATTERY_HEALTH_COLD:
result = "COLD";
break;
case BatteryManager.BATTERY_HEALTH_DEAD:
result = "DEAD";
break;
case BatteryManager.BATTERY_HEALTH_GOOD:
result = "GOOD";
break;
case BatteryManager.BATTERY_HEALTH_OVERHEAT:
result = "OVERHEAT";
break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
result = "OVER VOLTAGE";
break;
case BatteryManager.BATTERY_HEALTH_UNKNOWN:
result = "UNKNOWN";
break;
case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
result = "UNSPECIFIED_FAILURE";
break;
default:
result = "Unknown";
}
return result;
}
}
This is my AndroidManifest.xml file
This is Runtime exception
The reason you are getting this exception is because of following line:
String technology =
batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
setting.setText(technology);
The above line is throwing null pointer. This extra is only available for Intent.ACTION_BATTERY_CHANGED. So either remove it or add condition
if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
String technology =
batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
setting.setText(technology);
setting.setText(technology);
}
Related
At the moment I'm writing an App which Scans NFC Tags and tells you what's written on the Tag.
But now I have a problem. I wrote a Intent into the Menu, so that from the Menu you can get to that Scan-Page. But when I pasted the code that Scans the NFC Tags, the Intent suddenly Stoped working.
I can install the App without a Problem and there is no Error, but When I click onto the Button in The Menu that should bring me to the Page on which I scan NFC Tags, the App just crashes.
I really do not Know where the error is, and I would be very glad if you could help me.
I will provide the code I have so far below:
Menu with Intents:
package com.example.kristian.nfcproject;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class nfc_menu extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_menu);
getSupportActionBar().hide();
Button buttonLogout = (Button) findViewById(R.id.buttonLogout);
Button buttonProfil = (Button) findViewById(R.id.buttonProfil);
Button buttonAssets = (Button) findViewById(R.id.buttonAssets);
Button buttonNfcid = (Button) findViewById(R.id.buttonNfcid);
Button buttonNfcscan = (Button) findViewById(R.id.buttonNfcscan);
buttonLogout.setOnClickListener(
new Button.OnClickListener()
{
public void onClick(View v)
{
Intent logoutI = new Intent(v.getContext(), MainActivity.class);
startActivity(logoutI);
}
}
);
buttonProfil.setOnClickListener(
new Button.OnClickListener()
{
public void onClick(View v)
{
Intent meinprofilI = new Intent(v.getContext(), meinprofil.class);
startActivity(meinprofilI);
}
}
);
buttonAssets.setOnClickListener(
new Button.OnClickListener()
{
public void onClick(View v)
{
Intent assetsI = new Intent(v.getContext(), meineassets.class);
startActivity(assetsI);
}
}
);
buttonNfcid.setOnClickListener(
new Button.OnClickListener()
{
public void onClick(View v)
{
Intent nfcidI = new Intent(v.getContext(), nfcidhinzu.class);
startActivity(nfcidI);
}
}
);
buttonNfcscan.setOnClickListener(
new Button.OnClickListener()
{
public void onClick(View v)
{
Intent nfcscannI = new Intent(v.getContext(), nfctagscann.class);
startActivity(nfcscannI);
}
}
);
}
}
The NFC Scan Activity:
package com.example.kristian.nfcproject;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.view.View;
import android.widget.Button;
import com.example.kristian.nfcproject.R;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class nfctagscann extends AppCompatActivity {
TextView text;
NfcAdapter nfcAdapter;
public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String TAG = "NfcDemo";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfcidhinzu);
getSupportActionBar().hide();
text = (TextView) findViewById(R.id.textView);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "This Device doesn't support NFC", Toast.LENGTH_LONG).show();
finish();
}
if (!nfcAdapter.isEnabled()) {
text.setText("Please enable NFC in your settings.");
} else {
text.setText(R.string.explanation);
}
handleIntent(getIntent());
}
#Override
protected void onResume() {
super.onResume();
/**
* It's important, that the activity is in the foreground (resumed). Otherwise
* an IllegalStateException is thrown.
*/
setupForegroundDispatch(this, nfcAdapter);
}
#Override
protected void onPause() {
/**
* Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
*/
stopForegroundDispatch(this, nfcAdapter);
super.onPause();
}
#Override
protected void onNewIntent(Intent intent) {
/**
* This method gets called, when a new Intent gets associated with the current activity instance.
* Instead of creating a new activity, onNewIntent will be called. For more information have a look
* at the documentation.
*
* In our case this method gets called, when the user attaches a Tag to the device.
*/
handleIntent(intent);
}
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType(MIME_TEXT_PLAIN);
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("Check your mime type.");
}
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
private void handleIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
String type = intent.getType();
if (MIME_TEXT_PLAIN.equals(type)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
new NdefReaderTask().execute(tag);
} else {
Log.d(TAG, "Wrong mime type: " + type);
}
} else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
// In case we would still use the Tech Discovered Intent
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tag.getTechList();
String searchedTech = Ndef.class.getName();
for (String tech : techList) {
if (searchedTech.equals(tech)) {
new NdefReaderTask().execute(tag);
break;
}
}
}
}
private class NdefReaderTask extends AsyncTask<Tag, Void, String> {
#Override
protected String doInBackground(Tag... params) {
Tag tag = params[0];
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// NDEF is not supported by this Tag.
return null;
}
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
NdefRecord[] records = ndefMessage.getRecords();
for (NdefRecord ndefRecord : records) {
if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
try {
return readText(ndefRecord);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported Encoding", e);
}
}
}
return null;
}
private String readText(NdefRecord record) throws UnsupportedEncodingException {
/*
* See NFC forum specification for "Text Record Type Definition" at 3.2.1
*
* http://www.nfc-forum.org/specs/
*
* bit_7 defines encoding
* bit_6 reserved for future use, must be 0
* bit_5..0 length of IANA language code
*/
byte[] payload = record.getPayload();
// Get the Text Encoding
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
// Get the Language Code
int languageCodeLength = payload[0] & 0063;
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
// e.g. "en"
// Get the Text
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
text.setText("NFC INHALT" + result);
}
}
}
}
Before Pasting this pre written code into the App the Intent worked fine, now when I click the button to get to the Scan Activity the app just crashes.
I appreciate every kind of help :)
Log:
03-19 18:34:27.669 22810-22810/com.example.kristian.nfcproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kristian.nfcproject, PID: 22810
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kristian.nfcproject/com.example.kristian.nfcproject.nfctagscann}: java.lang.IllegalStateException: Already attached
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.IllegalStateException: Already attached
at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:3146)
at android.support.v4.app.FragmentController.attachHost(FragmentController.java:95)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:283)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
at com.example.kristian.nfcproject.nfctagscann.onCreate(nfctagscann.java:42)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
I'm building an Android Wear service which runs in the background and logs device data every three minutes. For this logging, I am using a Handler, which records the values and then has an interval of three minutes. This will be used to monitor user behaviour for one month, and as such it should not randomly stop.
I have also used android.intent.action.BOOT_COMPLETED in my manifest and this successfully runs the application whenever the watch is booted.
My issue is that the service can run correctly for 12 hours...and then just suddenly stop. The amount of time appears to be non-deterministic, as sometimes it will stop after 40 minutes. I suspect it's being killed by Android, but in this case I would like it to restart. I have included return START_STICKY in my service and this should minimise the chance of it being killed.
In some solutions, I have seen onDestroy() overridden and a refresh broadcast being sent to the service. While this appears to work, the onDestroy() function is being called every time the Handler completes one piece of work. This leads to the service restarting every three minutes, rather than when the application is actually killed by Android.
I have also looked at the intent actions to see whether my service could be called at regular intervals. However, aside from android.intent.action.BOOT_COMPLETED, all the useful ones cannot be registered in the Manifest file. Since the service will not be running, registerReceiver() would serve little purpose.
Does anybody know of a technique to either a) guarantee a service will not be killed by Android; or b) guarantee that a service will always be restarted after it has been killed. Any help would be greatly appreciated, as I've even started considering writing a Cron job on the device and setting it to execute my app every three minutes! I've also looked at the AlarmManager class, but I fear it is as likely to be killed if running for long periods.
Please find my code below: (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.study">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<receiver android:name="com.example.study.MyServiceManager" android:enabled="true">
<intent-filter>
<action android:name="com.example.study.RestartAction" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:name="com.example.study.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>
<service
android:name="com.example.study.RecordService"
android:exported="false" />
</application>
</manifest>
RecordService.java
package com.example.study;
import android.Manifest;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import com.google.android.gms.location.LocationServices;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import com.google.android.gms.location.*;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class RecordService extends IntentService {
private static Context context;
private final static int INTERVAL = 1000 * 5; // 1 minutes
Handler handler = new Handler();
Location myLocation;
private FusedLocationProviderClient mFusedLocationClient;
SensorManager sensorManager;
SensorManager gyroSensorManager;
SensorManager compassSensorManager;
SensorEventListener sensorEventListener;
float[] accValues;
float[] gyroValues;
float[] compassValues;
Runnable handlerTask = new Runnable() {
#Override
public void run() {
try {
recordData();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.postDelayed(handlerTask, INTERVAL);
}
};
public RecordService() {
super("RecordService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
handlerTask.run();
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
public void recordData() throws ExecutionException, InterruptedException {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MainActivity.getAppContext());
boolean fineLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean coarseLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean isLocationEnabled = isLocationEnabled(this);
if(fineLocationGranted && coarseLocationGranted && isLocationEnabled) {
long startTime = System.currentTimeMillis();
long timeWaiting = 0L;
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(MainActivity.getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
myLocation = location;
} else {
System.out.print("");
}
}
});
do {
timeWaiting = System.currentTimeMillis() - startTime;
} while (myLocation == null && timeWaiting < 200);
}
List<PackageInfo> packages = getPackageManager().getInstalledPackages(PackageManager.GET_PERMISSIONS);
KeyguardManager kg = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean isLocked = kg.isDeviceSecure();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
gyroSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
compassSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if(sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accValues = sensorEvent.values;
} else if(sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE){
gyroValues = sensorEvent.values;
} else if(sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
compassValues = sensorEvent.values;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {}
};
try {
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
gyroSensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_NORMAL);
compassSensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
} catch(SecurityException e) {
e.printStackTrace();
}
long startTime2 = System.currentTimeMillis();
long timeWaiting2 = 0L;
do {
timeWaiting2 = System.currentTimeMillis() - startTime2;
} while((accValues == null || gyroValues == null || compassValues == null) && timeWaiting2 < 200);
StringBuilder builder = new StringBuilder();
builder.append("G" + (isLocationEnabled ? 1 : 0));
builder.append(" L" + (isLocked ? 1 : 0));
if(accValues != null && gyroValues != null && compassValues != null) {
builder.append(" ACX" + accValues[0]);
builder.append(" ACY" + accValues[1]);
builder.append(" ACZ" + accValues[2]);
builder.append(" GYX" + gyroValues[0]);
builder.append(" GYY" + gyroValues[1]);
builder.append(" GYZ" + gyroValues[2]);
builder.append(" CMX" + gyroValues[0]);
builder.append(" CMY" + gyroValues[1]);
builder.append(" CMZ" + gyroValues[2]);
}
if(myLocation != null) {
builder.append(" LT" + myLocation.getLatitude());
builder.append(" LN" + myLocation.getLongitude());
}
builder.append("\n");
for(PackageInfo info: packages) {
int lastDot = info.packageName.lastIndexOf('.');
builder.append(info.packageName + "\n");
if(info.requestedPermissions != null) {
for (String rqprm : info.requestedPermissions) {
int dot = rqprm.lastIndexOf('.');
builder.append(rqprm.substring(dot != -1 ? dot + 1 : 0) + " ");
}
builder.append("\n");
for (int permflag : info.requestedPermissionsFlags) {
builder.append("" + permflag + " ");
}
builder.append("\n");
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd--HH-mm-ss");
String currentDateString = sdf.format(new Date());
File log = new File("/sdcard/Recordings/" + currentDateString);
try {
if (!log.exists()) {
log.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(log, true));
writer.append(builder.toString());
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
MainActivity.java
package com.example.study;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
private static Context context;
private static MainActivity activity;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.context = getApplicationContext();
activity = this;
serviceIntent = new Intent(this, RecordService.class);
startForegroundService(serviceIntent)
startService(serviceIntent);
}
public static Context getAppContext() {
return MainActivity.context;
}
public static MainActivity getActivity() {
return activity;
}
}
MyServiceManager.java
package com.example.study;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class MyServiceManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
}
I am basically working with Android Application , i have requirement to restrict to open others apps while my app is running, Means My app is running it will put some locks on other application while i am accessing the others app, Kind of Application Lock. I am trying but could not find good solution. If any buddy have some idea or link or sample code please share to me.
Basically you want Kiosk Mode .
Try this:
Home button press:
<category android:name="android.intent.category.HOME" /> //add in manifest
What id does: whenever you press the home button, all the applications installed in your phone which have category.HOME category in intent-filter in their AndroidManifest.xml will be listed .
then handle Long press Home Button:
#Override
protected void onPause() {
super.onPause();
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
}
for this add this line in manifest :
<uses-permission android:name="android.permission.REORDER_TASKS" />
3.handle BackButton :
#Override
public void onBackPressed() {
// Stop user to exit
// super.onBackPressed();
}
You can also try this for Kiosk Mode:
Read this document
import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.provider.SyncStateContract;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
public class HeartBeat extends Service {
private static final String TAG = HeartBeat.class.getSimpleName();
public Timer TIMER;
// private static Set<AccessGranted> mAccessGrantedList = new HashSet<AccessGranted>();
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
// private BroadcastReceiver mAccessGrantedReceiver;
private File mLockedAppsFile;
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
String prefix;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, HeartBeat.class));
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
//Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
// Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, HeartBeat.class));
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
Set keySet = allEntries.keySet();
Iterator<String> keySetIter = keySet .iterator();
while (keySetIter.hasNext()) {
String keyEntry= keySetIter.next();
Log.e("Shared Vaues",keyEntry);
}
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
packagezList.add(entry.getKey());
Log.e("right key: ", entry.getKey().toString() + "right value: " + entry.getValue().toString());
}
/* for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
//Check if the package name starts with the prefix.
if (entry.getKey().startsWith(prefix)) {
//Add JUST the package name (trim off the prefix).
packagezList.add(entry.getKey().substring(prefix.length()));
packagezList.add(entry.getKey());
}
}*/
for(Object object: packagezList){
Log.e("YO!", (String) object);
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
Log.e("activity on Top", "" + activityOnTop);
Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
// Provide the packagename(s) of apps here, you want to show password activity
if (!activityOnTop.contains(getApplicationContext().getPackageName()))
// if(!activityOnTop.contains(getApplicationContext().getPackageName()))
{ // you have to make this check even better
Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra( "", "");
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
Basicly I'm trying to cancel method execution in an aspect.
So, here's my program:
I have
a Sender Application
a receiver Application (let's call it the Central Monitor)
In the Sender App :
I have,
An Activity (ın this activity, I have a method called callMethodA() )
An Aspect (In this aspect, I'm catching before the callMethodA() execution and in this before structure, I'm starting the Service )
A Service (When this service is started, it basicly sends a String to the Receiver App by Broadcast)
In the Receiver App:
I have :
An Activity ( When a string is broadcasted by sender app, then it receives the broadcast by broadcastreceiver and puts the string into an automaton which checks some condition and when automaton completes, then Result string is broadcasted back to the sender App)
So here's my actual question :
When the Sender App receives the Result string (In the sender's Activity), if the Result is Success, then I want to allow callMethodA() to be executed( this can be done by doing simply nothing, because we caught the callMethodA() execution with before and if we do nothing, then this method will be executed. )
But if the Result is FAIL then I want this method not to be executed and also I want whole program to keep running (I mean for this broadcast result, callMethodA() doesn't have to be executed, It can be executed on the next broadcast result according to the automaton result), also I want to cancel it in the aspect.
Simply, please teach me how can I cancel a method execution in an aspect.
Here's the Sender App codes:
Sender1Activity.java
package com.example.sender;
import java.util.Random;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Sender1Activity extends Activity {
Button btn_send;
public Intent serviceIntent;
public Context context;
//The initial state for automaton Result is Success, nothing fancy.
static String string_AutomatonResult = "Success";
public int id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// context = getApplicationContext();
setContentView(R.layout.activity_sender1);
// serviceIntent = new Intent(context, senderService.class);
btn_send = (Button) findViewById(R.id.buttonSend);
methodCallerHandler.removeCallbacks(hMyValueTask);
methodCallerHandler.post(hMyValueTask);
registerReceiver(broadcastReceiver_AutomatonResult, new IntentFilter(
"intent_AutomatonResult"));
}
// callMethodA() is called in the random time. It's just provides randomness
public Handler methodCallerHandler = new Handler();
public Runnable hMyValueTask = new Runnable() {
public void run() {
int n = new Random().nextInt(3000);
System.out.println("A random delay : " + (float) n / 1000
+ " seconds");
callMethodA(new View(getApplicationContext()));
methodCallerHandler.postDelayed(hMyValueTask, (long) n);
}
};
// The actual method who starts everything, it does simply nothing for now.
public void callMethodA(View v) {
System.out.println("MethodA called");
}
// Receives Automaton result from the receiver via BroadcastReceiver
public BroadcastReceiver broadcastReceiver_AutomatonResult = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
string_AutomatonResult = bundle
.getString("automatonResult_Put_String");
System.out
.println("***************************************************************");
System.out.println("** Automaton Result returned to Sender1 : "
+ string_AutomatonResult + "**");
System.out
.println("***************************************************************");
}
}
};
#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 void onDestroy() {
unregisterReceiver(broadcastReceiver_AutomatonResult);
stopService(serviceIntent);
}
}
senderService.java
package com.example.sender;
import java.util.Random;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
//Sends "a" string to the receiver via Broadcast
public class senderService extends Service {
String value = String.valueOf("a");
#Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
mSendValue.removeCallbacks(hMyValueTask);
mSendValue.post(hMyValueTask);
return startId;
}
public Handler mSendValue = new Handler();
public Runnable hMyValueTask = new Runnable() {
public void run() {
publishBuiltinAccelResults(value);
}
};
#Override
public void onDestroy() {
}
public void publishBuiltinAccelResults(String value) {
Intent intent = new Intent("ResultsA");
intent.putExtra("resultA", value);
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Test.aj (Sender's aspect)
package com.example.sender;
import android.app.Activity;
import android.content.Intent;
public aspect Test {
int i = 1;
// pointcut for the callMethodA() execution.
pointcut pointcutCatchMethod(Activity activity) : execution(* callMethodA(*))
&& target(activity);
// a hopeless try for me to cancel the method execution, see below please
pointcut pointcutMethodAExecution() : execution(* callMethodA(*));
// before callMethodA() execution, start sendService which sends string "a"
// to the Receiver
before(Activity activity) : pointcutCatchMethod(activity) {
System.out.println("******" + "Beginning of " + i
+ "th Aspect *************************");
Intent sendIntent = new Intent(activity.getApplicationContext(),
senderService.class);
System.out.println("SenderService is starting");
activity.startService(sendIntent);
System.out
.println(" callMethodA() cought by before aspect , aspect No: "
+ i);
i++;
}
// a hopeless try, for example, here, when string_AutomatonResult is FAIL,
// then I want to cancel callMethodA() execution, then I want also whole
// program to keep running.
Object around() : pointcutMethodAExecution(){
Object result = proceed();
System.out.println("aut res : "
+ Sender1Activity.string_AutomatonResult);
System.out.println("******" + "End of " + i
+ "th Aspect ******************");
return result;
}
}
Receiver Application codes below:
ReceiverActivity.java
package com.example.receiver;
import android.app.Activity;
public class ReceiverActivity extends Activity {
TextView txt_recA;
TextView txt_recB;
TextView txt_packageNumber;
String returningStringInput;
TextView txt_nowReceived;
int state = 1;
String automatonResult = "Init";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Integer pkg_number_int = 0;
setContentView(R.layout.activity_receiver);
txt_recA = (TextView) findViewById(R.id.txt_recA);
txt_recB = (TextView) findViewById(R.id.txt_recB);
txt_nowReceived = (TextView) findViewById(R.id.txt_nowReceived);
txt_packageNumber = (TextView) findViewById(R.id.txt_packageNumber);
registerReceiver(receiverResultsA, new IntentFilter("ResultsA"));
registerReceiver(receiverResultsB, new IntentFilter("ResultsB"));
}
// Broadcast Receiver for the string "a" coming from Sender1.
public BroadcastReceiver receiverResultsA = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String sentStringA = bundle.getString("resultA");
returningStringInput = sentStringA;
AutomatonAB(sentStringA);
txt_recA.setText(sentStringA);
txt_nowReceived.setText("Now Received String : " + sentStringA);
}
}
};
// Ignore this BroadcastReceiver, because I have 2 Senders actually. This is
// for other sender
public BroadcastReceiver receiverResultsB = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String sentStringB = bundle.getString("resultB");
returningStringInput = sentStringB;
AutomatonAB(sentStringB);
txt_nowReceived.setText("Now Received String : " + sentStringB);
txt_recB.setText(sentStringB);
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// unregisterReceiver(receiverResultsPackageNumber);
unregisterReceiver(receiverResultsA);
unregisterReceiver(receiverResultsB);
}
// Automaton for checking the strings coming from the senders. In the end,
// it broadcasts the result to the senders (FAIL or SUCCESS)
public String AutomatonAB(String returningString) {
int stringIntValue = 0;
// to use Java version below than 1.7, 'cause string value
// cannot be used on switch...
if (returningString.equals("a")) {
stringIntValue = 1;
} else if (returningString.equals("b")) {
stringIntValue = 2;
} else {
System.out.println("No input");
}
switch (stringIntValue) {
case 1:
switch (state) {
case 1:
System.out.println("Status : Passing from State 1 to State 2");
state = 2;
System.out.println(" Success ");
// Status : Passing from State 1 to State 2 :
automatonResult = "Success2";
break;
case 2:
System.out
.println("Status : Passing from State2 to Failure State");
state = 3;
System.out.println(" Failure ");
// Status : Passing from State2 to Failure State :
automatonResult = "Failure";
break;
default:
break;
}
break;
case 2:
switch (state) {
case 1:
System.out
.println("Status : Passing from State 1 to Failure State");
state = 3;
System.out.println(" Failure ");
// Status : Passing from State 1 to Failure State :
automatonResult = "Failure";
break;
case 2:
System.out.println("Status : Passing from State 2 to State 1");
state = 1;
System.out.println(" Success ");
// Status : Passing from State 2 to State 1 :
automatonResult = "Success1";
break;
default:
break;
}
break;
default:
break;
}
// to make automaton keep going on the next turns.
if (state == 3) {
state = 1;
}
System.out.println("automata result : " + automatonResult);
txt_packageNumber.setText(automatonResult);
//Broadcast the automaton result to the senders
Intent intent = new Intent("intent_AutomatonResult");
intent.putExtra("automatonResult_Put_String", automatonResult);
sendBroadcast(intent);
return automatonResult;
}
#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;
}
}
I've resolved my problem, using Around advice is the solution,
if we use proceed() then method is going to be executed, if we don't then it is not going to.
if method returns a value, you can manipulate the methods return value in around advice like:
return null.
or if the method is void , then simply don't call the proceed().
So i'm using asmack library to listen for incoming xmpp packets. I've got the service implemented. It's started, bound, a method is run and then it's unbound. The service creates a PacketListener to get incoming messages, and displays a notification when a new message comes in. This all works while the app is the active activity, but doesn't work when it's fully closed (swiped away in the window list) and it's just the service running, the PacketListener doesn't fire. It fires as soon as the app is reopened though, firing off all notifications. I'm looking to get those notifications fired as they come in, instead of the service being suspended, if you will. The code for the service is here:
package com.jayseeofficial.xmpp.service;
import java.io.File;
import java.util.ArrayList;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;
import com.jayseeofficial.xmpp.MainActivity;
import com.jayseeofficial.xmpp.Program;
import com.jayseeofficial.xmpp.R;
import com.jayseeofficial.xmpp.objects.Contact;
import com.jayseeofficial.xmpp.preferences.Preferences;
public class XMPPService extends Service {
private Connection conn = null;
private boolean loggedIn = false;
private final XMPPBinder binder = new XMPPBinder();
private Handler handler;
#Override
public IBinder onBind(Intent arg0) {
handler = new Handler(getMainLooper());
return binder;
}
public class XMPPBinder extends Binder {
public XMPPService getService() {
return XMPPService.this;
}
}
public void logIn() {
new LogInTask().execute();
}
public boolean isLoggedIn() {
return loggedIn;
}
private ConnectionConfiguration getConnectionConfiguration() {
ConnectionConfiguration config = new ConnectionConfiguration(
Preferences.Account.getServer(), Preferences.Account.getServerPort());
config.setSASLAuthenticationEnabled(true);
config.setCompressionEnabled(true);
config.setSecurityMode(SecurityMode.enabled);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
config.setTruststoreType("AndroidCAStore");
config.setKeystoreType("AndroidCAStore");
config.setTruststorePassword(null);
config.setTruststorePath(null);
} else {
config.setTruststoreType("BKS");
String path = System.getProperty("javax.net.ssl.trustStore");
if (path == null) {
path = System.getProperty("java.home") + File.separator + "etc" + File.separator
+ "security" + File.separator + "cacerts.bks";
}
config.setTruststorePath(path);
}
return config;
}
private void showNotification() {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContentTitle("XMPP+").setContentText("running")
.setSmallIcon(R.drawable.speech_bubble);
Intent i = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(i);
// Assign the intent
mBuilder.setContentIntent(stackBuilder.getPendingIntent(9127,
PendingIntent.FLAG_UPDATE_CURRENT));
NotificationManager mgr = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = mBuilder.build();
n.flags |= Notification.FLAG_ONGOING_EVENT;
mgr.notify(1,n);
}
private void hideNotification() {
// TODO Implement hideNotification in XMPPService
}
private class LogInTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
showNotification();
// Set up and log in
conn = new XMPPConnection(getConnectionConfiguration());
conn.connect();
conn.login(Preferences.Account.getUsername(), Preferences.Account.getPassword());
// Set up to receive messages
PacketFilter filter = new PacketTypeFilter(Message.class);
conn.addPacketListener(new XMPPMessagePacketListener(), filter);
conn.sendPacket(new Presence(Type.available));
final ArrayList<Contact> allContacts = new ArrayList<Contact>();
// Populate contact list
for (RosterEntry re : conn.getRoster().getEntries()) {
Log.d("Roster entry: ", re.getUser() + ": " + re.getName());
Contact c = new Contact();
if (re.getName() == null) {
c.setName(re.getUser());
} else {
c.setName(re.getName());
}
c.setAddress(re.getUser());
allContacts.add(c);
}
handler.post(new Runnable() {
#Override
public void run() {
Program.contacts.addAll(allContacts);
}
});
loggedIn = true;
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void ignored) {
if (loggedIn) {
Toast.makeText(XMPPService.this, "Logged in successfully", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(XMPPService.this, "Failed to log in", Toast.LENGTH_LONG).show();
}
}
}
private class XMPPMessagePacketListener implements PacketListener {
#Override
public void processPacket(Packet packet) {
Message m = (Message) packet;
if (m.getBody() != null) {
com.jayseeofficial.xmpp.objects.Message message = new com.jayseeofficial.xmpp.objects.Message();
message.setRecipient(Preferences.Account.getUsername() + "#"
+ Preferences.Account.getServer());
String fullSender = m.getFrom();
String address = fullSender.substring(0, fullSender.indexOf('/'));
message.setSender(address);
message.setContents(m.getBody());
Program.showMessageNotification(message, 9127);
}
}
}
}
and the code for the starting/binding the service is here:
public static void init() {
if (!initialized) {
// Call other portions of init code first
SmackAndroid.init(context);
Preferences.init();
// Set up our variables
contacts = GlazedLists.threadSafeList(new BasicEventList<Contact>());
// Start up the xmpp connection
Intent ixmpp = new Intent(context, XMPPService.class);
context.startService(ixmpp);
context.bindService(ixmpp, xmppConnection, Context.BIND_AUTO_CREATE);
initialized = true;
}
}
So as I said, i want to receive notifications from the service running in the background when the foreground activity is closed. Is there any way of doing this? Maybe have it in it's own process? Something else?
EDIT: the ongoing notification sticks around and works when clicked, in case you're wondering
use startforeground method
http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29
in onCreate of service
public void onCreate() {
startForeground (int id, Notification notification)
}