CountDownTimer Service crashing when it is opened - java

I am trying to make a countdown timer screen that will keep counting down if I back out of the app or change screens or something. For some reason it keeps crashing saying that timeLeft is null. I can't figure out why it would be because I know the time variable in my Countdown class is there. Thanks for any help!
Countdown Activity
public class Countdown extends Activity {
public static String time;
public static String address;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
Intent confIntent = getIntent();
time = confIntent.getStringExtra("time");
address = confIntent.getStringExtra("address");
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView= findViewById(R.id.t1);
String timeLeftString = intent.getStringExtra("timeSent");
int timeLeft = Integer.parseInt(timeLeftString);
if(timeLeft>0) {
textView.setText("You have " + timeLeft + " minutes left");
}
else{
textView.setText("Y'all outta time, see ya again soon!");
killIt();
}
}
}, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);
Intent toService = new Intent(this, CountdownService.class);
startService(toService);
}
#Override
protected void onResume() {
super.onResume();
TextView textView= findViewById(R.id.t1);
textView.setText("You have " + CountdownService.toSend + " minutes left");
}
#Override
protected void onPause() {
super.onPause();
}
public void killIt(){
stopService(new Intent(this, CountdownService.class));
}
}
Countdown Service
public class CountdownService extends Service{
public static int toSend=0;
public int time;
public static final String
ACTION_LOCATION_BROADCAST = CountdownService.class.getName() +
"LocationBroadcast";
public final String timeFromCD = Countdown.time;
public final String address = Countdown.address;
#Override
public void onCreate() {
super.onCreate();
time = Integer.parseInt(timeFromCD);
time = time*60000;
new CountDownTimer(time, 5000) {
public void onTick(long millisUntilFinished) {
int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000); //Whole number of minutes left, ceiling
sendBroadcastMessage(timeLeftInt);
toSend = timeLeftInt;
if(timeLeftInt == 5){
Notify("Not Done");
}
}
public void onFinish() {
sendBroadcastMessage(0);
Notify("done");
Response.Listener<String> response = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//creating a jsonResponse that will receive the php json
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(CountdownService.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SpotAmountRequest spotAmountRequest = new SpotAmountRequest(address, "0", response);
RequestQueue queue = Volley.newRequestQueue(CountdownService.this);
queue.add(spotAmountRequest);
}
}.start();
}
private void sendBroadcastMessage(int timeSent) {
Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
intent.putExtra("timeSent", timeSent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
Notification n = new Notification.Builder(this)
.setContentTitle("Time to leave!")
.setContentText("Your PrePark spot has expired, time to go home!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(1000);
}
else{
Notification n = new Notification.Builder(this)
.setContentTitle("Ya got 5 minutes left in your PrePark spot!")
.setContentText("Better get going soon here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
}
}
}

You're storing an int value in the intent that you're broadcasting from the service, but you're then trying to get it out as a String where you receive the broadcast. Either change the receiver to use getIntExtra instead of getStringExtra, or convert the int to a String in the service before storing it in the intent.

Related

how do i start multiple same services to run at the same time?

i need to start a service whenever the user wants, its the same service with only different input data. I tried with workmanager and using threads libraries, its important to say that is a long running task. Down below is my code
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startThread(View view){
Value1 = findViewById(R.id.Value1);
Value2 = findViewById(R.id.Value2);
String value1 = Value1.getText().toString();
String Value2 = Value2.getText().toString();
Intent service = new Intent(this, servicio.class);
service.putExtra("value1", value1);
service.putExtra("value2", value2);
startService(service);
service file
public class servicio extends Service {
private static final String TAG = "service";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String rapida = intent.getStringExtra("value1");
String lenta = intent.getStringExtra("value2");
int value = Integer.parseInt(rapida);
int to = Integer.parseInt(lenta);
for (int i = value; i<to; i++){
Log.d(TAG, "number: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Intent notificationintent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationintent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Counting")
.setContentText("from" + rapida + "to" + lenta)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(new Random().nextInt(), notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
i need to make to run multiple of this at the same time no matter with what.

AudioPlaybackCapture (Android 10) not working and recording empty sounds

I tried to use new AudioPlaybackCapture method to record some media in an android 10 device. But unfortunately my code which uses this API does not seem to be working well.
Here I used an activity which starts a separate service for media recording. That service is registered to a broadcast receiver to start and stop recordings. And the broadcast intents are fired using my main activity via button clicks (start, stop)
No exceptions are printed. Also the file is created at the desired location. But with no content (0bytes). All the required manifest and runtime permissions are given. What i'm doing wrong here.
Here is my service
public class MediaCaptureService extends Service {
public static final String ACTION_ALL = "ALL";
public static final String ACTION_START = "ACTION_START";
public static final String ACTION_STOP = "ACTION_STOP";
public static final String EXTRA_RESULT_CODE = "EXTRA_RESULT_CODE";
public static final String EXTRA_ACTION_NAME = "ACTION_NAME";
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
NotificationCompat.Builder _notificationBuilder;
NotificationManager _notificationManager;
private String NOTIFICATION_CHANNEL_ID = "ChannelId";
private String NOTIFICATION_CHANNEL_NAME = "Channel";
private String NOTIFICATION_CHANNEL_DESC = "ChannelDescription";
private int NOTIFICATION_ID = 1000;
private static final String ONGING_NOTIFICATION_TICKER = "RecorderApp";
int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format
AudioRecord _recorder;
private boolean isRecording = false;
private MediaProjectionManager _mediaProjectionManager;
private MediaProjection _mediaProjection;
Intent _callingIntent;
public MediaCaptureService() {
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Call Start foreground with notification
Intent notificationIntent = new Intent(this, MediaCaptureService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
_notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Starting Service")
.setContentText("Starting monitoring service")
.setTicker(ONGING_NOTIFICATION_TICKER)
.setContentIntent(pendingIntent);
Notification notification = _notificationBuilder.build();
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
_notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
_notificationManager.createNotificationChannel(channel);
startForeground(NOTIFICATION_ID, notification);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
_mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
_callingIntent = intent;
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_ALL);
registerReceiver(_actionReceiver, filter);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startRecording(Intent intent) {
//final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
_mediaProjection = _mediaProjectionManager.getMediaProjection(-1, intent);
startRecording(_mediaProjection);
}
#TargetApi(29)
private void startRecording(MediaProjection mediaProjection ) {
AudioPlaybackCaptureConfiguration config =
new AudioPlaybackCaptureConfiguration.Builder(mediaProjection)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.build();
AudioFormat audioFormat = new AudioFormat.Builder()
.setEncoding(RECORDER_AUDIO_ENCODING)
.setSampleRate(RECORDER_SAMPLERATE)
.setChannelMask(RECORDER_CHANNELS)
.build();
_recorder = new AudioRecord.Builder()
// .setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(audioFormat)
.setBufferSizeInBytes(BufferElements2Rec * BytesPerElement)
.setAudioPlaybackCaptureConfig(config)
.build();
_recorder.startRecording();
writeAudioDataToFile();
}
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
Log.i(MainActivity.LOG_PREFIX, "Recording started. Computing output file name");
File sampleDir = new File(getExternalFilesDir(null), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String fileName = "Record-" + new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss").format(new Date()) + ".pcm";
String filePath = sampleDir.getAbsolutePath() + "/" + fileName;
//String filePath = "/sdcard/voice8K16bitmono.pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
_recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.i(MainActivity.LOG_PREFIX, String.format("Recording finished. File saved to '%s'", filePath));
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void stopRecording() {
// stops the recording activity
if (null != _recorder) {
isRecording = false;
_recorder.stop();
_recorder.release();
_recorder = null;
}
_mediaProjection.stop();
stopSelf();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(_actionReceiver);
}
BroadcastReceiver _actionReceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_ALL)) {
String actionName = intent.getStringExtra(EXTRA_ACTION_NAME);
if (actionName != null && !actionName.isEmpty()) {
if (actionName.equalsIgnoreCase(ACTION_START)) {
startRecording(_callingIntent);
} else if (actionName.equalsIgnoreCase(ACTION_STOP)){
stopRecording();
}
}
}
}
};
And here is an extract from the main activity where the service and start / stop actions are started.
public class MainActivity extends AppCompatActivity {
public static final String LOG_PREFIX = "CALL_FUNCTION_TEST";
private static final int ALL_PERMISSIONS_PERMISSION_CODE = 1000;
private static final int CREATE_SCREEN_CAPTURE = 1001;
Button _btnInitCapture;
Button _btnStartCapture;
Button _btnStopCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnGetOkPermissions = findViewById(R.id.btnGetOkPermissions);
_btnGetOkPermissions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkOkPermissions();
}
});
_btnInitCapture = findViewById(R.id.btnInitCapture);
_btnInitCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initAudioCapture();
}
});
_btnStartCapture = findViewById(R.id.btnStartCapture);
_btnStartCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startRecording();
}
});
_btnStopCapture = findViewById(R.id.btnStopAudioCapture);
_btnStopCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopRecording();
}
});
}
...
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAudioCapture() {
_manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = _manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
private void stopRecording() {
Intent broadCastIntent = new Intent();
broadCastIntent.setAction(MediaCaptureService.ACTION_ALL);
broadCastIntent.putExtra(MediaCaptureService.EXTRA_ACTION_NAME, MediaCaptureService.ACTION_STOP);
this.sendBroadcast(broadCastIntent);
}
private void startRecording() {
Intent broadCastIntent = new Intent();
broadCastIntent.setAction(MediaCaptureService.ACTION_ALL);
broadCastIntent.putExtra(MediaCaptureService.EXTRA_ACTION_NAME, MediaCaptureService.ACTION_START);
this.sendBroadcast(broadCastIntent);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (CREATE_SCREEN_CAPTURE == requestCode) {
if (resultCode == RESULT_OK) {
Intent i = new Intent(this, MediaCaptureService.class);
i.setAction(MediaCaptureService.ACTION_START);
i.putExtra(MediaCaptureService.EXTRA_RESULT_CODE, resultCode);
i.putExtras(intent);
this.startService(i);
} else {
// user did not grant permissions
}
}
}
}
Well, nothing sets isRecording true. Also, you're doing your recording in a blocking method, but you're on the UI thread, which ought to cause your interface to freeze as soon as you start recording.

splash screen getting value from the service

I have splash screen which has count down time. I am assigning time value manually in my example time = 10000.
1)How can I assign value which I am getting from the service to the time variable.
2) How can I compare both the time and then assign the service time to the splash screen activity.
Activity
TextView text1, text2, text3;
// int time= 3600000*8;
int time = 10000;
public int Main_time ;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
StringBuilder stringBuilder = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
splashScreenUseAsyncTask();
int mUIFlag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
//usbService.sendATGetESN();
//usbService.sendATGetSTART();
//usbService.sendATGetPC();
//usbService.sendATGetSTOP();
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
StringBuilder main= mActivity.get().stringBuilder.append(data);
Main_time = Integer.parseInt(main.toString());
Log.d("REPLY", "Processing Accumulator List Command22"+Main_time);
break;
}
}
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
//long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
//imageAplha = 0;
//splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(time);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
Service
long sec = Integer.parseInt(value9);
long result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY","Milli"+ result);
String s = String.valueOf(result);
if (mHandler != null) {
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, s).sendToTarget();
}
new MyTask().execute();
private class MyTask extends AsyncTask<Void,Void,Long>{
#Override
protected Long doInBackground(Void... voids) {
//after downloading or after getting time from service that time for example 3000 we received
return 3000l;
}
#Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
}
},timeinMs);
}
}
public class splash_screen extends AppCompatActivity {
TextView text1, text2, text3,display;
// int time= 3600000*8;
public String data;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
public StringBuilder stringBuilder = new StringBuilder();
long time = 60000;
private long result ;
private long result2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().time(data);
break;
}
}
}
public void time(String data) {
long sec = Integer.parseInt(data);
result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY", "Result value"+result);
result2 = time - result;
Log.d("REPLY", "Result2 value"+result2);
Log.d("REPLY", "Time value"+time);
if(result>=time) {
//usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
}
else{
if (result >= time) {
// usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
} else {
// Log.d("REPLY", "result2 value " + result2);
splashScreenUseAsyncTask();
} }
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(result2, 1000) {
#SuppressLint("DefaultLocale")
#Override
public void onTick(long l) {
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
#SuppressLint("StaticFieldLeak")
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(result2);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
//usbService.sendATGetSTOP();
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
usbService.sendATGetACC();
}
}
}

Does Service needs another parser?

I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.

Push notification service in Android

I am trying to make an app in Android Studio which sends a push notification every 15 seconds, using a service. The problem is that the mobiles I tested the code on acted really slowly when a notification pops up. When I use an emulator, it works fine. Does anyone know what makes this code really slow?
Thanks in advance!
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this, MyService.class);
startService(i);
}
}
MyService.java
public class MyService extends Service {
public MyService() {
}
public void showPushNotification (){
NotificationCompat.Builder pushbericht;
final int IDnummer = 123;
pushbericht = new NotificationCompat.Builder(this);
pushbericht.setAutoCancel(true);
pushbericht.setSmallIcon(R.drawable.icoontje);
pushbericht.setContentTitle("Poll App");
pushbericht.setContentText("Hoi");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pushbericht.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(IDnummer, pushbericht.build());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 5; i++) {
long futureTime = System.currentTimeMillis() + 15000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
showPushNotification();
} catch (InterruptedException e) {
}
}
}
}
}
};
Thread thread = new Thread(r);
thread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

Categories

Resources