CountDownTimer inside Android app stops when using Google Search widget? - General Questions and Answers

I'm showing the timer in the TextView. I'm adding the code for onPause and onResume method.
Below is the code for countDownTimer. I call this method from the onResume method.
Code:
public void startCountDownTimer() {
countDownTimer = new CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
total = millisUntilFinished;
completedMin = (int) (TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)));
sessionTimerTextView.setText("" + String.format(TIME_FORMAT,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
sessionTimerTextView.setText("00:00:00");
}
};
countDownTimer.start();
}
Below is the code for onResume method
Code:
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
startCountDownTimer();
}
Below is the code for onPause method
Code:
@Override
protected void onPause() {
super.onPause();
}
The code works fine when I minimize the app and open any other app but when I use the Google search widget then the timer inside my app stops. What should I do to resolve the issue?

Related

help with this code

i wnat to use the random outside the method
plz help
Code:
public class asd2 extends Activity {
private Button Button01;
private Button Button02;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button01 = (Button) findViewById(R.id.Button01);
Button02 = (Button) findViewById(R.id.Button02);
final SeekBar seekBar01 = (SeekBar) findViewById(R.id.SeekBar01);
final Random anyrandom = new Random();
final EditText EditText01 = (EditText) findViewById(R.id.EditText01);
Button01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// i need help to move to other activity in my app with this
// intent
Intent asdintenet = new Intent(this, secjavafile);
startActivity(asdintenet);
// this is the random i want to use (asdrandom)outside this
// method
int asdrandom = anyrandom.nextInt(30) + 1;
seekBar01.setProgress(asdrandom);
}
});
Button02.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
seekBar01
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
/*
* I WANT to use the random here e.g
* EditText01.setText("progress is"+asdrandom);when i
* use progress int the app crash
*/
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
this file contains the project
as u c I'm beginner
i;ve solved one
i used string.valueof(progress)
any help with intent to other activity???

[Q] How can I create a white list of Apps?

Hi, I am developping a home screen app, and I want only certain apps to be able tu be launched from my home screen.
I want to do it exactly like Surelock:
When the user tries to open an app that doesn't belong to my list of accepted apps, he should receive a toast saying something like example: "com.android.settings blocked by this app".
I need that type of security, I came across a piece of code on the web, but it does not work...
Could you help me out either by suggesting something new or by helping me understand and fix this one?
public class MonitorService extends Service {
private Handler handler;
Runnable runnable;
@override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler = new Handler();
runnable = new Runnable() {
@override
public void run() {
new Thread(new Runnable() {
@override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am
.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
String currentActivityName=componentInfo.getClassName();
String packageName=componentInfo.getPackageName();
if(whitelist.contains(currentActivityName)){
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName(blockActivityPackageName,
blockActivityName));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
}
}
}).start();
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
@override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, MonitorService.class);
startService(intent);
}
@override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}}

Google Play Game Services in libgdx

The article was written in the course of the game's development CLEAR SKY 2
The first part here!
Code
In the main Activity implement two interfaces GameHelperListener, ActionResolver:
public class MainActivity extends AndroidApplication implements GameHelperListener, ActionResolver
GameHelperListener interface is as follows:
Code:
public interface GameHelperListener {
/ **
* Called when an attempt to login. This method can show
* User button «Sign-in» for manual entry
* /
void onSignInFailed ();
/ ** Called when a successful login attempt * /
void onSignInSucceeded ();
}
Interface ActionResolver create ourselves. He needed to call the platform-dependent code. This technique is described in the official wiki libgdx. An example of the interface:
Code:
public interface ActionResolver {
/ ** Check the status of the user input * /
public boolean getSignedInGPGS ();
/ ** Log * /
public void loginGPGS ();
/ ** Send the result in the high score table * /
public void submitScoreGPGS (int score);
/ **
* Unlock achievement
*
*param AchievementId
* ID achievements. Taken from the file games-ids.xml
* /
public void unlockAchievementGPGS (String achievementId);
/ ** Show Activity records to the table * /
public void getLeaderboardGPGS ();
/ ** Show Activity achievements * /
public void getAchievementsGPGS ();
}
Example code main Activity:
Code:
public class MainActivity extends AndroidApplication implements
GameHelperListener, ActionResolver {
// Assistant to work with gaming services
private GameHelper gameHelper;
// Class of our games
private TestGame game;
Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
// CLIENT_ALL instruct you on the use of the API all customers
gameHelper = new GameHelper (this, GameHelper.CLIENT_ALL);
// Disable automatic login when starting the game
gameHelper.setConnectOnStart (false);
gameHelper.enableDebugLog (true);
// From turning off the screen without the use of additional
// Permits (less than permissions - more confidence in the application)
getWindow (). addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Input parameter this is ActionResolver. Allows you to call from
// Game loop platform-specific methods GPGS
game = new TestGame (this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration ();
initialize (game, config);
gameHelper.setup (this);
}
// Methods gameHelper'a: onStart (), onStop () are called to work correctly
// GPGS in the lifecycle of android-app
Override
protected void onStart () {
super.onStart ();
gameHelper.onStart (this);
}
Override
protected void onStop () {
super.onStop ();
gameHelper.onStop ();
}
Override
protected void onDestroy () {
super.onDestroy ();
}
Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
// Here gameHelper decides to connect, or reconnect
// Disconnected from the game services, depending on the result code
// Activity
gameHelper.onActivityResult (requestCode, resultCode, data);
}
Override
public boolean getSignedInGPGS () {
// Connection status
return gameHelper.isSignedIn ();
}
Override
public void loginGPGS () {
try {
runOnUiThread (new Runnable () {
Override
public void run () {
// Initiate user entry. Can be called a dialogue
// Login. Performed in UI-stream
gameHelper.beginUserInitiatedSignIn ();
}
});
} Catch (Exception e) {
e.printStackTrace ();
}
}
Override
public void submitScoreGPGS (int score) {
// Send game points to a specific table records with ID
// "HgkIr62KmoQJEAIQAQ"
Games.Leaderboards.submitScore (gameHelper.getApiClient (),
"HgkIr62KmoQJEAIQAQ", score);
}
Override
public void unlockAchievementGPGS (String achievementId) {
// Open achievement with ID achievementId
Games.Achievements.unlock (gameHelper.getApiClient (), achievementId);
}
Override
public void getLeaderboardGPGS () {
Activity // call for all registered tables records. as
Activity // can call for a specific table
startActivityForResult (
Games.Leaderboards.getAllLeaderboardsIntent (gameHelper
.getApiClient ()), 100);
}
Override
public void getAchievementsGPGS () {
// Call Activity achievements
startActivityForResult (
Games.Achievements.getAchievementsIntent (gameHelper
.getApiClient ()), 101);
}
Override
public void onSignInSucceeded () {
}
Override
public void onSignInFailed () {
}
}
Suppose we have in the game provided the achievement - to collect 1 million. Player points, the code implementing it would look like this:
Code:
public static void checkTotalPoints (int points) {
ActionResolver res = getActionResolver ();
if (! res.getSignedInGPGS ()) {
return;
}
if (points> = 1000000) {
res.unlockAchievementGPGS ("HgkIr62KmoQJEAIQGA");
}
}
Same thing with a table of records, only even easier: you just need to call the submitScoreGPGS (int score) interface ActionResolver.
PS To test gaming services need to export apk-file with the same certificate as in the developer console. Just need to add accounts testers in the console. Changes in gaming services come into effect after a while.
Google Play Clear Sky 2
Long second part released!
sources used
developers.google.com/games/services/android/quickstart
developer.android.com/intl/ru/google/play-services/setup.html
github.com/libgdx/libgdx/wiki
Please don't add the &hl=ru parameter to your Play Store links - then it is in Russian for all users. Without it, native language is used.

How to Get the Current Location using Google Play Services in android

I'm trying to get the current GPS location from an android smartphone but I'm having some issues, because I didn't get any latitude and longitude.
I've used Google Play Services library because the other methods didn't work. Here's the code:
Code:
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class AroundMeActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
private TextView mLatitudeText;
private TextView mLongitudeText;
private Location mLastLocation;
private boolean mRequestingLocationUpdates = true;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_around_me);
mLatitudeText = (TextView) findViewById(R.id.location_text);
mLongitudeText = (TextView) findViewById(R.id.activity_text);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
@Override
public void onConnected(Bundle connectionHint) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
return;
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
return;
}
}
@Override
public void onConnectionSuspended(int i) {
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
@Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
//mLastUpdateTimeTextView.setText(mLastUpdateTime);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
Has anyone encountered the same issue and can help me?
Thank you in advance guys!!

Is RecyclerView refreshed when AlertDialog's positive button gets pressed

My MainActivity has a RecyclerView adapter, and data to this RecyclerView is added through a AlertDialog which passes the entered text to the MainActivity. The recycler view gets refreshed somehow when the positive button in the dialog is pressed even though I never call notifyItemInserted() or notifyDatasetChange() after passing the new input. I want to know how this happens, my guess is the recyclerview is somehow refreshed after the positive button is pressed in the dialog box.
Custom AlertDialog Code:
Code:
public class CustomDialog extends AppCompatDialogFragment {
OnNoteAddedListener onNoteAddedListener;
public interface OnNoteAddedListener {
public void onClick(String note);
}
public CustomDialog(OnNoteAddedListener onNoteAddedListener) {
this.onNoteAddedListener = onNoteAddedListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogLayout = inflater.inflate(R.layout.dialog_box, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogLayout).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int id) {
EditText addNote = dialogLayout.findViewById(R.id.note_text);
String note = addNote.getText().toString();
onNoteAddedListener.onClick(note);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CustomDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Adapter code:
Code:
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
private static final String TAG = "RecyclerViewAdapter";
private List<String> notesList;
private Context mContext;
private SendPositionConnector sendPositionConnector;
public interface SendPositionConnector
{
public void sendPosition(int position);
}
public RecyclerViewAdapter(List<String> notesList, Context mContext)
{
this.notesList = notesList;
this.mContext = mContext;
this.sendPositionConnector = (MainActivity)mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
{
Log.d(TAG, "onBindViewHandler: called");
viewHolder.noteContent.setText(notesList.get(position));
viewHolder.parentLayout.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View view)
{
Log.d(TAG, "onLongClick: long clicked on");
sendPositionConnector.sendPosition(position);
return false;
}
});
}
@Override
public int getItemCount()
{
return notesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView noteContent;
RelativeLayout parentLayout;
ImageView bullet;
public ViewHolder(@NonNull View itemView)
{
super(itemView);
bullet = itemView.findViewById(R.id.bullet);
noteContent = itemView.findViewById(R.id.text_content);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Main Activity:
Code:
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.SendPositionConnector
{
private static final String TAG = "MainActivity";
private List<String> notesList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private int position;
public AgentAsyncTask agentAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.my_recycler_view);
registerForContextMenu(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
agentAsyncTask = new AgentAsyncTask(notesList, getApplicationContext(), true, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
adapter = new RecyclerViewAdapter(notesList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
agentAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.add_note:
showDialogBox(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStop()
{
super.onStop();
new AgentAsyncTask(notesList, getApplicationContext(), false, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
}
}).execute();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private boolean showDialogBox(MenuItem menuItem)
{
AppCompatDialogFragment dialogFragment = new CustomDialog(new CustomDialog.OnNoteAddedListener(){
@Override
public void onClick(String note)
{
Log.d(TAG, "onClick: "+ note);
notesList.add(note);
}
});
dialogFragment.show(getSupportFragmentManager(),"Adding");
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.delete:
notesList.remove(position);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, notesList.size());
return true;
default:
return false;
}
}
@Override
public void sendPosition(int position)
{
this.position = position;
}
private static class AgentAsyncTask extends AsyncTask<Void, Void, List<String>>
{
private List<String> notesList;
private boolean flag;
OnRead onRead;
Context context;
AppDataBase dataBase;
private static final String TAG = "AgentAsyncTask";
public interface OnRead
{
public void onRead(List<String> notesList);
}
private AgentAsyncTask(List<String> notesList,Context context,boolean flag, OnRead onRead)
{
this.notesList = notesList;
this.onRead = onRead;
this.flag = flag;
this.context = context;
}
@Override
protected List<String> doInBackground(Void... params)
{
dataBase = Room.databaseBuilder(context, AppDataBase.class, "database-name").build();
if(!flag)
{
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {}.getType();
String json = gson.toJson(notesList, type);
Log.d(TAG, "doInBackground: "+json);
Notes notes = new Notes();
notes.setNoteContent(json);
notes.setUid(1);
dataBase.notesDao().insertNotes(notes);
return notesList;
}
else
{
Gson gson = new Gson();
String notesListContent = dataBase.notesDao().getNotes();
if(dataBase.notesDao().getCount() != 0)
{
notesList = gson.fromJson(notesListContent, new TypeToken<List<String>>()
{
}.getType());
}
else
{
return notesList;
}
return notesList;
}
}
@Override
protected void onPostExecute(List<String> notesList)
{
super.onPostExecute(notesList);
if(flag)
onRead.onRead(notesList);
}
}
}

Categories

Resources