How to start my application process when a android device is rebooted? - java

I am making app which tracks user location continuously, so far I have been able to make a successful receiving of its ordinate on location change, but if he is restarting the phone than I am not able to start my service without user again opening the app.
This is my Servicesstart.java code
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("service started", "start");
userFunctions = new UserFunctions();
final LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(userFunctions.isUserLoggedIn(getApplicationContext())){
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei=telephonyManager.getDeviceId();
Toast.makeText(getApplicationContext(), imei, 5000).show();
if(Broadcast.check==false)
{
final UserFunctions userFunction = new UserFunctions();
LocationListener locatioListner = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
get();
}
public void onLocationChanged(Location location) {
Log.i("location", "loc");
String latitude=String.valueOf(location.getLatitude());
String longtitude=String.valueOf(location.getLongitude());
//location updated starts here
boolean check_update=userFunction.locationUpdater(UserFunctions.email, latitude, longtitude,imei);
if(check_update==true){
Log.i("updated", "update");
}
else
{
Log.i("notupdated","not");
}
}
};
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locatioListner);
}
}
}
this is my Broadcast.java code
public class Broadcast extends BroadcastReceiver {
public static boolean check=true;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
check=false;
Intent i = new Intent(context,Servicestart.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(i);
}
}
}
This my manifest.xml code
<service android:name=".Servicestart">
</service>
<receiver android:name=".Broadcast"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Add this permission in manifest and add this broadcast receiver class in your application.
I have added my service ServiceStarter to start first, replace this with yours
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("Reciver Started..........................................");
Intent activate = new Intent();
activate.setClass(context, **ServiceStarter.class**);
// activate.putExtra("Auto", true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, activate,
Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 20000, pendingIntent);
}
}

Related

Alertdialog on outgoing call not working. CallBlocker implementation failed

Below is my code that I am using for displaying alert during outgoingcall. But the problem is it is not working.
Picked up from https://github.com/dharmikvyas/CallBlocker
I just need to implement it in my project
Thanks in advance for your help!
CallBarring.java
public class CallBarring extends BroadcastReceiver {
// This String will hold the incoming phone number
private String number;
CustomDialog dialog;
TelephonyManager telephonyManager;
PhoneStateListener listener;
Context context;
#Override
public void onReceive(final Context context, Intent intent) {
// If, the received action is not a type of "Phone_State", ignore it
if (!intent.getAction().equals("android.intent.action.PHONE_STATE"))
return;
// Else, try to do some action
else {
this.context = context;
if(dialog == null){
dialog = new CustomDialog(context);
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
// Fetch the number of incoming call
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
dialog.dismiss();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
dialog.dismiss();
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
dialog.show();
break;
}
Toast.makeText(context, stateString,Toast.LENGTH_LONG).show();
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
// Check, whether this is a member of "Black listed" phone numbers
// stored in the database
/*if (MainActivity.blockList.contains(new Blacklist(number))) {
// If yes, invoke the method
disconnectPhoneItelephony(context);
return;
}*/
}
}
// Method to disconnect phone automatically and programmatically
// Keep this method as it is
#SuppressWarnings({ "rawtypes", "unchecked" })
private void disconnectPhoneItelephony(Context context) {
ITelephony telephonyService;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
class CustomDialog extends Dialog implements OnClickListener {
public CustomDialog(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
Button btnEndCall = (Button) findViewById(R.id.end_call);
//btnEndCall.set
btnEndCall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
disconnectPhoneItelephony(context);
}
}
below is my Androidmanifest.xml
All the permissions seem to be ok.
<receiver android:name=".CallBarring" >
<intent-filter android:priority="100" >
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

SharedPreferences getSharedPreferences always returns previous value even it has been changed

I have a service that is started when the main activity starts. I call the Service using this code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, CheckService.class));
finish();
}
The Service has the following code:
public class CheckService extends Service {
private static final String TAG = "CheckService";
WakeLock wakeLock;
public CheckService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
// TODO Auto-generated method stub
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
//Restart the service once it has been killed android
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 100, restartServicePI);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
Log.e("Checker", "Service Created");
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
check_pref();
}
}, 0, 5000);
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("YouWillNeverKillMe"));
}
public void check_pref( ) {
Context con;
Log.e("check_pref", "Restarting");
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("chmod -R 0777 /data/data/com.my.project.app/\n");
dos.writeBytes("exit\n");
dos.flush();
dos.close();
p.waitFor();
p.destroy();
con = createPackageContext("com.my.project.app", 0);
SharedPreferences pref = con.getSharedPreferences("myprefs", 0);
String login_id = pref.getString("login", "");
System.out.println(login_id);
} catch (PackageManager.NameNotFoundException e)
{
Log.e("check_pref", e.toString());
}
catch (NullPointerException e){
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
Every 5 seconds in my service runs method check_pref(), which checks login in another app (com.my.project.app) and prints it in Logcat. But even login has been changed it returns same value as previously. Only if I restart app it returns actual value. My device(android 5.1.1) is rooted and I allowed permissions for my app. Whats wrong with my code? How to make it always return the actual value, which located in /data/data/com.my.project.app/myprefs.xml ?
PS. I found a solution. I changed
SharedPreferences pref = con.getSharedPreferences("myprefs", 0);
to
SharedPreferences pref = con.getSharedPreferences("myprefs", MODE_MULTI_PROCESS); and it works now.
I changed
SharedPreferences pref = con.getSharedPreferences("myprefs", 0);
to
SharedPreferences pref = con.getSharedPreferences("myprefs", MODE_MULTI_PROCESS);
and it works now.

Activity is opening multiple times using broadcast receiver

I am developing android app which work as battery indicator, open activity when battery low or full.
It works fine when i call finish() in Main activity from onCreate event after start of service.
but when i comment finish method it open activity multiple times, which i open from BroadCast receiver.
Here is MainActivity Code:
public class Main extends Activity {
private MyService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (service == null) {
Intent i = new Intent(this, MyService.class);
startService(i);
}
finish();
}}
Here is my service code:
I think i am doing something wrong when i start Activity.
At line
getApplication().startActivity(intent);
Complete Service Code is:
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand");
// do not receive all available system information (it is a filter!)
final IntentFilter battChangeFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
// register our receiver
this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
checkBatteryLevel(intent);
}
};
private void checkBatteryLevel(Intent batteryChangeIntent) {
// some calculations
final int currLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_LEVEL, -1);
final int maxLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_SCALE, -1);
final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);
if(percentage==100)
{
Intent intent = new Intent(getBaseContext(), Last.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
}
if(percentage==15)
{
Intent intent = new Intent(getBaseContext(), Last.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
}
}}
And this is my last "Last.cs" activity which is opening multiple time.
but it works fine when i call finish() into Main Activity.
public class Last extends Activity {
Button btnCancel;
Uri notification;
Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
btnCancel = (Button) findViewById(R.id.stopsound);
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
r.stop();
}
});
} }
Make your Last activity launchMode as singleTask in Manifest
<activity
android:name=".Last"
android:configChanges="orientation|screenSize"
android:launchMode="singleTask"
>
</activity>

Android IntentService for Notifications

I'm trying to make a service, that is completely independent from the activity and running all the time in background to send the notification about incoming event. I have solved the problem of service killing along with activity by returning START_STICKY value in onStartCommand. It works well, but then I have problem with sending notifications. The problem is in the setSmallIcon method. When i pass there the reference to R.drawable.ic_launcher, I have got error, which says, that icon == 0. Is there any way to make it work properly?
Here is my NotificationService.java
public class NotificationService extends IntentService {
private static final int UPDATE_TIME = 60 * 1000;
private ArrayList<Group> groups;
public NotificationService() {
super("NotficationService");
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
private void showNotification(String name, int remindTime) {
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification n = new Notification.Builder(this)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setContentIntent(pIntent)
.setSmallIcon(android.R.drawable.ic_delete)
.setSound(sound)
.setAutoCancel(true)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
#Override
protected void onHandleIntent(Intent intent) {
while(true) {
checkForNotification();
try {
Thread.sleep(UPDATE_TIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try using:
.setSmallIcon(Resources.getSystem().getDrawable(android.R.drawable.ic_delete))
instead of
.setSmallIcon(android.R.drawable.ic_delete)

Android AlarmManager Start a service with ringtone

I am working on Alarm Manager. I used a service to start and will ring a tone. But the service is not starting. Can anyone suggest about service, Pending Intent and identify the error in my code. The code is copied from net.
This is my AndroidScheduledActivity.java
public class AndroidScheduledActivity extends Activity {
private PendingIntent pendingIntent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStart = (Button) findViewById(R.id.startalarm);
Button buttonCancel = (Button) findViewById(R.id.cancelalarm);
buttonStart.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(AndroidScheduledActivity.this,
MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidScheduledActivity.this,
0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
Toast.makeText(AndroidScheduledActivity.this, "Start Alarm",
Toast.LENGTH_LONG).show();
Log.d("Alarm", "Alarm Started");
}
});
buttonCancel.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(AndroidScheduledActivity.this, "Cancel!",
Toast.LENGTH_LONG).show();
}
});
}
}
And this is my MyAlarmService.java
public class MyAlarmService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
#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();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("AlarmService", "Alarm Starting to ring");
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(getBaseContext(), alert);
mp.setVolume(100, 100);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(400);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
And my menifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarm_basic"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.alarm_basic.AndroidScheduledActivity"
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=".MyAlarmService" />
</application>
</manifest>
Also need to check wheather Ringtone is null also.
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone r = RingtoneManager.getRingtone(getBaseContext(), alert);
if(r == null){
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
r = RingtoneManager.getRingtone(getBaseContext(), alert);
if(r == null){
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getBaseContext(), alert);
}
}
if(r != null)
r.play();
Or otherway
MediaPlayer mp = MediaPlayer.create(getBaseContext(), alert);
if(mp !=null) {
mp.setVolume(100, 100);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
Try it, and let me know what happen...
In your manifest.xml file
<service android:enabled="true" android:name=".ServiceClass" />
Add a permission in your Manifest file
< uses-permission android:name="android.permission.VIBRATE" />
Should check vibrator is null or not.
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrator != null)
vibrator.vibrate(400);

Categories

Resources