I have to do an android service that communicates with a web service within 45 seconds. but i can't do it with business service or normal service. The system automatically shuts itself down after 10 minutes. I need help.
public class bildirim extends JobService {
int Kul_Id = 0;
String[] sto;
int sayac = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
final ipdatabase dbo = new ipdatabase(getBaseContext());
sto = dbo.ipler(getBaseContext());
database db = new database(bildirim.this);
if (db.dbkontrol()) {
List<String> cr = db.veriListele(2);
if (!cr.isEmpty()) {
Kul_Id = Integer.parseInt(cr.get(4));
}
}
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
new arkaplan().execute("http://" + sto[0] + "/Services.asmx/bildirimal?Kul_ID=" + Kul_Id+"&durum=1");
}
},0,30000);
return false;
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
#Override
public void onDestroy() {
JobSchedulerService.scheduleJob(getApplicationContext());
super.onDestroy();
}
class arkaplan extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
return jsonparser.getdata(params[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray listarray = obj.getJSONArray("list");
JSONObject fistobj;
for (int i = 0; i < listarray.length(); i++) {
fistobj = listarray.getJSONObject(i);
int icon = R.drawable.redwhitefav;
NotificationManagerCompat notifiynm = NotificationManagerCompat.from(bildirim.this);
Notification notifiy = new NotificationCompat.Builder(bildirim.this, CHANNEL_1_ID)
.setSmallIcon(icon)
.setContentTitle(fistobj.getString("Gork_Deger") + ": " + fistobj.getString("Gork_Mstad"))
.setContentText("Tanım: "+ fistobj.getString("Gork_Tanim") + "\n"+ "Tarih: " + fistobj.getString("Gork_Baslangic"))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.build();
notifiynm.notify(sayac, notifiy);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Related
Im trying to make a service that would provide data of usagestat every x second. However i always getting the same value after x second. I already clear the map to include new data set from usagemanager. below is my service class thank you in advance.
I do know that in order to retrieve queries every x time, we may use queryevent. However, the total time in foreground for this fit my project, and i already tested using the code for adapter. In the adapter, it do retrieve usage time, however it only provide new value on restarting the activity where the adapter used.
public class PushService extends Service {
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id_1";
private static final String NOTIF_CHANNEL_ID2 = "Channel_Id_2";
private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
private static final int _DISPLAY_ORDER_APP_NAME = 2;
private static final boolean localLOGV = false;
private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
private AppNameComparator mAppLabelComparator;
private LastTimeUsedComparator mLastTimeUsedComparator;
private UsageTimeComparator mUsageTimeComparator;
private PackageManager mPm;
private UsageStatsManager mUsageStatsManager;
public HashMap<String, Long> mapToFirebase = new HashMap<>();;
public ArrayList<UsageStats> mPackageStats;
public ArrayMap<String, String> mAppLabelMap;
public List<UsageStats> stats;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
/*notice*/
startForeground();
if (intent != null){
String uid = intent.getStringExtra("parentUID");
if (!uid.equals("")){
Toast.makeText(this, uid, Toast.LENGTH_SHORT).show();
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
pushAppList();
mapToFirebase.clear();
loadDataToMapForFirebase();
Log.d("mapservice", mapToFirebase.toString());
ha.postDelayed(this, 5000);
}
}, 10000);
}
}
return super.onStartCommand(intent, flags, startId);
}
public static class AppNameComparator implements Comparator<UsageStats> {
private Map<String, String> mAppLabelList;
AppNameComparator(Map<String, String> appList) {
mAppLabelList = appList;
}
#Override
public final int compare(UsageStats a, UsageStats b) {
String alabel = mAppLabelList.get(a.getPackageName());
String blabel = mAppLabelList.get(b.getPackageName());
return alabel.compareTo(blabel);
}
}
public void pushAppList(){
mAppLabelMap = new ArrayMap<>();
mPackageStats = new ArrayList<>();
mPm = getPackageManager();
mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
mLastTimeUsedComparator = new LastTimeUsedComparator();
mUsageTimeComparator = new UsageTimeComparator();
stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());
if (stats == null) {
return;
}
ArrayMap<String, UsageStats> map = new ArrayMap<>();
int statCount = stats.size();
for (int i = 0; i < statCount; i++) {
Log.d("", String.valueOf(stats.get(i).getTotalTimeInForeground()));
android.app.usage.UsageStats pkgStats = stats.get(i);
// load application labels for each application
try {
ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
String label = appInfo.loadLabel(mPm).toString();
mAppLabelMap.put(pkgStats.getPackageName(), label);
UsageStats existingStats =
map.get(pkgStats.getPackageName());
if (existingStats == null) {
map.put(pkgStats.getPackageName(), pkgStats);
} else {
existingStats.add(pkgStats);
}
} catch (PackageManager.NameNotFoundException e) {
// This package may be gone.
}
}
mPackageStats.addAll(map.values());
// Sort list
mAppLabelComparator = new AppNameComparator(mAppLabelMap);
sortList();
}
public static class LastTimeUsedComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
// return by descending order
return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
}
}
public static class UsageTimeComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
}
}
private void sortList() {
if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
if (localLOGV) Log.i(TAG, "Sorting by usage time");
Collections.sort(mPackageStats, mUsageTimeComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
if (localLOGV) Log.i(TAG, "Sorting by last time used");
Collections.sort(mPackageStats, mLastTimeUsedComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
if (localLOGV) Log.i(TAG, "Sorting by application name");
Collections.sort(mPackageStats, mAppLabelComparator);
}
}
public void loadDataToMapForFirebase(){
/*TODO UPDATE DATA ONBACKGROUND*/
String system_sign = "android";
PackageManager pm = getPackageManager();
if (mPackageStats.size() != 0){
for (int i = 0; i < mPackageStats.size(); i++){
if (pm.checkSignatures(system_sign, mPackageStats.get(i).getPackageName()) == PackageManager.SIGNATURE_MATCH) {
Log.d("CheckAppSys", mPackageStats.get(i).getPackageName() + " is sys.");
} else {
String usagetime = DateUtils.formatElapsedTime(mPackageStats.get(i).getTotalTimeInForeground() / 1000);
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(Objects.requireNonNull(mAppLabelMap.get(mPackageStats.get(i).getPackageName())));
boolean constainsSymbols = matcher.find();
if(!constainsSymbols){
mapToFirebase.put(mAppLabelMap.get(mPackageStats.get(i).getPackageName()), mPackageStats.get(i).getTotalTimeInForeground());
}
Log.d("maptofirebase", mapToFirebase.toString());
Log.d("CheckApp", mPackageStats.get(i).getPackageName() + " is not sys.");
}
}
}
}
private void startForeground() {
Intent notificationIntent = new Intent(this, UsageStatsActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
NOTIF_CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is channel 1");
NotificationChannel channel2 = new NotificationChannel(
NOTIF_CHANNEL_ID2,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.app_name))
.setContentText("Monitoring apps.")
.setContentIntent(pendingIntent)
.build());
}
}
I am currently creating an app for a university project. Within the app I use two php scripts - one to set data from variables within the app to a MySQL data base, and the other to retrieve data from the database and set the variables within the app. The first script that sends the data to mySQL is working fine with no issues, however the script to retrieve the data from mySQL to set variables within the app is only working when ran through my webserver. When run within my app (on Activity Start and create) the variables are all set to zero. Any help would be amazing, Ive been stuck for weeks!
<?php
require "conn.php";
$username = "test";
$stmt = $conn->prepare("SELECT gold, goldMulti, xp, xpMulti, xpMax, xpMaxMulti, dmg, dmgMulti, bossCount, bossHp, bossHpMulti, level, backgroundCount FROM users WHERE username = '$username'");
$stmt ->execute();
$stmt ->bind_result($gold, $goldMulti, $xp, $xpMulti, $xpMax, $xpMaxMulti, $dmg, $dmgMulti, $bossCount, $bossHp, $bossHpMulti, $level, $backgroundCount);
$varaibles = array();
$stmt ->fetch();
$temp = array();
$temp['gold'] = $gold;
$temp['goldMulti'] = $goldMulti;
$temp['xp'] = $xp;
$temp['xpMulti'] = $xpMulti;
$temp['xpMax'] = $xpMax;
$temp['xpMaxMulti'] = $xpMaxMulti;
$temp['dmg'] = $dmg;
$temp['dmgMulti'] = $dmgMulti;
$temp['bossCount'] = $bossCount;
$temp['bossHp'] = $bossHp;
$temp['bossHpMulti'] = $bossHpMulti;
$temp['level'] = $level;
$temp['backgroundCount'] = $backgroundCount;
array_push($variables,$temp);
echo json_encode($temp);
?>
public class MainActivity extends AppCompatActivity {
// int variables for logic and functions ------------------------------------------------------
public int gold;
public int goldAwarded;
public int goldMultiplier;
public int xp;
public int xpAwarded;
public int xpMultiplier;
public int dmg;
public int dmgMultiplier;
public int bossCount;
public int bossHP;
public int bossHPMultiplier;
public int bossHPBase;
public int level;
public int xpMax;
public int bossCountFunc;
public int backgroundCount;
public int xpMaxMulti;
public int baseDmg;
// Widget variables -----------------------------------------------------------------------------
private TextView bossNumberText;
private TextView levelText;
private TextView goldText;
private TextView bossHealthText;
private ImageButton tapButton;
private ImageView bossImage;
private ImageView playerImage;
private ImageView bossImage2;
private ImageView bossImage3;
private ImageButton shopButton;
public String LoggedInUser = LogIn.getUser();
// Audio players --------------------------------------------------------------------------------
MediaPlayer mps;
MediaPlayer mpb;
MediaPlayer mpc;
MediaPlayer mpl;
MediaPlayer mpp;
// Websever php file URL to retrieve Data from user ----------------------------------------------
private static final String URL = "http://jg1104.brighton.domains/AppPhp/variablesretrieval.php";
private void getData(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray array = new JSONArray(response);
for(int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
gold = object.getInt("gold");
goldMultiplier = object.getInt("goldMulti");
xp = object.getInt("xp");
xpMultiplier = object.getInt("xpMulti");
xpMax = object.getInt("xpMax");
xpMaxMulti = object.getInt("xpMaxMulti");
dmg = object.getInt("dmg");
dmgMultiplier = object.getInt("dmgMulti");
bossCount = object.getInt("bossCount");
bossHP = object.getInt("bossHp");
bossHPMultiplier = object.getInt("bossHpMulti");
level = object.getInt("level");
backgroundCount = object.getInt("backgroundCount");
}
}catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(), Toast.LENGTH_SHORT).show();
}
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("LoggedInUser", LoggedInUser);
return param;
}
}
);
Volley.newRequestQueue(MainActivity.this).add(stringRequest);
}
// On create -------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bossNumberText = (TextView) findViewById(R.id.bossNumberText);
levelText = (TextView) findViewById(R.id.levelText);
goldText = (TextView) findViewById(R.id.goldText);
bossHealthText = (TextView) findViewById(R.id.bossHealthText);
tapButton = (ImageButton) findViewById(R.id.TapButton);
bossImage = (ImageView) findViewById(R.id.bossImage);
playerImage = (ImageView) findViewById(R.id.playerImage);
bossImage2 = (ImageView) findViewById(R.id.bossImage2);
bossImage3 = (ImageView) findViewById(R.id.bossImage3);
shopButton = (ImageButton) findViewById(R.id.shopButton);
mpb = MediaPlayer.create(this, R.raw.backgroundmusic);
mpc = MediaPlayer.create(this, R.raw.coin);
mpl = MediaPlayer.create(this, R.raw.levelup);
mpp = MediaPlayer.create(this, R.raw.pain);
mps = MediaPlayer.create(this, R.raw.shootingsound);
// retrieving data from database and setting TextViews -----------------------------------
getData();
// Set looping and start of background music ---------------------------------------------
mpb.setLooping(true);
mpb.start();
// Initialising variable values on create ------------------------------------------------
goldAwarded = 100;
xpAwarded = 100;
baseDmg = 1;
bossHPBase = 10;
bossCountFunc = 1;
shopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchShop();
}
});
}
#Override
protected void onStart() {
// onclickListener for main button --------------------------------------------------------
super.onStart();
getData();
levelText.setText("Level: " + Integer.toString(level));
goldText.setText("Gold: " + Integer.toString(gold));
bossHealthText.setText("HP: " + Integer.toString(bossHP));
bossNumberText.setText("Boss: " + bossCount);
tapButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// shooting sound
mps.start();
// run method that looks to see if background needs to be changed
newBackground();
// handlers for enemy animations
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
bossImage.setImageDrawable(getResources().getDrawable(R.drawable.onezshot));
AnimationDrawable oneshotz = (AnimationDrawable) bossImage.getDrawable();
oneshotz.start();
}
}, 0);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
bossImage2.setImageDrawable(getResources().getDrawable(R.drawable.twozshot));
AnimationDrawable twozshot = (AnimationDrawable) bossImage2.getDrawable();
twozshot.start();
}
}, 0);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
bossImage3.setImageDrawable(getResources().getDrawable(R.drawable.threezshot));
AnimationDrawable threezshot = (AnimationDrawable) bossImage3.getDrawable();
threezshot.start();
}
}, 0);
// handler for shooting animation
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
playerImage.setImageDrawable(getResources().getDrawable(R.drawable.shooting));
AnimationDrawable shooting = (AnimationDrawable) playerImage.getDrawable();
shooting.start();
}
}, 0);
bossHP -= dmg;
bossHealthText.setText("HP: " + Integer.toString(bossHP));
// if boss dies
if (bossHP <= 1) {
mpp.start();
bossCount++;
bossCountFunc++;
backgroundCount++;
if (backgroundCount > 9) {
backgroundCount = 1;
}
if (bossCountFunc > 3) {
bossCountFunc = 1;
}
bossNumberText.setText("Boss: " + bossCount);
goldMultiplier++;
xpMultiplier++;
mpc.start();
gold += (goldAwarded * goldMultiplier);
goldText.setText("Gold: " + Integer.toString(gold));
xp += (xpAwarded * xpMultiplier);
bossHPMultiplier++;
// look for level up
if (xp >= xpMax) {
mpl.start();
level++;
dmgMultiplier++;
bossHPMultiplier *= 2;
dmg = (baseDmg * dmgMultiplier);
levelText.setText("lvl: " + Integer.toString(level));
xp = 0;
xpMax = xpMax * xpMaxMulti;
}
newBoss();
}
}
});
}
// Method to show or hide boss frames
public void newBoss(){
bossHP = bossHPBase * bossHPMultiplier;
if(bossCountFunc==1){
bossImage.setVisibility(View.VISIBLE);
bossImage2.setVisibility(View.INVISIBLE);
bossImage3.setVisibility(View.INVISIBLE);
}
if(bossCountFunc==2){
bossImage.setVisibility(View.INVISIBLE);
bossImage2.setVisibility(View.VISIBLE);
}
if(bossCountFunc==3){
bossImage2.setVisibility(View.INVISIBLE);
bossImage3.setVisibility(View.VISIBLE);
}
}
// method to check and change background
public void newBackground(){
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);
if(backgroundCount<=3){
layout.setBackgroundResource(R.drawable.main);
}
if(backgroundCount>3 && backgroundCount<=6){
layout.setBackgroundResource(R.drawable.maintwo);
}
if(backgroundCount>6 && backgroundCount<=9){
layout.setBackgroundResource(R.drawable.mainthree);
}
}
public void launchShop(){
Intent intent = new Intent(this, Shop.class);
startActivity(intent);
}
private void setData(final String LoggedInUser, final int gold,final int goldMultiplier,final int xp,final int xpMultiplier
,final int xpMax,final int xpMaxMulti,final int dmg
,final int dmgMultiplier,final int bossCount,final int bossHP
,final int bossHPMultiplier,final int level,final int backgroundCount){
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setTitle("Setting Data");
progressDialog.show();
String uRl = "http://jg1104.brighton.domains/AppPhp/setdata.php";
StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("Data set")){
progressDialog.dismiss();
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
else{
progressDialog.dismiss();
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("LoggedInUser", LoggedInUser);
param.put("gold", Integer.toString(gold));
param.put("goldMulti", Integer.toString(goldMultiplier));
param.put("xp", Integer.toString(xp));
param.put("xpMulti", Integer.toString(xpMultiplier));
param.put("xpMax", Integer.toString(xpMax));
param.put("xpMaxMulti", Integer.toString(xpMaxMulti));
param.put("dmg", Integer.toString(dmg));
param.put("dmgMulti", Integer.toString(dmgMultiplier));
param.put("bossCount", Integer.toString(bossCount));
param.put("bossHp", Integer.toString(bossHP));
param.put("bossHpMulti", Integer.toString(bossHPMultiplier));
param.put("level", Integer.toString(level));
param.put("backgroundCount", Integer.toString(backgroundCount));
return param;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(MainActivity.this).addToRequestQueue(request);
}
#Override
protected void onStop() {
super.onStop();
setData(LoggedInUser,gold,goldMultiplier,xp,xpMultiplier,xpMax,xpMaxMulti,dmg,dmgMultiplier,bossCount,bossHP,bossHPMultiplier,level,backgroundCount);
}
}
Since the script is working when used in my webserver, I am sure it is something to do with my java coding.
This code is your problem:
try{
JSONArray array = new JSONArray(response);
for(int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
gold = object.getInt("gold");
goldMultiplier = object.getInt("goldMulti");
xp = object.getInt("xp");
xpMultiplier = object.getInt("xpMulti");
xpMax = object.getInt("xpMax");
xpMaxMulti = object.getInt("xpMaxMulti");
dmg = object.getInt("dmg");
dmgMultiplier = object.getInt("dmgMulti");
bossCount = object.getInt("bossCount");
bossHP = object.getInt("bossHp");
bossHPMultiplier = object.getInt("bossHpMulti");
level = object.getInt("level");
backgroundCount = object.getInt("backgroundCount");
}
} catch (Exception e) {
}
You should not leave the catch block empty. It's likely throwing and swallowing an error.
Do this:
} catch (Exception e) {
Log.e("MyApp", "Error parsing!", e);
}
(Some reading on Logcat https://developer.android.com/studio/debug/am-logcat)
or get rid of the try catch all together and let your app crash (fail fast)!!
Your actual error (or first error I can see anyway) is that you are attempting to parse a JSONarray when your server side response is a JSONObject. This line of code:
JSONArray array = new JSONArray(response);
And this response:
{
"gold":600, "goldMulti":3,
"xp":0, "xpMulti":3, "xpMax":0, "xpMaxMulti":0,
"dmg":3,"dmgMulti":3,
"bossCount":3,
"bossHp":80,
"bossHpMulti":14,
"level":3,
"backgroundCount":3
}
(from here) http://jg1104.brighton.domains/AppPhp/variablesretrieval.php
You should parse it as a JsonObject or wrap your server side returned response in an Array [].
firstly, i read all answers related with this problem but i didn't solve this error. My program is running but very laggy and slow. i tryed use smaller images and use async task but my problem is continued. here is my code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
NotificationManager manager;
public Veri veri,veri1;
int x= 0;
private Timer autoUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
veri1 = new Veri();
x=veri1.getList().size();
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
onResume();
new AsyncCaller().execute();
}
#Override
protected void onStart() {
super.onStart();
}
////////////////////////////////////////////
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
updateHTML();
}
});
}
}, 0, 60000);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
////////////////////////////////////
private void updateHTML(){
// your logic here
RecyclerAdapter adapter=new RecyclerAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
veri = new Veri();
int a = veri.getList().size();
if(a!=x){
generateNotification(MainActivity.this,"Listede Degisim Var");
}
x=a;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
// search action
case R.id.action_location_found:
// location found
LocationFound();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void LocationFound() {
Intent i = new Intent(MainActivity.this, LocationFound.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
private void generateNotification(Context context,String message){
int notificationId = 001;
Intent viewIntent = new Intent(context, MainActivity.class);
PendingIntent viewPendingIntent =
PendingIntent.getActivity(context, 0, viewIntent, 0);
NotificationCompat.Builder notificationBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.dikat)
.setContentTitle("Bildirim")
.setContentText(message)
.setContentIntent(viewPendingIntent)
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.bildirim))
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
here is my data class
public class Veri extends ActionBarActivity {
NotificationManager manager;
Notification myNotication;
String ip, db, un, passwords;
Connection connect,conn;
PreparedStatement stmt;
ResultSet rs;
TextView tv;
int position1=0;
Button b1;
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> data2 = new ArrayList<String>();
public Veri(){
ip = "x.x.x.x";
un = "x";
passwords = "x";
db = "xxx";
connect = CONN(un, passwords, db, ip);
String query = "SELECT Adsoyad,(DATEPART(hour, BeklemeSuresi) * 3600) + (DATEPART(minute, BeklemeSuresi) * 60) + DATEPART(second, BeklemeSuresi) as SecondsFromMidnight,Durum FROM [dbo].[IslemiDevamEdenHasta] (1)";
try {
// connect = CONN(un, passwords, db, ip);
stmt = connect.prepareStatement(query);
rs = stmt.executeQuery();
while (rs.next()) {
int b = (int)rs.getInt("SecondsFromMidnight")/60;
if(b>50) {
String id = rs.getString("Adsoyad");
String id2 = rs.getString("Durum");
String full = id + " " + id2;
String a = "" + b;
data.add(full);
data2.add(a);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<String> getList() {
return data;
}
public ArrayList<String> getList2() {
return data2;
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB,
String _server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
+ "databaseName=" + _DB + ";user=" + _user + ";password="
+ _pass + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
and here is my recycler class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
public Veri veri = new Veri();
int sayi=0;
ArrayList<String> liste = veri.getList();
ArrayList<String> liste2 = veri.getList2();
static ArrayList<String> liste3 = new ArrayList<String>() ;
Context context;
LayoutInflater inflater;
public RecyclerAdapter(Context context) {
this.context=context;
inflater=LayoutInflater.from(context);
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=inflater.inflate(R.layout.item_list, parent, false);
RecyclerViewHolder viewHolder=new RecyclerViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
liste3.add("a");
sayi = 0;
for (int j = 0; j < liste3.size(); j++) {
if (liste3.get(j).equals(liste.get(position))) {
sayi++;
}
if (sayi == 0) {
holder.tv1.setText(liste.get(position));
holder.tv2.setText(liste2.get(position));
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setTag(holder);
} else {
holder.tv1.setText(liste.get(position));
holder.tv2.setText(liste2.get(position));
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setImageResource(R.drawable.ic_checkin);
}
}
}
View.OnClickListener clickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerViewHolder vholder = (RecyclerViewHolder) v.getTag();
int position = vholder.getPosition();
//Toast.makeText(context,"This is position "+position,Toast.LENGTH_LONG ).show();
vholder.imageView.setImageResource(R.drawable.ic_checkin);
liste3.add(liste.get(position));
}
};
#Override
public int getItemCount() {
return liste.size();
}
}
what is my problem??
you doing so much coding for loading image.There are some third party api so you can refer it. so it may be helpful to load your image easily and memory management control is handle by that api also here just refer this tutorial.
I'm new to Android app developing, and I've tried to program a very simple app: each time the headphone cable is inserted it will play a random song from the collection, and stop whenever the headphone cable is disconnected.
However, I now face a very strange problem: no matter what I do, the app plays always two songs at the same time.
It's very strange because I tried to synchronize everything but it didn't solve the issue...
Here follows my code. Thanks in advance for any help!
public class MainActivity extends AppCompatActivity {
private int countMusic;
private boolean headphones= false;
private HeadphonePlugReceiver receiver;
private HashMap<Integer, String> playing_title;
private RandomPlayer player;
Object lock = new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playing_title = new HashMap<>();
scanAgain();
Button scanButton = (Button)findViewById(R.id.scan_again);
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanAgain();
}
});
updateStatus();
receiver = new HeadphonePlugReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
}
private void updateStatus() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView statusTextView = (TextView)findViewById(R.id.status);
TextView titleTextView = (TextView)findViewById(R.id.title);
if (headphones) {
statusTextView.setText("Headphones connected!");
String txt = "";
for (Integer cd: playing_title.keySet()) {
txt += String.format("%d: %s ### ", cd, playing_title.get(cd).replace("_", " "));
}
titleTextView.setText(txt);
} else {
statusTextView.setText("Headphones not connected.");
titleTextView.setText("Music not playing");
}
}
});
}
private void addDebug(final String code) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView debugTextView = (TextView)findViewById(R.id.debug);
String dbg = String.format("%s \n %s", debugTextView.getText(), code);
debugTextView.setText(dbg);
}
});
}
private void addError(final String msg) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView errorTextView = (TextView)findViewById(R.id.error);
errorTextView.setText(msg);
}
});
}
private void startPlayer() {
if (player == null) {
player = new RandomPlayer(this);
player.start();
}
}
private void stopPlayer() {
if (player != null) {
player.interr();
player = null;
}
}
private void scanAgain() {
try {
TextView countTextView = (TextView)findViewById(R.id.count);
countTextView.setText("Scanning... ");
countMusic = scanMusic().getCount();
countTextView.setText(String.format("Music file found: %d", countMusic));
}
catch(Exception e) {
Log.e("problem", e.getMessage());
}
}
public Cursor scanMusic() {
ContentResolver cr = this.getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.TITLE_KEY
};
Cursor cur = cr.query(uri, projection, selection, null, sortOrder);
return cur;
}
private class HeadphonePlugReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
synchronized (lock) {
int state = intent.getIntExtra("state", 0);
managePlayer(state);
// Log.e("state", String.format("state: %d", state));
}
}
private void managePlayer(int state) {
boolean n_headphones = (state != 0);
if (n_headphones == headphones)
return;
headphones = n_headphones;
if (headphones)
startPlayer();
else
stopPlayer();
}
}
private class RandomPlayer extends Thread implements MediaPlayer.OnCompletionListener {
private final MainActivity act;
private final Random r;
private final int code;
private MediaPlayer mp;
private boolean keep_going = true;
Object lock2 = new Object();
public RandomPlayer(MainActivity mainActivity) {
r = new Random(System.currentTimeMillis());
act = mainActivity;
code = r.nextInt(10000);
}
public void onCompletion(MediaPlayer arg0) {
playNext();
}
#Override
public void run() {
playNext();
while (keep_going) {
try {
sleep(100);
} catch (InterruptedException e) {
keep_going = false;
}
}
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
playing_title.remove(code);
updateStatus();
}
public void interr() {
keep_going = false;
}
private void playNext() {
synchronized (lock2) {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
//mp.setVolume(0.9f , 0.9f);
mp.setOnCompletionListener(this);
int chosen = r.nextInt(countMusic);
Cursor cur = scanMusic();
for (int i = 0; i < chosen; i++)
cur.moveToNext();
playing_title.put(code, cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)));
try {
int a1 = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
String a2 = cur.getString(a1);
mp.setDataSource(a2);
mp.prepare();
mp.start();
addDebug(a2);
} catch (Exception e) {
Log.e("Randomplayer", "exception", e);
addError(e.getMessage());
}
updateStatus();
}
}
}
}
I have an activity that calls a service on its onCreate , however when I try yo run the project I keep getting an error saying the service has leaked and longer bound on the activity that called/registered it .
"Activity com.xera.deviceinsight.home.DataUsageActivity has leaked ServiceConnection com.xera.deviceinsight.home.DataUsageActivity$3#42676a48 that was originally bound here" I am assuming this might have something to do with the lifecycle of the activity . I have both the activity and the service in question below
myActivity
public class DataUsageActivity extends AppCompatActivity implements MonitorService.ServiceCallback
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TinyDB settings = new TinyDB(this);
if (settings.getBoolean(AppPreferences.HAS_LOGGED_IN))
{
this.bindService(
new Intent(this, MonitorService.class),
serviceConnection,
Context.BIND_AUTO_CREATE);
return;
}
}
public void sendResults(int resultCode, Bundle b)
{
// adapter.notifyDataSetChanged();
}
private ServiceConnection serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName className, IBinder service)
{
MonitorService.LocalBinder binder = (MonitorService.LocalBinder)service;
backgroundService = binder.getService();
backgroundService.setCallback(DataUsageActivity.this);
backgroundService.start();
}
#Override
public void onServiceDisconnected(ComponentName className)
{
backgroundService = null;
}
};
#Override
public void onResume()
{
super.onResume();
if(backgroundService != null)
{
backgroundService.setCallback(this);
}
}
#Override
public void onPause()
{
super.onPause();
if(backgroundService != null)
{
backgroundService.setCallback(null);
}
}
}
**myService**
public class MonitorService extends Service
{
private boolean initialized = false;
private final IBinder mBinder = new LocalBinder();
private ServiceCallback callback = null;
private Timer timer = null;
private final Handler mHandler = new Handler();
private String foreground = null;
private ArrayList<HashMap<String,Object>> processList;
private ArrayList<String> packages;
private Date split = null;
// private Date startTime = null;
public int timeCheckVariable = 0 ;
public static int SERVICE_PERIOD = 5000; // TODO: customize (this is for scan every 5 seconds)
private final ProcessList pl = new ProcessList(this)
{
#Override
protected boolean isFilteredByName(String pack)
{
// TODO: filter processes by names, return true to skip the process
// always return false (by default) to monitor all processes
return false;
}
};
public interface ServiceCallback
{
void sendResults(int resultCode, Bundle b);
}
public class LocalBinder extends Binder
{
MonitorService getService()
{
// Return this instance of the service so clients can call public methods
return MonitorService.this;
}
}
#Override
public void onCreate()
{
super.onCreate();
initialized = true;
processList = ((DeviceInsightApp)getApplication()).getProcessList();
packages = ((DeviceInsightApp)getApplication()).getPackages();
}
#Override
public IBinder onBind(Intent intent)
{
if(initialized)
{
return mBinder;
}
return null;
}
public void setCallback(ServiceCallback callback)
{
this.callback = callback;
}
// private boolean addToStatistics(String target , Long startTime)
private boolean addToStatistics(String target )
{
boolean changed = false;
Date now = new Date();
if(!TextUtils.isEmpty(target))
{
if(!target.equals(foreground))
{
int i;
// timeCheckVariable = i ;
if(foreground != null && split != null)
{
// TODO: calculate time difference from current moment
// to the moment when previous foreground process was activated
i = packages.indexOf(foreground);
timeCheckVariable = i ;
long delta = (now.getTime() - split.getTime()) / 1000;
Long time = (Long)processList.get(i).get(ProcessList.COLUMN_PROCESS_TIME);
if(time != null)
{
// TODO: add the delta to statistics of 'foreground'
time += delta;
}
else
{
time = new Long(delta);
}
processList.get(i).put(ProcessList.COLUMN_PROCESS_TIME, time);
//String applicationName = (String)processList.get(i).get(ProcessList.COLUMN_PROCESS_NAME);
// DatabaseHandler db = new DatabaseHandler(this);
// int x = time.intValue( );
// db.addAppRecord(new AppUsageClass(applicationName , x));
// db.getApplicationCount();
// List<AppUsageClass> appUsageClass = db.getAllApplications();
// db.getApplicationCount();
// for (AppUsageClass cn : appUsageClass) {
//String log = "Id: " + cn.getID() + " ,ApplicationName : " + cn.getName() + " ,TimeSpent: " + cn.getTimeSpent();
// Log.d("Name: ", log);
//}
}
//update count of process activation for new 'target'
i = packages.indexOf(target);
Integer count = (Integer)processList.get(i).get(ProcessList.COLUMN_PROCESS_COUNT);
if(count != null) count++;
else
{
count = new Integer(1);
}
processList.get(i).put(ProcessList.COLUMN_PROCESS_COUNT, count);
foreground = target;
split = now;
changed = true;
}
}
//Long checkTimeNow = (Long)processList.get(timeCheckVariable).get(ProcessList.COLUMN_PROCESS_TIME);
return changed;
}
public void start()
{
if(timer == null)
{
timer = new Timer();
timer.schedule(new MonitoringTimerTask(), 500, SERVICE_PERIOD);
}
// TODO: startForeground(srvcid, createNotification(null));
}
public void stop()
{
timer.cancel();
timer.purge();
timer = null;
}
private class MonitoringTimerTask extends TimerTask
{
#Override
public void run()
{
fillProcessList();
ActivityManager activityManager = (ActivityManager)MonitorService.this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
String current = taskInfo.get(0).topActivity.getPackageName(); // gets the application which is in the foreground
int i = packages.indexOf(current);
Long timecheck = (Long)processList.get(i).get(ProcessList.COLUMN_PROCESS_TIME);
if(addToStatistics(current)&& callback != null)
{
final Bundle b = new Bundle();
// TODO: pass necessary info to UI via bundle
mHandler.post(new Runnable()
{
public void run()
{
callback.sendResults(1, b);
}
});
}
}
}
private void fillProcessList()
{
pl.fillProcessList(processList, packages);
}
The problem is that you don't unbind from you service in .onPause() or in .onDestroy(), so if you Activity is destroyed, connection still last, so there is leaked connection. If you want you service to run all the time, you should start it by .startService() and then bind to it. In .onStop() or .onDestroy() unbind from that service