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....
Related
In my app, there is a login activity first and a home activity. After logging in using volley and passing parameters to home activity in an intent, I'm able to start a foreground service that keeps the app running in background with notifications and getting back to home activity by clicking on the notification with the help of pending intent.
Now, I'm searching for how to open the app from main menu and accessing directly home activity with the pending intent of the foreground service. Maybe should I pass the parameters of the pending intent to the login activity and check them to redirect to home activity, but i'am stuck with this and don't understand.
Here is the login activity Page :
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.signIn);
// Login On Button Click
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();}
});
// THIS IS THE SOLUTION THAT I THOUGHT ABOUT : if the intent is not null open HomeActivity
Intent startinIntent = getIntent();
if (startinIntent.getStringExtra("userLogged") != null && !startinIntent.getStringExtra("userLogged").isEmpty()) {
String userLogged = startinIntent.getStringExtra("userLogged");
Intent startAgain = new Intent(this, HomeActivity.class);
tackBackWork.putExtra("userLogged", userLogged);
startActivity(startAgain);
Log.d("this is the ilue", userLogged);
}
}
private void login(){
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
try {
//input your API parameters
object.put("u",username.getText());
object.put("p",password.getText());
} catch (JSONException e) {
e.printStackTrace();
}
// Enter the correct url for your api service site
String url = getResources().getString(R.string.loginUrl);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String msg = response.getString("msg");
if(msg.contains("true")){
Intent loggedIn = new Intent(LoginActivity.this, HomeActivity.class);
loggedIn.putExtra("userLogged", response.toString());
startActivity(loggedIn);
finish();
}else{
Toast.makeText(getApplicationContext(), "Identifiants Incorrectes", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e){
Toast.makeText(getApplicationContext(), "erreur - 200 ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Volley on error listener", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
Here is the Home activity
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String userLogged = getIntent().getStringExtra("userLogged");
}
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
public void onResume(){
super.onResume();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onPause() {
super.onPause();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
}
Here is foreground Service Page :
public class ForegroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
String userLogged = intent.getStringExtra("userLogged");
Intent backToHomeActivity = new Intent(this, HomeActivity.class);
backToHomeActivity.putExtra("userLogged", userLogged);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, backToHomeActivity, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
// .setLargeIcon()
// .setColor()
.setContentIntent(pendingIntent)
.setContentText(input)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm new to all of this. please help me.
The solution is to use SharedPreferences.
public class LoginActivity extends AppCompatActivity {
Button login;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.loginBtn);
sp = getSharedPreferences("login",MODE_PRIVATE);
if(sp.getBoolean("logged",false)){
goToMainActivity();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToMainActivity();
sp.edit().putBoolean("logged",true).apply();
}
});
}
public void goToMainActivity(){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
See the Tutorial below
https://medium.com/#prakharsrivastava_219/keep-the-user-logged-in-android-app-5fb6ce29ed65
I made application which should send linux command to another device, when are together connected via ust otg.
How can i send my command to another device?
I made communication, and i can read for example model device, now i would like send command to see ip address connected device
Ok, sorry my fault
Here I is my MainActivity
private static final String TAG = "UsbEnumerator";
private TextView mStatusView, mResultView, showCommand;
private Button buttonRefresh, sendCommand;
private UsbManager usbManager;
private EditText writeCommand;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mStatusView = (TextView) findViewById(R.id.mStatusView);
mResultView = (TextView) findViewById(R.id.mResultView);
showCommand = (TextView) findViewById(R.id.showCommand);
buttonRefresh = (Button) findViewById(R.id.buttonRefresh);
sendCommand = (Button) findViewById(R.id.sendCommand);
writeCommand = (EditText) findViewById(R.id.writeCommand);
mResultView.setMovementMethod(new ScrollingMovementMethod());
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
finish();
overridePendingTransition(0,0);
startActivity(i);
overridePendingTransition(0,0);
}
});
sendCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View t) {
SendCommandExecutor exe = new SendCommandExecutor();
String command = writeCommand.getText().toString();
String outp = exe.Executer(command);
showCommand.setText(outp);
Log.d("Output", outp);
}
});
usbManager = getSystemService(UsbManager.class);
IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbReceiver, filter);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbReceiver);
}
BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Delete");
printDeviceDescription(device);
}
}
}
};
private void handleIntent(Intent intent) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Adding");
printDeviceDetails(device);
} else {
printStatus("Remove");
printDeviceList();
}
}
I would like send linux command (for example check ip address) when i have connected device via ust otg. Should i execute command in here?
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Delete");
printDeviceDescription(device);
}
}
}
};
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
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();
}
}
}
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