I design alarm manager with repeated in specific time. But when I cancel it on on click method after seconds(time Interval) service start automatically itself.
I want activate service on button click and repeat in interval. and after restaring phone wants to start service too.
any Idea?
here its my manifest code :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarm"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" android:enabled="true"/>
<receiver android:name=".BootCompleteReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".AlarmService" />
</application>
</manifest>
My AlarmReceiver :
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "BANANEALARM";
private static final int NOTIFICATION_ID = 1;
Intent intent;
PendingIntent pendingIntent;
NotificationManager notificationManager;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "starttt", Toast.LENGTH_LONG).show();
// if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Log.d(TAG, "in onreceive");
Intent service1 = new Intent(context, AlarmService.class);
context.startService(service1);
// }
}
}
My BootCompleteReceiver
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Toast.makeText(context, "Boot", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
this.scheduleAlarms(context, calendar);
}
}
private void scheduleAlarms(Context ctxt, Calendar c) {
AlarmManager alarManager = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, AlarmService.class);
PendingIntent pi = PendingIntent.getService(ctxt, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
alarManager.setRepeating(AlarmManager.RTC,c.getTimeInMillis(),getInterval(), pi);
}
private int getInterval(){
int days = 0;
int hours = 0;
int minutes = 1;
int seconds = 60;
int milliseconds = 1000;
int repeatMS = minutes* seconds * milliseconds;
return repeatMS;
}
}
And my MainActivity :
public class MainActivity extends Activity {
private static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
NotificationManager notificationManager;
Button btn,btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setAlarm();
}
});
btn2=(Button)findViewById(R.id.stop_s);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopservice();
}
});
}
public void stopservice()
{
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(MainActivity.this , "Cancel!", Toast.LENGTH_LONG).show();
}
public void triggerAlarm(View v){
setAlarm();
}
public void setAlarm(){
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setAction("com.example.alarm.ACTION");
PendingIntent pendingIntent = PendingIntent
.getBroadcast(MainActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
AlarmManager alarm = (AlarmManager) MainActivity.this
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
getInterval(), pendingIntent);
Log.d(TAG,"alarmStartTime: " );
}
private int getInterval(){
int days = 0;
int hours = 0;
int minutes = 1;
int seconds = 60;
int milliseconds = 1000;
int repeatMS = minutes* seconds * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
cancelNotifications();
setAlarm();
}
public void cancelNotifications(){
notificationManager.cancelAll();
}
}
In your stopservicemethod, codealarmManager.cancel(pendingIntent), the pendingIntent is always null.
Try replace
PendingIntent pendingIntent = PendingIntent
to
pendingIntent = PendingIntent
in your setAlarm method.
Hope it helps.
Related
I'm creating an app. which is always wants to trigger when the phone call states changes (Phone state listener), but my Broadcast receiver killed by Android after a few minutes So I created a Foreground service to keep the app running in the background, but the thing is After I installed the app I start the foreground service in the MainActivity through button click, then if the broadcast receiver triggers my foreground service stops. I think Service and Broadcast receiver using the same thread I guess. How can I Archive that I below coding
Manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<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"></activity>
<activity android:name=".MainActivity2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- This part is inside the application -->
<service android:name=".HammerService" android:enabled="true" />
<receiver
android:name=".CallReceiver"
android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
</application>
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.button);
checkAndRequestPermissions();
final Intent serviceIntent = new Intent(this, HammerService.class);
serviceIntent.putExtra("inputExtra", "Call Hammer ");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ContextCompat.startForegroundService(MainActivity.this, serviceIntent);
}
}
});
}
private boolean checkAndRequestPermissions() {
int readPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int read_call_log = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG);
List listPermissionsNeeded = new ArrayList<>();
if (readPhoneState != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
}
if (read_call_log != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CALL_LOG);
}
if (read_call_log != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
}
if (read_call_log != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.INTERNET);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
(String[]) listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
> App
public class App extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
HammerService
public class HammerService extends Service {
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground() {
// String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "Call Hummer Background Service";
NotificationChannel chan = new NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_android)
.setContentTitle("Call Hammer Service")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Call Hammer Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
CallReciverclass
public class CallReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
try {
runfirstTime(context,intent);
Toast.makeText(context, "1st", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
try {
}
catch (Exception e)
{
}
}
}
}
I want to start the Alarm Manager when hour and minute are set in the Application, But in my code the alarm is not starting once set.
I am not sure if it is not matching the time with my device or if there is any other issue with my code. Any help will be greatly appreciated.
Here is my code:
public class Alarmactivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static Alarmactivity inst;
private TextView alarmTextView;
public static Alarmactivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(Alarmactivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(Alarmactivity.this, 0, myIntent, pendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}}
AlarmReceiver.java
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
Alarmactivity inst = Alarmactivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}}
AlarmService.java
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Alarmactivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}}
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Alarmactivity"
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=".AlarmService"
android:enabled="true" />
<receiver android:name=".AlarmReceiver" />
</application>
Try this, it worked for me:
MainActivity.class
public class MainActivity extends AppCompatActivity
{
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static MainActivity inst;
private TextView alarmTextView;
public static MainActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
// setAlarmText("");
Log.d("MyActivity", "Alarm Off");
}
}
}
AlarmReceiver.class
public class AlarmReceiver extends WakefulBroadcastReceiver
{
#Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
MainActivity inst = MainActivity.instance();
//inst.setAlarmText("Alarm! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmService.class
public class AlarmService extends IntentService
{
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification myNotication;
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setAutoCancel(false);
//builder.setTicker("this is ticker text");
builder.setContentTitle("Alarm Notification");
builder.setContentText("Alarm Playing");
builder.setSmallIcon(R.drawable.mail2);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
}
How can I get the method in my BroadcastReceiver into my Fragment?
Or is it even possible?
receiver:
public class Receiver extends BroadcastReceiver {
public void test(Context c) {
....
}
}
Fragment:
public class Test extends Fragment {
...
}
So a error appeared:
Attempt to invoke virtual method 'android.content.Context
android.content.Context.getApplicationContext()' on a null object
reference
at
com.test.tab.MyReceiver.sendNotificationIfTimeEnd01(MyReceiver.java:47)
at com.test.tab.Juli.broadcastIntent(Juli.java:54)
at com.test.tab.Juli.onCreateView(Juli.java:188)
The code for those lines are:
in Receiver:
public void sendNotificationIfTimeEnd01(Context c) {
Context context = c.getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
....
}
and in Fragment:
receiver.sendNotificationIfTimeEnd01(context);
broadcastIntent();
EDIT UPGRADED CODE:
Fragment:
public class FragmentTest extends Fragment {
private Context context;
IntentFilter filter = new IntentFilter("com.example.Broadcast");
MyReceiver receiver = new MyReceiver();
// Call this method when the condition is met.
public void broadcastIntent() {
Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
getActivity().sendBroadcast(intent);
}
...
if (diffDays <= 0 && diffHours <= 0 && diffMinutes <= 0) {
((TextView) android.findViewById(R.id.test)).setText("test works");
if (!notification043 && !buttonColor01.equals("red01")) {
broadcastIntent();
editor.putBoolean("notification43", true);
editor.apply();
}
}
}
MyReceiver:
public class MyReceiver extends BroadcastReceiver {
public static final int NOTIFICATION_ID_01 = 1;
#Override
public void onReceive(Context context, Intent intent) {
sendNotificationIfTimeEnd01(context);
}
public void sendNotificationIfTimeEnd01(Context c) {
Context context = c.getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
PendingIntent pendingIntent01 = PendingIntent.getActivity(context, 1, intent01, 0);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pendingIntent01)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.ic_launcher))
.setContentTitle(testArray[0])
.setContentText("testready")
.setSubText("click here");
NotificationManager notificationManager =
(NotificationManager) c.getSystemService(c.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID_01, builder.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(c.getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Actually, you could use Intents :
public class Test extends Fragment {
...
// Call this method when the condition is met.
public void broadcastIntent() {
Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
getActivity().sendBroadcast(intent);
}
}
And declare that your broadcast receiver can react to this kind of Intent either through the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.BroadcastDetector"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.example.Broadcast" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
or programmatically
IntentFilter filter = new IntentFilter("com.example.Broadcast");
MyReceiver receiver = new MyReceiver();
getActivity().registerReceiver(receiver, filter);
Then you can intercept this Intent in the receiver :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
}
}
I want to get data in background and automatic and in the interval of time,
I use this but not work does not work correctly
AndroidManifest.xml
.
.
.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
.
.
.
<service
android:name=".NewsServiceReceiver"
android:icon="#drawable/ic_launcher"
android:label="#string/service_name" >
</service>
<receiver
android:name=".NewsReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<receiver android:name=".NewsStartReceiver" >
</receiver>
NewsReceiver.java
public class NewsReceiver extends BroadcastReceiver {
private static final long REPEAT_TIME = 1000 * 30;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, NewsStartReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
}
}
NewsStartReceiver.java
public class NewsStartReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent service = new Intent(context, NewsServiceReceiver.class);
context.startService(service);
}
}
NewsServiceReceiver.java
public class NewsServiceReceiver extends Service {
.
.
.
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(DBAdapter.TAG, "[*******-----------> BACKGROUND <-----------*******]");
//My Code Here
return Service.START_NOT_STICKY;
}
}
i want run NewsServiceReceiver.java in background when internet connect or app run As well as run automatic in the interval of time!?
my problem solve with
Autostart.java
public class Autostart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent alarm = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
System.out.println("[*******-----------> Autostart <-----------*******]");
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15000, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, NewsServiceReceiver.class);
context.startService(background);
}
}
NewsServiceReceiver.java
public class NewsServiceReceiver extends Service {
private boolean isRunning;
private Context contex;
private Thread backgroundTread;
#Override
public IBinder onBind(Intent intent){
return null;
}
#Override
public void onCreate(){
this.contex = this;
this.isRunning = false;
this.backgroundTread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("[*******-----------> BACKGROUND <-----------*******]");
//------------My Code Here--------------
stopSelf();
}
};
#Override
public void onDestroy(){
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning){
this.isRunning = true;
this.backgroundTread.start();
}
return START_STICKY;
}
}
SplashActivity.java -> May first Activity when app run
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
-
this.context=this;
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15000, pendingIntent);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<service
android:name=".NewsServiceReceiver"
android:enabled="true" >
</service>
<receiver
android:name=".Autostart"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<receiver android:name=".AlarmReceiver" >
</receiver>
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);