Start service on boot: why it doens't work? - java

I would like to start a service when the phone boot but does not work and I do not understand why. In my Package i created a class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootPhone extends BroadcastReceiver{
Intent intent;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
intent = new Intent(context, Service.class);
context.startService(intent);
}
}
My Service.class is
public class Service extends Service{
Notify notify;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
notify = new Notify(this);
}
}
In my Manifest i put
<service android:name="Servicer"></service>
<receiver android:name="BootPhone"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
But, why it does'n work? Where is the problem/error?

you have to declare user permission in manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Related

I created a service in Java but it doesn't run in the background

I am trying to create a simple service in java that will run in the background. I want to play a song on the phone even though the app is closed. I read some articles and watched tutorials but my service still stops when I close the app.
1) I changed my manifest
<service
android:name="com.example.myapplication.ServiceSound"
android:exported="true"
android:enabled="true">
</service>
2) I returned START_STICKY
This is manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.myapplication.ServiceSound"
android:exported="true"
android:enabled="true">
</service>
</application>
This is the service
public class ServiceSound extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
And this is how I start the service in MainActivity.java
startService(new Intent(getBaseContext(),ServiceSound.class));
I think you need Broadcast Receiver.
So now
1- Create broadcast receiver class and call your Service class.
public class MyBroadcaseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,ServiceSound.class));
Log.e(TAG, "onReceive: BroadCast is started");
}
}
2- Your Service class define this
public static String str_receiver = "Your_Package_Name.receiver";
on startCommand start your broadcast class
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.start();
return START_STICKY;
Intent intent1 = new Intent(this,MyBroadcaseReceiver.class);
sendBroadcast(intent1);
return START_STICKY;
}
Now in your MainActivity class create an object for broadcast
private BroadcastReceiver broadcastReceiver;
inside onCreate() define the object
broadcastReceiver = new MyBroadcaseReceiver();
Finaly call onResume() and onPause() inside the MainActivity.
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(MyService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
Don't forget to call broadcast reciever in your Manifest file
<receiver android:name=".MyBroadcaseReceiver"></receiver>

How to trigger a service to start at a certain date and time?

This is my activity class:
public class activity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Intent i = new Intent(activity.this, Service.class);
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar c=Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,mHour);
c.set(Calendar.MINUTE,mMinute);
c.set(year,month,date);
c.setTimeInMillis(System.currentTimeMillis());
aManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pIntent);
Toast.makeText(getApplicationContext(), "Service triggered", Toast.LENGTH_SHORT).show();
startService(i);
}
}
And this is my service class:
public class Smscreator extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
// TODO Auto-generated method stub
Context context=getApplicationContext();
Toast.makeText(context, "This is the service.",
Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
This is my Manifest class:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application
<service
android:name=".Service"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".activity"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The variables mHour,mMinute,year,month and date are certain values for the date and time that depends on the user.
Now when I execute this code, the service gets triggered instantly; it completely ignores the date and time specified by the user. Can someone please help me with this?
Edit: I am currently working on Android M.

How to use implicit broadcast PACKAGE_ADDED in Oreo (8.0)?

I have to receive system-sent implicit broadcasts (ACTION_PACKAGE_ADDED) to detect the installation of the application and perform some code. I used the code below:
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// It will trigger when any app is installed
Uri data = intent.getData();
String packageAdv = data.getEncodedSchemeSpecificPart();
//some code...
}
}
In my Manifest file I declared my receiver:
<receiver android:name="com.myapp.Receiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<data android:scheme="package"/>
</intent-filter>
</receiver>
It works perfect before Version 8.0 Oreo. Now, I have to make my receiver explicit by using registerReceiver. How can I do this? Sample code would be appreciated.
I have decided to create a simple service for listening to PACKAGE_ADDED event.
public class MyService extends Service {
private BroadcastReceiver receiver;
public MyService() { }
#Override
public void onCreate() {
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addDataScheme("package");
receiver = new Receiver();
registerReceiver(receiver, intentFilter);
}
//ensure that we unregister the receiver once it's done.
#Override
public void onDestroy() {
unregisterReceiver(receiver);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Also, I needed to declare my service in manifest file:
<service
android:name="com.nolesh.myapp.MyService"
android:enabled="true">
</service>

Android - Can not Receive Push from Parse.com

I have parse notifications set up for my android app using Parse 1.7.1 sdk version.
But in the new android this method with parse says to call is depreciated.
PushService.setDefaultPushCallback(this, MainActivity.class);
But when it is removed the notification is sent from parse.com as I can see on the website but it does not arrive to the phone?
How can this be changed so that the push will arrive? Without using the depreciated method?
Thanks for the help in advance.
Try extending ParsePushBroadcastReceiver class and and use its
OnPushRecieve (to do something before notification is shown in status bar)
OnPushOpen (to do some action when user open's push for example open an activity)
getNotification and
onPushDismiss methods
And in manifest file replace
<receiver android:name="com.parse.ParsePushBroadcastReceiver" android:exported="false">
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
with this :
<receiver
android:name="com.example.parse.Notifications.NotificationsReciever"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
And if you want to open an activity onPushOpen, here is a sample:
#Override
protected void onPushOpen(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent i = new Intent(context, PushNotificationHandler.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
Here is a sample class that extends ParsePushBroadcastReciever class
public class NotificationsReciever extends ParsePushBroadcastReceiver {
#Override
protected Class<? extends Activity> getActivity(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
return ParseStarterProjectActivity.class;
}
#Override
protected Notification getNotification(Context context, Intent intent) {
// TODO Auto-generated method stub
return super.getNotification(context, intent);
}
#Override
protected void onPushDismiss(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onPushDismiss(context, intent);
}
#Override
protected void onPushOpen(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent i = new Intent(context, PushNotificationHandler.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#Override
protected void onPushReceive(Context context, Intent intent) {
//here You can handle push before appearing into status e.g if you want to stop it.
super.onPushReceive(context, intent);
}
}

Switch between activities in Android

I want the user to be able to tap a button and be taken to a different activity. I've used similar code before in another app, but every time I press the button now the app crashes. In the main menu I have:
Button testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("de.vogella.android.c2dm.simpleclient.TEST"));
}
});
In the manifest:
<activity
android:name=".TestClass"
android:label="#string/app_name" >
<intent-filter>
<action android:name="de.vogella.android.c2dm.simpleclient.TEST" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
TestClass.java is:
package de.vogella.android.c2dm.simpleclient;
import android.app.Activity;
import android.os.Bundle;
public class TestClass extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Try this: In the onClick modify your first class to this:
Button testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
final ClassName changeAct = this;
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
i.setClass(changeAct, TEST.class); //Change TEST.class to the name of the class you want it to go to.
startActivity(i);
stop();
}
});
Intent intent = new Intent (CurrentActivity.this, TestClass.class);
startActivity(intent);
If your TestClass is in another package just put your package in front.
Intent intent = new Intent (CurrentActivity.this, de.vogella.android.c2dm.simpleclient.TestClass.class);
startActivity(intent);
Declare the activity in manifest like this:
<activity
android:name="de.vogella.android.c2dm.simpleclient.TestClass"
</activity>

Categories

Resources