i want to kill the sms application when it is open. for this purpose i write a service . that checks if sms application is opened. and if it is then it kills this. i am using ActivityManager class. here is my code
but when i launch sms application it nevers ends. why? is it possible ? if yes then please help.
package com.example.activitymanager;
import java.util.List;
import android.app.ActivityManager;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
public class Servicee extends IntentService {
ActivityManager am;
Handler handler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
List<ActivityManager.RunningTaskInfo> list = am
.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : list) {
if (task.baseActivity.getPackageName()
.equals("com.android.mms")) {
am.restartPackage(task.baseActivity.getPackageName());
}
}
handler.postDelayed(this, 5000);
}
};
public Servicee() {
super("");
}
#Override
protected void onHandleIntent(Intent arg0) {
am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
handler.postDelayed(r, 2000);
}
}
I agree with Usman Riaz comment but keep in mind, the process id might change from device to device. I wanted to monitor the tpc traffic of a specific app and id didn't work out in the end. You'll kill some other app or crash the system.
Related
I am working on an android app which will run in androidTv(currently i am using MiBox for my testing purposes)
The requirement is like i need capture the number active notifications received by the android OS and show it somewhere in the APP.
Service which i've written:
package org.libsdl.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Notification;
import android.app.Notification.Action;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import org.haxe.lime.HaxeObject;
public class AndroidNotificationListener extends NotificationListenerService {
private static final int EVENT_UPDATE_CURRENT_NOS = 0;
public static List<StatusBarNotification[]> mCurrentNotifications = new
ArrayList<StatusBarNotification[]>();
public static int mActiveNotificationsCount = 0;
public static StatusBarNotification mPostedNotification;
public static StatusBarNotification mRemovedNotification;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
#Override
public boolean onUnbind(Intent mIntent) {
return super.onUnbind(mIntent);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
updateCurrentNotifications();
mPostedNotification = sbn;
// Get the text from notification
// CharSequence notificationText = sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TEXT);
// Show a toast with your Notification Text
// Toast.makeText(getApplicationContext(), notificationText, Toast.LENGTH_SHORT).show();
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
updateCurrentNotifications();
mRemovedNotification = sbn;
}
public void onListenerConnected() {
// Add some prints here to check if our service is connected to OS or not?
}
private void updateCurrentNotifications() {
try {
StatusBarNotification[] activeNos = getActiveNotifications();
if (mCurrentNotifications.size() == 0) {
mCurrentNotifications.add(null);
}
mCurrentNotifications.set(0, activeNos);
mActiveNotificationsCount = activeNos.length;
} catch (Exception e) {
System.out.println("Anil : AndroidNotificationListener : Should not be here!!");
e.printStackTrace();
}
}
public static StatusBarNotification[] getCurrentNotifications() {
if (mCurrentNotifications.size() == 0) {
return null;
}
return mCurrentNotifications.get(0);
}
}
AndroidManifest.xml part is:
<service
android:name="org.libsdl.app.AndroidNotificationListener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:enabled="true" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
Same service is working for my phone but in my androidTv(MiBox) it is not working.
and as in phone we have settings from where we can enable/disable our app to receive notifications the same option is not available in MiBox.
My MiBox has Android M and my phone has Android N. am i missing something which i should know before running this service in Android service?
So my question is about why this service is not working in androidTv?
any help on this will be much appreciated..
I've found the reason why my dummy app worked on my phone and did not work on miBox.
On my phone, when i installed the dummy app it asked for permission to receive the notification and when i gave the permission it started to receive permission.
On miBox, we do not have any way to give permission to our app to receive notification.
In short, the app was not able to receive the notification on miBox because the app did not have the permission because or listener/app to receive the notification was attached.
and there are no way we can attach the listener for notification to our app in android tvs. But we can do it only when the app is signed as a system app.
if (verifyNotificationPermission()) {
//You have the permission to listen to the System Notification
} else {
//can ask for permission if it not yet granted
// show dialog why you need this permission and if
// user is ok with the permission then call
//openNotificationPermissionPanel
}
fun openNotificationPermissionPanel(){
//Below code will open side panel and will show list of apps and there is a way to unable and disable the Permission
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
}
// fun to check if your launcher app has permission or not
fun verifyNotificationPermission(): Boolean? {
val theList = Settings.Secure.getString(
activity.getContentResolver(),
"enabled_notification_listeners"
)
val theListList = theList.split(":").toTypedArray()
val me = ComponentName(activity, NotificationService::class.java).flattenToString()
for (next in theListList) {
if (me == next) {
return true
}
}
return false
}
I have an Android application, which uploads data into web service using async tasks(P,Q,R) currently starting fired in button click. I have three tables(A,B,C) of data. Currently I upload Table A data in doInBackground in first async task(P), I call second async task(Q) in onPostExecute of first async task(P).In onPostExecute, I update my local tables with returned data and give some UI messages as well. while that functionality is existing, now I want to upload data in a fixed time interval(every 30 minutes) even though the application is closed. when the device is booting up/installing app/updating app, this process should be started.While uploading data, if the user opens the application, upload button should be disabled.I don't necessarily need a long running task that runs forever.
1.Do I need to use services instead async tasks?
and give me advice on this.
To Upload Data do as follow
I think you are pretty new to android, Rather than Asynctasks i think you should move to volley or retrofit which is very easy and very fast when compared to Asynctask
Do I need to use services instead async tasks
Since you need to upload data every 30 mins i suggest you move your code to a service within which you will upload data. Also since a service is used it will work when the app is closed also, as it runs in the background
Your Receiver class
import java.util.Timer;
import java.util.TimerTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class yourReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
int delay = 5000; // delay for 5 sec.5000
int period = 60000; // repeat every 1min.60000
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Intent serviceIntent = new Intent(context,UploadService.class);
context.startService(serviceIntent);
}
}, delay, period);
}
}
Your Service Class
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class UploadService extends Service {
MediaPlayer myPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.sun);
myPlayer.setLooping(false); // Set looping
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
serviceThread = new ServiceThread();
serviceThread.start();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
private class ServiceThread extends Thread {
#Override
public void run() {
synchronized(UploadService.class){
if(uploadStatus) {
uploadStatus = false;
uploadData();
uploadStatus =true;
}
}
}
}
}
I have made an app in which a service runs in the background. But if the android system requires resources, it will stop the service. However I may still require my service to run.
Is it a bad practice to restart the service (if condition relevant to my app still holds true) in the onDestroy method of my service?
How can I make sure my service runs indefinitely (if condition relevant to my app still holds true)? Or atleast on high priority?
Probably the best you can do is use the START_STICKY flag, which tells Android to attempt to restart the service if it has stopped. Beyond that ensure that it consumes as few resources as possible, so that it is less likely to be destroyed.
Android prioritizes the UI over everything. Then processes that are related to the UI. Then processes that are consuming the least amount of resources. A Service runs in the background, so unless it has resources that are also in use on the UI or connected to the UI in some way, it should be a lower priority.
Also you cannot tell Android how to prioritize your Service (everyone would make theirs the "highest priority" right?). So it goes by how well you minimize the impact on overall resources - why kill 3 Services when it could kill 1 and regain all the resources it needs?
To help understand how to manage memory better: http://developer.android.com/training/articles/memory.html
set it START_STICKY. It Causes after killing service the service will restart again. it is my code :
android manifest :
<application
....
<service android:name=".UpdateService" />
</application>
service class :
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.....);
filter.addAction(Intent....);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
Log.i("log", "action Called");
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
receiver class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Log", "recevid");
}
}
in StartupActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context context = getApplicationContext();
Intent service = new Intent(context, UpdateService.class);
context.startService(service);
}
I am working on an application that will notify me (by playing a ringtone) that battery level has reached certain level. Level is configurable. For this I have created an activity that starts a service which in turn registers a receiver for ACTION_BATTERY_CHANGED.
MyActivity -> MyService -> MyBrodcastReceiver [ACTION_BATTERY_CHANGED] -> onReceive() -> if(Battery Level <= MyValue) -> play ringtone
Everything works fine as long as screen is on but as soon as phone is locked and screen goes off or CPU sleeps the broadcast receiver’s onReceive method doesn’t get called and when I unlock phone again everything works. I verified this with logging.
Is it that onReceive method for ACTION_BATTERY_CHANGED gets called only when phone screen is on and stops when phone sleeps?
I even tried using Wake Lock in onReceive method but that didn’t work
[I am testing with ICS (4.0.4)]
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class BatteryMeterService extends Service {
private BatteryStatusReceiver batteryStatusReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatusReceiver = new BatteryStatusReceiver(null);
registerReceiver(batteryStatusReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryStatusReceiver);
}
}
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import com.amol.bm.BatteryMeterUtility.NotificationInfo;
public class BatteryStatusReceiver extends BroadcastReceiver {
private BatteryMeterUtility batteryMeterUtility;
public BatteryStatusReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float fPct = (level / (float)scale) * 100;
int levelPct = (int)fPct;
boolean prefAlertLowBattery = sharedPrefs.getBoolean("prefAlertLowBattery", true);
if(prefAlertLowBattery) {
String prefAlertLowBatteryValue = sharedPrefs.getString("prefAlertLowBatteryValue", "20");
int lowBatteryValue = Integer.parseInt(prefAlertLowBatteryValue);
if(levelPct <= lowBatteryValue && iStatus != BatteryManager.BATTERY_STATUS_CHARGING) {
notificationInfo.icon = R.drawable.low_battery;
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BM WakeLook");
wakeLock.acquire();
batteryMeterUtility.playAlertRingtone(alertRingtone);
wakeLock.release();
}
}
}
}
You should give WAKE_LOCK Permission to your service running in background so that even when the phone is Idle or goes off your service keeps on running. hope you got it let me know if unclear
Finally I used Alarm Manager with RTC_WAKEUP to solve this problem. http://developer.android.com/reference/android/app/AlarmManager.html
I want to make an functionality, like reminder, in Android.
I want to start-up my app/activity, when it is not running, or its UI is invisible.
It is some-thing like same as reminder, that wakes ups the app at desired time.
I have not worked with any type of background task or service,
so I haven't any idea that what to do,
or what type of classes or demos should be studied by me?
Can any one give me some suggestions with demos or tutorials links.
Thanks, in advance.
Hi use the following code. This is service. By using pending Intent with alarm manager you can open your UI at your needed time.
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ScheduleCheckService extends Service{
private Timer timer;
final int REFRESH=0;
Context context;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
context=this;
//==============================================
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
void PendingIntentmethod()
{
Intent myIntent = new Intent(context, YOURCLASS.class);
pendingIntent = PendingIntent.getActivity(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
}
}
Start the service and stop the service when you want and also dont forget to register it in manifest file.
Have a look at the Android Service class.
http://developer.android.com/reference/android/app/Service.html
From this Service you can periodically start (using a TimerTask) an Intent to open your App or just set a Notification, from which the user can open the App with the desired Activity. I would prefer the second option, because he user doesn't want an Application just to be opened at some time.
Here is a simple Service Tutorial:
http://www.vogella.com/articles/AndroidServices/article.html