My Code,
public class SecondTextView extends Service {
private BroadcastReceiver mReceiver;
private boolean isShowing = false;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private WindowManager windowManager;
private ImageView floatIcon;
WindowManager.LayoutParams params;
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
//add floatIcon and its properties;
/* floatIcon = new TextView(this);
floatIcon.setText("Hello There!");
floatIcon.setTextColor(ContextCompat.getColor(this, android.R.color.white));
floatIcon.setTextSize(32f);*/;
floatIcon = new ImageView(this);
floatIcon.setImageResource(R.drawable.home);
floatIcon.setClickable(true);
//set parameters for the floatIcon;
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP|Gravity.CENTER_HORIZONTAL;
//Register receiver for determining screen off and if user is present;
mReceiver = new LockScreenStateReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public class LockScreenStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//if screen is turn off show the floatIcon;
if (!isShowing) {
windowManager.addView(floatIcon, params);
isShowing = true;
}
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
//Handle resuming events if user is present/screen is unlocked remove the floatIcon immediately;
if (isShowing) {
windowManager.removeViewImmediate(floatIcon);
isShowing = false;
}
}
}
}
#Override
public void onDestroy() {
//unregister receiver when the service is destroy;
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
//remove view if it is showing and the service is destroy;
if (isShowing) {
windowManager.removeViewImmediate(floatIcon);
isShowing = false;
}
super.onDestroy();
}
}
I Used this code but give error and crash my application with
android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#bed76c6
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.imageonlockscreen" >
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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=".SecondTextView"/>
<service android:name=".FloatIcon"/>
</application>
Related
I'm making a music player, and there was a problem when switching to the next song. When the phone is in working condition (the screen is on) the tracks switch smoothly, when the screen is off there is a long pause, the song starts only after a long time (very long!!!) or when the screen is turned on. Also, everything works well with a headset (Bluetooth), songs switch smoothly even when the screen is turned off. I use MediaPlayer.prepare to prepare the track (music files are taken from the SD card, so I don't see any point in using MediaPlayer.prepareAsync()). Songs are played using Service. Since the player works fine when the screen is turned on and poorly when it is turned off, then this is the problem. I tried everything, searched all the articles about media player in Russian and English, reviewed YouTube. Help is also accepted on Kotlin.
(here is the same question. but there is no answer. How to use wake lock for android mediaplayer?)
Below is the code:
public class MusicService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener {
IBinder mBinder = new MyBinder();
private MediaPlayer mediaPlayer = null;
private Uri uri;
private int position = POSITION_PLAY;
public static AudioManager audioManager;
int result;
private NotificationReceiver notificationReceiver;
#Override
public void onCreate() {
super.onCreate();
notificationReceiver = new NotificationReceiver();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
return;
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(notificationReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
releaseMP();
unregisterReceiver(notificationReceiver);
audioManager.abandonAudioFocus(this);
Log.e(TAG, "onDestroy()");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class MyBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(myPosition != -1){
playMedia(myPosition);
}
return START_STICKY;
}
public void createMediaPlayer(int positionInner) {
position = positionInner;
uri = Uri.parse(musicFiles.get(position).getPath());
mediaPlayer = null;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
} catch (IOException ioException) {
ioException.printStackTrace();
}
prepare();
}
private void playMedia(int position) {
if(mediaPlayer != null) {
mediaPlayer.stop();
releaseMP();
}
createMediaPlayer(position);
mediaPlayer.start();
}
public void prepare() {
try {
mediaPlayer.prepare();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
void showNotification(int playPauseBtn){
...
startForeground(2, notification);
if(!isGoing && IS_LIVE) {
stopForeground(false);
}
}
void OnCompleted(){
mediaPlayer.setOnCompletionListener(this);
}
void OnPrepared() { mediaPlayer.setOnPreparedListener(this);}
#Override
public void onCompletion(MediaPlayer mp) {
if(actionPlaying != null){
actionPlaying.nextBtnClicked();
if(mediaPlayer != null){
mediaPlayer.start();
OnCompleted();
}
}
}
private void releaseMP() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
public void start() {
mediaPlayer.start();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void stop() {
mediaPlayer.stop();
}
public void pause() {
mediaPlayer.pause();
}
public void release() {
releaseMP();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public void seekTo(int position) {
mediaPlayer.seekTo(position);
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
}
Code for the method:
public void nextBtnClicked() {
if(musicService.isPlaying()) {
musicService.stop();
musicService.release();
if(SHUFFLE && !REPEAT){
POSITION_PLAY = getRandom(ListSongs.size() - 1);
}
else if(!SHUFFLE && !REPEAT){
POSITION_PLAY = ((POSITION_PLAY + 1) % ListSongs.size());
}
uri = Uri.parse(ListSongs.get(POSITION_PLAY).getPath());
musicService.createMediaPlayer(POSITION_PLAY);
if(is_live_player_activity) {
metaData(uri);
}
musicService.OnCompleted();
musicService.showNotification(R.drawable.ic_pause);
playPauseBtn.setBackgroundResource(R.drawable.ic_pause);
musicService.start();
}
else {
musicService.stop();
musicService.release();
if(SHUFFLE && !REPEAT){
POSITION_PLAY = getRandom(ListSongs.size() - 1);
}
else if(!SHUFFLE && !REPEAT){
POSITION_PLAY = ((POSITION_PLAY + 1) % ListSongs.size());
}
uri = Uri.parse(ListSongs.get(POSITION_PLAY).getPath());
musicService.createMediaPlayer(POSITION_PLAY);
if(is_live_player_activity) {
metaData(uri);
}
musicService.OnCompleted();
if(FLAG){
musicService.showNotification(R.drawable.ic_pause);
playPauseBtn.setBackgroundResource(R.drawable.ic_pause);
} else {
musicService.showNotification(R.drawable.ic_play);
playPauseBtn.setBackgroundResource(R.drawable.ic_play);
}
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.music">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<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:name=".ApplicationClass"
android:screenOrientation="portrait"
android:theme="#style/Theme.Music">
<activity android:name=".MusicActivity"
android:screenOrientation="portrait"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
<service android:name=".MusicService" android:enabled="true"/>
<receiver android:name=".NotificationReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
<action android:name="actionprevious" />
<action android:name="actionnext" />
<action android:name="actionplay" />
</intent-filter>
</receiver>
</application>
</manifest>
I found a problem. It was necessary to call MediaPlayer.setwakemode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
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)
{
}
}
}
}
my broadcast receiver is working fine on Pause() function but when i kill my app my broadcast receiver stops listening only in oreo but working fine on other API Levels less then oreo. i also registered my broadcast receiver in my manifest file and also registered it on my resume().
My Main Activity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, BroadcastService.class));
Log.i(TAG, "Started service");
}
#Override
public void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.i(TAG, "Registered broacast receiver");
}
Here is my Service class:
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.codecollapse";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
//sendBroadcast(bi);
sendBroadcast(new Intent(getBaseContext(), CountDownReceiver.class).setAction("com.codecollapse").putExtra("countdown",millisUntilFinished));
}
#Override
public void onFinish() {
bi.putExtra("IsFinish",true);
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Here is my receiver class
public class CountDownReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "You Poke the service", Toast.LENGTH_SHORT).show();
}
}
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidservices">
<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>
<receiver
android:name=".CountDownReceiver">
<intent-filter>
<action android:name="com.codecollapse"/>
</intent-filter>
</receiver>
<service android:name=".BroadcastService" />
</application>
Hi You can read the topic as announced with Oreo 8.0 release:
you can see the detail of it at official link.
I want message or notification show when start or boot android mobile. Notification show but when I destroyed application it not showing message or notification. So Please anyone help me.
public class BeaconService extends Service {
Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
showNotification();
}
});
}catch (Exception e){
}
}
}
}).start();
return START_STICKY;
}
private void showNotification() {
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_loc)
.setContentTitle("Welcome to Ford Show Room")
.setContentText("Hello Puneet, Welcome to Ford! You'll be shortly attended by Karthik! ")
.setPriority(2)
.setOnlyAlertOnce(true);
Intent resultIntent = new Intent(this, SlideMenuActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(SlideMenuActivity.class);
stackBuilder.addNextIntent(resultIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(2001, mBuilder.build());
}
}
BeaconReceiverService.java
public class BeaconReceiverService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("DEBUG", "Creating the intent");
Intent service = new Intent(context, BeaconService.class);
context.startService(service);
}
}
Services in menifest.xml
<service
android:name=".BeaconService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
<receiver android:name=".BeaconReceiverService">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This below thing definitely worked well
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
>
<receiver android:name=".BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service android:name="NotifyingDailyService" >
</service>
BootCompletedReceiver class
public class BootCompletedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
context.startService(new Intent(context, NotifyingDailyService.class));
}
}
Service class
public class NotifyingDailyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent pIntent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "Notification", Toast.LENGTH_LONG).show();
return super.onStartCommand(pIntent, flags, startId);
}
}
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>