My Project is about the call recorder.
I want when the call received, my transparent activity open with a button.
I open my activity from my broadcast receiver class.
in this activity, I have a toggle button to activate or deactivate my application.
When a call received, if my toggle button is on, it starts to record the call.
it works OK but when the call is finished, I close my activity from my broadcast receiver class.
like this: first, this is my activity when the call received:
public class Test extends Activity {
static Test tes;
ToggleButton toggleButton;
TextView txt_disable, txt_enable;
private static Context context;
private BroadcastReceiver _closeActivityReceiver = new CloseActivityReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
tes = this;
IntentFilter filter = new IntentFilter("closeNoInternetActivity");
this.registerReceiver(_closeActivityReceiver, filter);
toggleButton = findViewById(R.id.togglebtn);
txt_enable = findViewById(R.id.txt_enable);
txt_disable = findViewById(R.id.txt_disable);
if (isActivityRunning(MainActivity.class)) {
MainActivity.getInstance().finish();
}
final SharedPreferences pref = getSharedPreferences("TOGGLE", MODE_PRIVATE);
boolean sie = pref.getBoolean("STATE", true);
if (sie == true) {
Log.i("mhs", "true");
//to main activity toggleRecord fal hast pass inja user agar bekhad mitone k disable kone
toggleButton.setChecked(true);
toggleButton.setText(null);
toggleButton.setTextOn(null);
toggleButton.setTextOff(null);
toggleButton.setBackgroundResource(R.drawable.record_btn);
txt_disable.setVisibility(View.VISIBLE);
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleRecord.setChecked(false);
toggleButton.setBackgroundResource(R.drawable.not_recording_btn);
finishAffinity();
}
});
} else {
Log.i("mhs", "false");
toggleButton.setChecked(false);
toggleButton.setText(null);
toggleButton.setTextOn(null);
toggleButton.setTextOff(null);
toggleButton.setBackgroundResource(R.drawable.not_recording_btn);
txt_enable.setVisibility(View.VISIBLE);
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleRecord.setChecked(true);
toggleButton.setBackgroundResource(R.drawable.record_btn);
finishAffinity();
}
});
}
}
protected Boolean isActivityRunning(Class activityClass) {
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
return true;
}
return false;
}
private class CloseActivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// close this damn activity!
}
}
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(this._closeActivityReceiver);
}
public static Test getInstance() {
return tes;
}
}
and here is my receiver:
here I start an activity from the receiver like this when I have a phone call
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
Intent i = new Intent(context, Test.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Log.i("mhs","zang khord");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (lastState != TelephonyManager.CALL_STATE_RINGING) {
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
Log.i("mhs","ghat kard");
} else {
isIncoming = true;
callStartTime = new Date();
onIncomingCallAnswered(context, savedNumber, callStartTime);
//vaghti zang mikhore va ghat mikone dar akhar
Log.i("mhs","ghatid");
Intent in = new Intent("closeNoInternetActivity");
context.sendBroadcast(in);
}
and here I close it like this:
case TelephonyManager.CALL_STATE_OFFHOOK:
if (lastState != TelephonyManager.CALL_STATE_RINGING) {
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
Log.i("mhs","ghat kard");
} else {
isIncoming = true;
callStartTime = new Date();
onIncomingCallAnswered(context, savedNumber, callStartTime);
//vaghti zang mikhore va ghat mikone dar akhar
Log.i("mhs","ghatid");
Intent in = new Intent("closeNoInternetActivity");
context.sendBroadcast(in);
}
My problem is that I think my activity doesn't close, and it reminds in the background and causes my activity is transparent, then again I have a phone call. my ringing screen doesn't show on screen.
I think If I able to close my Test activity in right way, my problem solved.
Just copy and paste below code. it should work. If it doesn't then try modifying finish method you can explicitly call destroy method if needed.
public class Test extends Activity {
static Test tes;
private static Context context;
ToggleButton toggleButton;
TextView txt_disable, txt_enable;
private BroadcastReceiver _closeActivityReceiver = new CloseActivityReceiver();
public static Test getInstance() {
return tes;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
tes = this;
IntentFilter filter = new IntentFilter("closeNoInternetActivity");
this.registerReceiver(_closeActivityReceiver, filter);
toggleButton = findViewById(R.id.togglebtn);
txt_enable = findViewById(R.id.txt_enable);
txt_disable = findViewById(R.id.txt_disable);
if (isActivityRunning(MainActivity.class)) {
MainActivity.getInstance().finish();
}
final SharedPreferences pref = getSharedPreferences("TOGGLE", MODE_PRIVATE);
boolean sie = pref.getBoolean("STATE", true);
if (sie == true) {
Log.i("mhs", "true");
//to main activity toggleRecord fal hast pass inja user agar bekhad mitone k disable kone
toggleButton.setChecked(true);
toggleButton.setText(null);
toggleButton.setTextOn(null);
toggleButton.setTextOff(null);
toggleButton.setBackgroundResource(R.drawable.record_btn);
txt_disable.setVisibility(View.VISIBLE);
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleRecord.setChecked(false);
toggleButton.setBackgroundResource(R.drawable.not_recording_btn);
finishAffinity();
}
});
} else {
Log.i("mhs", "false");
toggleButton.setChecked(false);
toggleButton.setText(null);
toggleButton.setTextOn(null);
toggleButton.setTextOff(null);
toggleButton.setBackgroundResource(R.drawable.not_recording_btn);
txt_enable.setVisibility(View.VISIBLE);
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleRecord.setChecked(true);
toggleButton.setBackgroundResource(R.drawable.record_btn);
finishAffinity();
}
});
}
}
protected Boolean isActivityRunning(Class activityClass) {
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
return true;
}
return false;
}
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(this._closeActivityReceiver);
}
public void finish() {
super.finish();
}
private class CloseActivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// close this damn activity!
finish();
}
}
}
Related
Purpose of program: I'm trying to make an app that will count how many times the user checked their phone by issuing a broadcast for Intent.ACTION_SCREEN_ON. it then increments a counter and updates the activity with the new counter.
The problem: This all works just fine but as soon as I swipe away the application from the apps tray, the counter goes back to zero.
obviously what is supposed to happen is the counter would continue.
I tried saving the counter value in the service onDestroy and then calling it again onCreate but onDestroy is never called.
Note that in the onCreate() for the activity it sends a broadcast to the service asking for the most recent value of counter and then updates it in the view. I couldn't find a better way to keep them in sync.
CounterService.java
public class CounterService extends Service {
public static boolean RERUN = true;
private int counter = 0;
private SharedPreferences SP;
private BroadcastReceiver mScreenStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
counter++;
System.out.println("************************************* \n \n " + counter);
}
sendCounterBroadcast();
}
};
public void sendCounterBroadcast() {
Intent i = new Intent();
i.setAction("com.inc.count");
i.putExtra("counterValue", counter);
sendBroadcast(i);
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("********************** CounterService.onCreate()");
// get counter value from SP -- this is useful for when the service gets recreated
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
counter = SP.getInt("counter", 0);
// wait for screen to be turned on or for the activity to ask you for the counter number
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction("send.counter.to.phonecounteractivity");
registerReceiver(mScreenStateBroadcastReceiver, intentFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************************************** CounterService.OnDestroy()");
unregisterReceiver(mScreenStateBroadcastReceiver);
// Save counter value for when we restart service
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
SharedPreferences.Editor SPE = SP.edit();
if (RERUN) {
SPE.putInt("counter", counter);
System.out.println("******************************** RESTARTING SERVICE ");
startService(new Intent(getApplicationContext(), CounterService.class));
} else
SPE.putInt("counter", 0);
SPE.apply();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PhoneCheckerCounter.Java
public class PhoneCheckerCounter extends AppCompatActivity {
private BroadcastReceiver changeCount;
private IntentFilter filter;
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_checker_counter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switcherOnClick();
assignValuesOnCreate();
System.out.println("**************************** onCreate()");
changeCounterText();
}
public void switcherOnClick() {
final Switch sCounter = findViewById(R.id.switchCounter);
sCounter.setOnClickListener(new View.OnClickListener() {
Intent intent = new Intent(getApplicationContext(), CounterService.class);
#Override
public void onClick(View v) {
if (sCounter.isChecked()) {
startService(intent);
CounterService.RERUN = true;
v.getContext().registerReceiver(changeCount, filter);
Toast.makeText(getApplicationContext(), "Counting has begun", Toast.LENGTH_SHORT).show();
} else {
TextView n = findViewById(R.id.counter);
n.setText("0");
CounterService.RERUN = false;
v.getContext().unregisterReceiver(changeCount);
stopService(intent);
Toast.makeText(getApplicationContext(), "The application stopped counting", Toast.LENGTH_SHORT).show();
}
}
});
}
public void changeCounterText() {
changeCount = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView n = findViewById(R.id.counter);
counter = intent.getIntExtra("counterValue", 0);
System.out.println("************************ RECEIVED!!!! value of: " + counter);
n.setText("" + counter);
}
};
filter = new IntentFilter();
filter.addAction("com.inc.count");
this.registerReceiver(changeCount, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(changeCount);
assignValuesOnDestroy();
System.out.println("**************************** onDestroy()");
}
public void assignValuesOnCreate() {
Switch s = findViewById(R.id.switchCounter);
if (getSwitchValueFromSP() == 1) s.setChecked(true);
else s.setChecked(false);
Intent f = new Intent();
f.setAction("send.counter.to.phonecounteractivity");
sendBroadcast(f);
}
public void assignValuesOnDestroy() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = SP.edit();
Switch s = findViewById(R.id.switchCounter);
if (s.isChecked()) edit.putInt("switch", 1);
else edit.putInt("switch", 0);
edit.apply();
}
public int getSwitchValueFromSP() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
int isOn = SP.getInt("switch", 0);
return isOn;
}
}
Sample of the activity
I have a service that runs in the background and every 15 minutes, it will show a notification or dialog. But how can I get it to start and stop OnClick of a FAB?
The button shows a Snack Bar OnClick, currently. I want to add If/Else code to start and stop the service. How can I do this?
Here is the service:
public class SafeService extends Service {
private Handler mHandler = new Handler();
private Timer mTimer = null;
public static final int NOTIFICATION_ID = 1;
public static final long NOTIFY_INTERVAL = 900 * 1000; // 15 Minutes
/*^TODO - TEST NOTIFY_INTERVAL FOR ACCURACY^*/
/*^Those are for the timer and handler so the code
can recognise it^ The last one gives how long the timer runs */
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// Cancels the timer if it already existed.
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// Lollipop or Above
if (Build.VERSION.SDK_INT >= 21) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(SafeService.this);
new NotificationCompat.Builder(SafeService.this);
builder.setSmallIcon(R.drawable.smallplaceholder);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Safeguard");
builder.setContentText("Be careful, Trainer! Remember to look up and stay aware of your surroundings!!");
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("Be careful, Trainer! Remember to look up and stay aware of your surroundings!!"));
builder.setPriority(Notification.PRIORITY_HIGH);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
//Below Lollipop
} else {
new MaterialDialog.Builder(SafeService.this)
.title(R.string.warning_title)
.content(R.string.warning)
.positiveText(R.string.button_ok)
.show();
}
}
});
}
};
}
Here is the button I want to start and stop the service:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Safeguard is now on!", Snackbar.LENGTH_LONG).show();
//Start service after showing SnackBar
}
});
You can use a Singleton instance which will bind/unbind from your service, this way, the service will not be unbound if your activity is destroyed by Android :
ServiceSingleton.java :
public class ServiceSingleton {
private String TAG = ServiceSingleton.class.getSimpleName();
private static ServiceSingleton mInstance;
private Context mContext;
private boolean mBound = false;
private SafeService mService;
private ServiceConnection mServiceConnection = null;
public static ServiceSingleton getInstance(Context context) {
if (mInstance == null)
mInstance = new ServiceSingleton(context);
return mInstance;
}
private ServiceSingleton(Context context) {
this.mContext = context.getApplicationContext();
}
public boolean startNotification() {
if (!mBound) {
mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
Log.i(TAG, "onServiceConnected");
mService = ((SafeService.LocalBinder) service).getService();
mService.startNotification();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
Intent intent = new Intent(this, SafeService.class);
mBound = mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
if (!mBound) {
Log.e(TAG, "Error cant bind to service !");
}
} else {
if (mService != null) {
mService.startNotification();
}
}
return mBound;
}
public void stopNotification() {
if (mBound && mService != null) {
mService.stopNotification();
}
}
public boolean isNotificationStarted() {
if (mBound && mService != null) {
return mService.isNotificationStarted();
}
return false;
}
public void close() {
try {
if (mBound) {
if (mService!=null){
mService.stopNotification();
}
mContext.unbindService(mServiceConnection);
mBound = false;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public boolean isBound() {
return mBound;
}
}
In your onCreate()
mSingleton = ServiceSingleton.getInstance();
For your click listener :
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mSingleton.isNotificationStarted()){
mSingleton.startNotification();
}
else {
mSingleton.stopNotification();
}
}
});
stopNotification() wont unbind service if you want to reuse it, if you want to shut it down call close()
sorry my question is may be very simple for all of you. But I am new and need solution for it. If you can help me for solve it.
I have one quote application which have function for check new quote from server in main activity, its checking with server on loading Main Activity that there new quotes available or not and if available its opening one popup window for go setting activity for download new quotes, and if user press setting button than its taking user to setting activity. I need some changes in it. I want automatic download new quotes from main activity without go setting activity. both activity are like below
Thanks
public class MainActivity extends Activity {
SharedPreferences mSharedPreferences;
//String qotdId;
private AdView mAdView;
private InterstitialAd mInterstitial;
public static boolean active;
DAO db;
String siteUrl, updatesUrl;
int lastAuthor, lastQuote;
private ConnectionDetector cd;
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
active = true;
}
#Override
protected void onStop() {
super.onStop();
active = false;
}
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
/* Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
Toast.makeText(MainActivity.this, "Please Push Download Button And Save Status in Your Mobile For Just One Time", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
*/
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
db = new DAO(this);
db.open();
cd = new ConnectionDetector(MainActivity.this);
siteUrl = getResources().getString(R.string.siteUrl);
updatesUrl = siteUrl + "site/get_updates/" + String.valueOf(lastAuthor) + "/" + String.valueOf(lastQuote);
if (cd.isConnectingToInternet()) {
// Internet Connection is not present
Intent checkUpdates = new Intent(MainActivity.this, CheckUpdatesService.class);
startService(checkUpdates);
}
// generateKeyHash();
final ImageButton quotes = (ImageButton) findViewById(R.id.quotes);
quotes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 1);
intent.putExtra("itemSelected", 0);
startActivity(intent);
}
});
final ImageButton authors = (ImageButton) findViewById(R.id.authors);
authors.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
AuthorsActivity.class);
startActivity(intent);
}
});
final ImageButton favorites = (ImageButton) findViewById(R.id.favorites);
favorites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 2);
startActivity(intent);
}
});
final ImageButton settings = (ImageButton) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
}
});
}
}
And my other activity
public class SettingsActivity extends PreferenceActivity {
static final int TIME_DIALOG_ID = 999;
private AdView mAdView;
private InterstitialAd mInterstitial;
private static final String MY_PREFERENCES = "my_preferences";
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
}
#Override
protected void onStop() {
//unregisterReceiver(receiver);
super.onStop();
}
// ==========================================================================================================//
DAO db;
// Progress dialog
ProgressDialog pDialog;
PreferenceScreen preferenceScreen;
private static SharedPreferences mSharedPreferences;
UpdateClass update;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
Preference more, rate, about, check, share,status,background, progress = null;
PreferenceCategory socialsCategory;
private MyDownloadReceiver receiver;
// ==============================================================================
//////////////////// First Load /////////////////
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
//TWITTER_CONSUMER_KEY = getResources().getString(
// R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(
// R.string.TWITTER_CONSUMER_SECRET);
//TWITTER_CALLBACK_URL = "oauth://"
// + getApplicationContext().getPackageName()
// + ".SettingsActivity";
//uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
addPreferencesFromResource(R.layout.settings);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
check = (Preference) findPreference("check");
about = (Preference) findPreference("about");
more = (Preference) findPreference("more");
rate = (Preference) findPreference("rate");
status = (Preference) findPreference("status");
share = (Preference) findPreference("share");
background = (Preference) findPreference("background");
socialsCategory = (PreferenceCategory) findPreference("socials");
preferenceScreen = getPreferenceScreen();
check.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
update = new UpdateClass(SettingsActivity.this);
update.handleUpdates();
//if (mInterstitial.isLoaded()) {
// mInterstitial.show();
//}
return false;
}
});
// ==============================================================================
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsActivity.this,
AboutActivity.class);
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
return false;
}
});
// ==============================================================================
background
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.equals(true)) {
db.updateSetting("background", "1");
} else {
db.updateSetting("background", "0");
}
return true;
}
});
// ==============================================================================
// ==============================================================================
rate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindishayari2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
more.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String developerName = "karopass";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q="+ developerName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q="+ developerName)));
}
return true;
}
});
share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "आज ही डाउनलोड करे हिंदी शायरी एप्लीकेशन और पाइए बेस्ट हिंदी शायरी.इस एप्लीकेशन में 3000 से भी ज्यादा बढ़िया हिंदी शायरी का कलेक्शन है जिसे आप पढने या शेर करने के लिए यूज कर सकते है !! आज ही डाउनलोड करे !! http://play.google.com/store/apps/details?id=com.karopass.hindishayari2016";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " ");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
});
// ==============================================================================
status.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindi_status_2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
IntentFilter filter = new IntentFilter(MyDownloadReceiver.ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MyDownloadReceiver();
registerReceiver(receiver, filter);
}
void showProgressBar() {
progress = new MyProgressBarPreference(this);
preferenceScreen.addPreference(progress);
}
void setDownloadProgress(int percent) {
if (progress != null) {
((MyProgressBarPreference)progress).setProgress(percent);
((MyProgressBarPreference)progress).setLabel("Please wait... " +percent + "%"+" Downloading Done");
}
}
void hideProgressBar()
{
if (progress != null)
preferenceScreen.removePreference(progress);
}
public class MyDownloadReceiver extends BroadcastReceiver {
public static final String ACTION = "com.karopass.hindishayari2016.intent.action.DOWNLOAD";
public static final int INITIALIZE = 0x001;
public static final int DOWNLOAD = 0x002;
public static final int FINISH = 0x003;
public static final String EXTRA_STATUS = "status";
public static final String EXTRA_PERCENT = "percent";
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_STATUS, -1);
Log.d("DESOLF", "receive broadcast : " + status);
switch(status) {
case INITIALIZE:
showProgressBar();
break;
case DOWNLOAD:
int percent = intent.getIntExtra(MyDownloadReceiver.EXTRA_PERCENT, 0);
setDownloadProgress(percent);
break;
case FINISH:
hideProgressBar();
//Toast.makeText(SettingsActivity.this, "Downloaded successfully", Toast.LENGTH_LONG).show();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
break;
default:
}
}
}
public class MyProgressBarPreference extends Preference {
public MyProgressBarPreference(Context context) {
super(context);
}
public MyProgressBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyProgressBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private ImageView mStatusIcon;
private ProgressBar mProgressBar;
private TextView mStatusText ;
private int lastReqProgress=-1;
private int lastReqMax=-1;
private String lastLabel;
#Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View myLayout=li.inflate(R.layout.download_progress, null, false);
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
mStatusIcon = (ImageView) myLayout.findViewById(R.id.status_icon);
mStatusIcon.startAnimation(anim);
mProgressBar=(ProgressBar) myLayout.findViewById(R.id.status_progress);
mStatusText=(TextView) myLayout.findViewById(R.id.status_text);
mStatusIcon.setImageResource(R.drawable.rotate);
mProgressBar.setProgress(0);
mStatusText.setText(0 + "%");
return myLayout;
}
public void setIcon(int resId) {
mStatusIcon.setImageResource(resId);
}
public void setProgress(int value){
if (mProgressBar!=null){
mProgressBar.setProgress(value);
} else {
lastReqProgress=value;
}
}
public void setMax(int value){
if (mProgressBar!=null){
int savedprogress=mProgressBar.getProgress();
mProgressBar.setMax(0);
mProgressBar.setMax(value);
mProgressBar.setProgress(savedprogress);
} else {
lastReqMax=value;
}
}
public void setLabel(String text){
if (lastLabel!=null){
mStatusText.setText(text);
} else {
lastLabel=text;
}
}
}
}
You can try this code:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
Don't forget to add your Second Activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="SecondActivity"/>
Android Page
I'm using this code:
public class ActivityMain extends Activity {
private static final String TAG = "MainActivity";
private ServiceSpeechRecognition service;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
ServiceSpeechRecognition.MyBinder b = (ServiceSpeechRecognition.MyBinder) binder;
service = b.getService();
Log.e(TAG, "Service connected");
}
public void onServiceDisconnected(ComponentName className) {
savePrefs();
service = null;
Log.e(TAG, "Service disconnected");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
setContentView(R.layout.activity_ui_main);
getPackageManager().setComponentEnabledSetting(new ComponentName(this, getPackageName() + ".MainActivity-Alias"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
#Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume");
GoogleSearchApi.registerQueryGroup(this, ReceiverGoogleSearch.group);
// Load prefs
SharedPreferences prefs = ActivityMain.getPrefs(this);
String key_phrase = prefs.getString(Preferences.KEY_PHRASE_KEY, Preferences.DEFAULT_KEY_PHRASE);
boolean require_charge = prefs.getBoolean(Preferences.KEY_REQUIRE_CHARGER, true);
// Update Ui
EditText text = (EditText) findViewById(R.id.key_phrase);
text.setText(key_phrase);
CheckBox checkbox = (CheckBox) findViewById(R.id.require_battery);
checkbox.setChecked(require_charge);
// If should, start intent
if (!require_charge || Util.isCharging(this)) {
bindIntent();
}
}
#Override
protected void onPause() {
if (service != null) {
Log.e(TAG, "Unbind");
unbindService(mConnection);
}
super.onPause();
}
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
bindService(intent, mConnection, 0);
}
public void setKeyPhrase(View view) {
savePrefs();
if (service != null) {
EditText text = (EditText) findViewById(R.id.key_phrase);
String key_phrase = text.getText().toString();
service.setKeyPhrase(key_phrase);
}
Toast.makeText(this, R.string.str_key_phrase_updated, Toast.LENGTH_SHORT).show();
}
public void setRequireCharge(View view) {
savePrefs();
CheckBox checkbox = (CheckBox) view;
boolean require_charge = checkbox.isChecked();
if (service != null) {
service.setRequiresCharge(require_charge);
} else if (!require_charge || Util.isCharging(this)) {
bindIntent();
}
}
public void savePrefs() {
EditText text = (EditText) findViewById(R.id.key_phrase);
String key_phrase = text.getText().toString();
CheckBox checkbox = (CheckBox) findViewById(R.id.require_battery);
boolean require_charge = checkbox.isChecked();
SharedPreferences.Editor prefs = ActivityMain.getPrefs(this).edit();
prefs.putString(Preferences.KEY_PHRASE_KEY, key_phrase);
prefs.putBoolean(Preferences.KEY_REQUIRE_CHARGER, require_charge);
prefs.commit();
}
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(Preferences.KEY, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
}
this is an activity in which starts a service.. The problem is that the service starts as soon as the activity it opens. I would create a button or checkbox to start it. But now when I open the activity it starts the service. I didn't write any startService() in the onCreate() method.
Here You Start Your Service in On Resume so Replace
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
bindService(intent, mConnection, 0);
}
to
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
bindService(intent, mConnection, 0);
}
Put below code in your button click event.
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
Thats it....
I cant figure out why i cant set text to my textView tv.
getting:
E/AndroidRuntime(686): android.view.ViewRoot$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
I tried many ways to make it right.
As you can see i tried Handler because i had the same problem with toasts. Now toast works but setText doesnt :((
Please someone help me, how should i configure this handler?
public class calculate extends Activity implements OnClickListener {
private myService myService; //bound service instance
private boolean serviceStarted;
View show_map;
View data;
View start;
View stop;
public TextView tv;
private Location loc;
private boolean initiated=false;
private float distance=0;
UIHandler uiHandler;
route_calc rc;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.calculate);
tv=(TextView)findViewById(R.id.textView1);
show_map=findViewById(R.id.button1);
show_map.setOnClickListener(this);
data=findViewById(R.id.button2);
data.setOnClickListener(this);
start=findViewById(R.id.button3);
start.setOnClickListener(this);
stop=findViewById(R.id.button4);
stop.setVisibility(View.INVISIBLE);
stop.setOnClickListener(this);
HandlerThread uiThread = new HandlerThread("UIHandler");
uiThread.start();
uiHandler = new UIHandler( uiThread.getLooper());
}
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View v) {
Intent i;
switch(v.getId()){
case R.id.button1:
i=new Intent(this,Map.class);
startActivity(i);
break;
case R.id.button2:
i=new Intent(this,data.class);
startActivity(i);
break;
case R.id.button3:
startService();
break;
case R.id.button4:
stopService();
break;
}
}
//connection between this activity and service myService
ServiceConnection myServConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName arg0) {
myService = null;
}
#Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
myService = ((myService.MyBinder)binder).getMyService();
}
};
private void startService() {
Intent intent = new Intent(this, myService.class);
startService(intent);
//Bind MyService here
bindService(intent, myServConn, BIND_AUTO_CREATE);
stop.setVisibility(View.VISIBLE);
serviceStarted = true;
rc = new route_calc();
rc.start();
}
private void stopService() {
if(serviceStarted) {
Intent intent = new Intent(this, myService.class);
//Unbind MyService here
unbindService(myServConn);
stopService(intent);
stop.setVisibility(View.INVISIBLE);
serviceStarted = false;
}
}
void showToast(String s){
handleUIRequest(s);
}
void setText(){
handleUISetText();
}
class route_calc extends Thread{
Location begin;
public void run() {
float temp;
while(!initiated){
try{
loc=myService.getLocation();
}
catch(Exception e){
}
if(loc!=null){
begin=loc;
initiated=true;
showToast("zadzialalo");
}
}
while(true){
loc=myService.getLocation();
temp=begin.distanceTo(loc);
distance=distance+temp;
tv.setText("przejechales "+distance+" m");
System.err.println(distance);
begin=loc;
try {
this.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private final class UIHandler extends Handler
{
public static final int DISPLAY_UI_TOAST = 0;
public static final int TV_SET_TEXT = 1;
public UIHandler(Looper looper)
{
super(looper);
}
public void handleMessage(Message msg)
{
switch(msg.what)
{
case UIHandler.DISPLAY_UI_TOAST:
{
Context context = getApplicationContext();
Toast t = Toast.makeText(context, (String)msg.obj, Toast.LENGTH_LONG);
t.show();
}
case UIHandler.TV_SET_TEXT:
{
tv.setText("przejechałeś "+distance+" m");
}
default:
break;
}
}
}
protected void handleUIRequest(String message)
{
Message msg = uiHandler.obtainMessage(UIHandler.DISPLAY_UI_TOAST);
msg.obj = message;
uiHandler.sendMessage(msg);
}
protected void handleUISetText(){
Message msg=uiHandler.obtainMessage(UIHandler.TV_SET_TEXT);
uiHandler.sendMessage(msg);
}
}
It seems like you put your entire Activity here, and that it also includes a service, and you didn't try to narrow down your problem.
in your route_calc thread you call showToast, this is probably one of your problems, you should call showToast (or any other UI function) from your Handler.
Something like this:
Do anything you want on your thread:
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
someHeavyStuffHere(); //Big calculations or file download here.
handler.sendEmptyMessage(SUCCESS);
}
catch (Exception e)
{
handler.sendEmptyMessage(FAILURE);
}
}
}).start();
When your data is ready, tell the handler to put it in a view and show it:
protected Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == SUCCESS)
{
setCalculatedDataToaView(); // the data you calculated from your thread can now be shown in one of your views.
}
else if (msg.what == FAILURE)
{
errorHandlerHere();//could be your toasts or any other error handling...
}
}
};