In my program, I have only 1 button. And first press the program will output a random string. If the user presses it again to stop, my program will slow random (delay) the same slot machine. How can I do it?
my code
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while (showRandom) {
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Ignoring the MediaPlayer part, I think it should be this way:
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Randomsentence.R;
public class Randomsentence extends Activity {
TextView txt;
int random;
public String[] myStrings;
Button bt1;
private static final int MESSAGE_RANDOM = 1;
private static final long MIN_INTERVAL = 500;
private static final long MAX_INTERVAL = 1500;
private static final long STEP = 60;
private long mInterval = 0;
private boolean mStarted = false;
private Random mRandom = new Random();
private Handler mHandler = new Handler() {
#Override
public void handleMessage (Message msg) {
if(msg.what == MESSAGE_RANDOM) {
showRandomString();
if(mStarted) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
} else {
if(mInterval <= MAX_INTERVAL) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
mInterval += STEP;
} else {
this.removeMessages(MESSAGE_RANDOM);
Toast.makeText(Randomsentence.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(mBt1OnClick);
myStrings = getResources().getStringArray(R.array.myArray);
}
private void showRandomString() {
final int index = mRandom.nextInt(myStrings.length - 1);
txt.setText(myStrings[index]);
}
private OnClickListener mBt1OnClick = new OnClickListener() {
#Override
public void onClick(View v) {
if(!mStarted) {
// Start
Toast.makeText(Randomsentence.this, "Started!", Toast.LENGTH_SHORT).show();
mStarted = true;
mInterval = MIN_INTERVAL;
mHandler.removeMessages(MESSAGE_RANDOM);
mHandler.sendEmptyMessage(MESSAGE_RANDOM);
} else {
// Stop
mStarted = false;
Toast.makeText(Randomsentence.this, "Stoping...", Toast.LENGTH_SHORT).show();
}
}
};
}
Related
So I am working on Nordic nrf52840 which is broadcasting extended advertising, thanks to the people on stackoverflow I can finally find my device, now the only function left is to dump extended advertising data to log, I found out that ScanResult contain may have contain the adv data I need but when I tried to dump it to log it show only {} why and how can I read adv data.
package com.example.tryble_scanner;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothLeScanner mBluetoothLeScanner = null;
public static final int REQUEST_BT_PERMISSIONS = 0;
public static final int REQUEST_BT_ENABLE = 1;
private boolean mScanning = false;
private Handler mHandler = null;
private ScanCallback mLeScanCallBack1 = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
//super.onScanResult(callbackType, result);
String data=ConverttoString(result.getScanRecord().getManufacturerSpecificData());
BluetoothDevice btdevice = result.getDevice();
Log.d("BLE", btdevice.getAddress());
Log.d("BLE",data);
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.d("BLE", "error");
}
};
private ScanCallback mLeScanCallBack2=new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.d("BLE","scan stop");
}
#Override
public void onScanFailed(int errorCode) {
Log.d("BLE","stop scan failed");
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallBack3=new
BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnScan = (Button) findViewById(R.id.btnScan);
BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
this.mHandler = new Handler();
}
public void stop_scan(View view) {
Log.d("Ble","scan stop pressed");
// mBluetoothLeScanner.stopScan(mLeScanCallback2);
mBluetoothAdapter.getBluetoothLeScanner().stopScan(mLeScanCallBack2);
}
public void onBtnScan(View view) {
Log.i("Btn","get click");
checkBTPermission();
String[] names=new String[]{"Auden test"};
List<ScanFilter> filters=null;
if(names != null){
filters=new ArrayList<>();
for(String name:names){
ScanFilter filter=new ScanFilter.Builder().setDeviceName(name).build();
filters.add(filter);
}
}
ScanSettings scanSettings = new ScanSettings.Builder()
//.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
//.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
//.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
//.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
//.setReportDelay(0L)
.setLegacy(false)
.build();
if(mBluetoothLeScanner==null){
Log.i("BLE","could not get scanner");
}else{
mBluetoothLeScanner.startScan(filters,scanSettings,mLeScanCallBack1); //filters,scanSettings,mLeScanCallback
}
}
private void checkBTPermission(){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
int pc=this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
pc+=this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(pc!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}else {
Log.d("BLE","checkBT permission");
}
}
}
public static String ConverttoString (SparseArray<byte[]> array) {
if (array == null) {
return "null";
}
if (array.size() == 0) {
return "{}";
}
StringBuilder buffer = new StringBuilder();
buffer.append('{');
for (int i = 0; i < array.size(); ++i) {
buffer.append(array.keyAt(i)).append("=").append(Arrays.toString(array.valueAt(i)));
}
buffer.append('}');
Log.d("convert",buffer.toString());
return buffer.toString();
}
}
I have been stuck for hours . I have integrated admob ads on my application and I add it when user write something in edit text but it takes time to load ads some times it comes while some times skip .So user type the text and move to the next activity and my ads not load in time .
Can you give me some solution how to solve this issue !
thanks in advance
PassValues.java
package com.logixcess.wordguessing;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Button;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by ert on 17/04/2016.
*/
public class Passvalues {
public static String[] words , toCompare;
public static int score = 0,staticScore = 0,prevScore = 0,correctCount = 0;
public static String selectedWord;
public static List<String> repeated = null;
public static List<Button> buttonList = new ArrayList<Button>();
public static int[] hiscore = new int[5];
public static String[] hiscorename = new String[5];
public static MediaPlayer mediaPlayer;//sounds
public static MediaPlayer tones;//music
static float volLeft = 70,volRight = 70;
public static boolean sound = true,music=true;
public static boolean adCheck = false;
public static InterstitialAd interstitial;
public Passvalues()
{
words=null ; toCompare=null;
score = 0;prevScore = 0;correctCount = 0;
selectedWord="";
repeated = null;
buttonList = new ArrayList<Button>();
hiscore = new int[5];
hiscorename = new String[5];
adCheck = false;
}
public static void playMusic(Context context,int id)
{
if(Passvalues.music)
{
if(tones != null)
{
if (!tones.isPlaying()) {
tones = MediaPlayer.create(context, id);
tones.setLooping(true);
tones.start();
}
}
else {
tones = MediaPlayer.create(context, id);
tones.setLooping(true);
tones.start();
}
}
}
public static void stopMusic(){
/* if(!Passvalues.sound) {
if(tones != null)
{
if(tones.isPlaying()) {
stopPlaying(tones);
}
}
else
{
tones = null;
stopPlaying(tones);
}
}*/
if((!Passvalues.music)&&(!Passvalues.sound))
{
if(tones!=null)
{
stopPlaying(tones);
tones=null;
}
else
{
//pehlay se hi band hai music
}
if(mediaPlayer!=null)
{
stopPlaying(mediaPlayer);
mediaPlayer=null;
}
else
{
//peh;ay se hi sound band hai
}
}
}
public static void playSound(Context context,int id){
if(Passvalues.sound)
{
mediaPlayer = MediaPlayer.create(context, id);
mediaPlayer.start();
}
else if(mediaPlayer != null)
{
if(mediaPlayer.isPlaying()) {
stopPlaying(mediaPlayer);
}
if(mediaPlayer != null)
stopPlaying(mediaPlayer);
}
}
public static void stopPlaying(MediaPlayer mp)
{
if(mp!=null)
{
mp.stop();
mp.release();
mp=null;
}
}
public static boolean showad(Context context)
{
if(isNetworkAvailable(context))
{
if(interstitial == null)
interstitial = new InterstitialAd(context);
interstitial.setAdUnitId("ca-app-pub-7328520387956873/2174089947");
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
interstitial.loadAd(adRequest);
return true;
}
return false;
}
private static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
EnterHighScore.java
this is the activity for ads
package com.logixcess.wordguessing;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.logixcess.wordguessing.R;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.ads.AdListener;
public class EnterHiscore extends Activity {
int score;
EditText namebox;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
onBackPressed();
super.onKeyDown(keyCode, event);
return true;
}
#Override
public void onBackPressed() {
Intent setIntent = new Intent(EnterHiscore.this,MainScreen.class);
//setIntent.addCategory(Intent.CATEGORY_HOME);
//setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set screen full screen and no title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.enterhiscore);
Passvalues.showad(EnterHiscore.this);
View backgroundImage = findViewById(R.id.bak);
Drawable background = backgroundImage.getBackground();
background.setAlpha(90);
//get score
score = Passvalues.staticScore; //getIntent().getIntExtra("score", 0);
//declare views
namebox = (EditText) findViewById(R.id.namebox);
Button save = (Button) findViewById(R.id.save);
namebox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!Passvalues.adCheck) {
Passvalues.interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
if (Passvalues.interstitial.isLoaded()) {
Passvalues.interstitial.show();
}
}
#Override
public void onAdClosed() {
//finish();
Passvalues.interstitial = null;
}
});
Passvalues.adCheck = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
process_highscore(score, namebox.getText().toString());
}
});
}
public void loadscore() {
// load preferences
SharedPreferences hiscores = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
for (int i = 0; i < 5; i++) {
Passvalues.hiscore[i] = hiscores.getInt("score" + i, 0);
Passvalues.hiscorename[i] = hiscores.getString("name" + i, "---");
}
}
public void savescore() {
//load preferences
SharedPreferences hiscores = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor hiscores_editor = hiscores.edit();
for (int i = 0; i < 5; i++) {
hiscores_editor.putInt("score" + i, Passvalues.hiscore[i]);
hiscores_editor.putString("name" + i, Passvalues.hiscorename[i]);
}
hiscores_editor.commit();
loadscore();
}
public void process_highscore(int score, String name){
System.out.println("ll"+score + name);
loadscore();
boolean ready = false;
if (score > Passvalues.hiscore[0]) {
Passvalues.hiscore[4] = Passvalues.hiscore[3];
Passvalues.hiscorename[4] = Passvalues.hiscorename[3];
Passvalues.hiscore[3] = Passvalues.hiscore[2];
Passvalues.hiscorename[3] = Passvalues.hiscorename[2];
Passvalues.hiscore[2] = Passvalues.hiscore[1];
Passvalues.hiscorename[2] = Passvalues.hiscorename[1];
Passvalues.hiscore[1] = Passvalues.hiscore[0];
Passvalues.hiscorename[1] = Passvalues.hiscorename[0];
Passvalues.hiscore[0] = score;
Passvalues.hiscorename[0] = name;
ready = true;
}
if (score > Passvalues.hiscore[1] && score <= Passvalues.hiscore[0] && !ready) {
Passvalues.hiscore[4] = Passvalues.hiscore[3];
Passvalues.hiscorename[4] = Passvalues.hiscorename[3];
Passvalues.hiscore[3] = Passvalues.hiscore[2];
Passvalues.hiscorename[3] = Passvalues.hiscorename[2];
Passvalues.hiscore[2] = Passvalues.hiscore[1];
Passvalues.hiscorename[2] = Passvalues.hiscorename[1];
Passvalues.hiscore[1] = score;
Passvalues.hiscorename[1] = name;
ready = true;
}
if (score > Passvalues.hiscore[2] && score <= Passvalues.hiscore[1] && !ready) {
Passvalues.hiscore[4] = Passvalues.hiscore[3];
Passvalues.hiscorename[4] = Passvalues.hiscorename[3];
Passvalues.hiscore[3] = Passvalues.hiscore[2];
Passvalues.hiscorename[3] = Passvalues.hiscorename[2];
Passvalues.hiscore[2] = score;
Passvalues.hiscorename[2] = name;
ready = true;
}
if (score > Passvalues.hiscore[4] && score <= Passvalues.hiscore[3] && !ready) {
Passvalues.hiscore[4] = score;
Passvalues.hiscorename[4] = name;
}
savescore();
Intent i=new Intent(EnterHiscore.this,Highscore.class);
startActivity(i);
//go back to hiscores
finish();
}
}
Instead of displaying the ad in the #onAdLoaded() callback, display it in the natural break point in #onTextChanged():
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!Passvalues.adCheck) {
if (Passvalues.interstitial.isLoaded()) {
Passvalues.interstitial.show();
}
Passvalues.interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
#Override
public void onAdClosed() {
//finish();
Passvalues.interstitial = null;
}
});
Passvalues.adCheck = true;
}
}
I am trying to access a method from a java class by a another java class. I have created the object of the class and import the class into my java class but i am not able to access it my code.
package com.example.musicplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.R.string;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Playlists;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public static final String MEDIA_PATH = new String("/sdcard/");
private List<String> songs = new ArrayList<String>();
public MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
public MediaPlayer getmp(){
return mp;
}
public void setmp(MediaPlayer mp){
this.mp = mp;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
updateSongList();
}
private void updateSongList() {
// TODO Auto-generated method stub
File home = new File(MEDIA_PATH);
if(home.listFiles(new Mp3Filter()).length > 0){
for(File file: home.listFiles(new Mp3Filter())){
songs.add(file.getName());
}
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.song_item, songs);
setListAdapter(songList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
currentPosition = position;
playSong(MEDIA_PATH + songs.get(position));
//Toast.makeText(getApplicationContext(), songs.get(position).toString(), Toast.LENGTH_SHORT).show();
final String songName = songs.get(position).toString();
//final TextView textchange = (TextView) v.findViewById(R.id.current_song_name);
Intent in = new Intent(this, current_song.class);
in.putExtra("song_name", songName);
startActivity(in);
//Toast.makeText(getApplicationContext(), "End of Song List", Toast.LENGTH_SHORT).show();
//textchange.setText(songName);
}
private void playSong(String songPath) {
// TODO Auto-generated method stub
try{
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
auto_nextSong();
}
});
}
catch (Exception e) {
// TODO: handle exception
}
}
public void pause(){
mp.pause();
}
public void stop(){
mp.stop();
}
public void next(){
Toast.makeText(getApplicationContext(), "In Next()", Toast.LENGTH_SHORT).show();
if(currentPosition < songs.size()){
currentPosition = currentPosition + 1;
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
public void prv(){
if(currentPosition > songs.size()){
currentPosition = currentPosition - 1;
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
private void auto_nextSong() {
// TODO Auto-generated method stub
if(++currentPosition >= songs.size()){
currentPosition = 0;
Toast.makeText(getApplicationContext(), "End of Song List", Toast.LENGTH_SHORT).show();
}
else{
playSong(MEDIA_PATH + songs.get(currentPosition));
Toast.makeText(getApplicationContext(), "Next Song", Toast.LENGTH_SHORT).show();
}
}
}
from the above class i am trying to access pause() and stop()
this is my class where i am trying to access
package com.example.musicplayer;
import com.example.musicplayer.MainActivity;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class current_song extends Activity implements OnClickListener{
public MainActivity ma;
protected void onCreate(Bundle icicle, MainActivity ma) {
Bundle extra = getIntent().getExtras();
super.onCreate(icicle);
setContentView(R.layout.songplay_page);
if(extra != null){
String song_name = extra.getString("song_name");
TextView textchange = (TextView)findViewById(R.id.current_song_name);
textchange.setText(song_name);
textchange.setSelected(true);
}
//MainActivity ma = ((MainActivity)getApplicationContext());
//MediaPlayer mp = ma.getmp();
this.ma = ma;
Button btn_pause = (Button)findViewById(R.id.pause_btn);
btn_pause.setOnClickListener(this);
Button btn_next = (Button)findViewById(R.id.next_btn);
btn_next.setOnClickListener(this);
Button btn_prv = (Button)findViewById(R.id.prv_btn);
btn_prv.setOnClickListener(this);
Button btn_stop = (Button)findViewById(R.id.stop_btn);
btn_stop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "In Onclick ()", Toast.LENGTH_SHORT).show();
switch(v.getId())
{
case R.id.pause_btn:
((MainActivity)ma).pause();
break;
case R.id.next_btn:
//ma.next();
break;
case R.id.prv_btn:
//ma.prv();
break;
case R.id.stop_btn:
((MainActivity)ma).stop();
break;
}
}
}
The concept is that i want to stop, pause the music which is playing. If my logic i wrong please guide me how to do it else please help me how to control my current music in Current music java class.
Please, move all your music playing code into Service. Activities don't work that way.
Consider the following:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
http://developer.android.com/reference/android/app/Service.html
I think You are new to android but no problem: See you can not call the functions of activity from any other class like this (Object.method();)
SO For this type of handling You Should Create a inner Handler class which extends Handler inside your MainActivity. and override onHandle(message msg){} method of it.
And When You start current_song activity pass this handler object in the intent.
And when you want to perform any task from your MainActivity (like stop, pause), pass messages through that handler like object.sendmessage(new msgObject("stop"));
And inside you onHandle() method call your stop or pause methods through diffrentiating command received from the message object.
like if(message's content == stop) MainActivity.this.stop();
I've made an apache thrift server and I have a service which contains several functions.
I'm trying to figure out what is the best way to make calls to the remote server from my android application.
My problem is that I can't make calls from the MainActivity thread (the main thread) - and I need to use most of the remote functions in my main activity methods.
I tried to make a static class with a static member called "Server" equals to the server object, and I set it in another thread and then I tried to call it in the main thread (the main activity class) - but I had errors because of jumping from one thread to another..
To be more specified I want something like that:
public class MainActivity extends Activity {
private service.Client myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
..
... Some stuff that define myService (In a new thread ofcourse) ...
}
...
private void MyFunc1() {
myService.Method1();
}
private void MyFunc2() {
myService.Method2();
}
private void MyFunc3() {
myService.Method3();
}
}
I've got a library for talking to REST APIs. Feel free to slice, dice, and re-use: https://github.com/nedwidek/Android-Rest-API
The code is BSD or GPL.
Here's how I use what I have (I've trimmed MainActivity a bit, hopefully not too much):
package com.hatterassoftware.voterguide.api;
import java.util.HashMap;
public class GoogleCivicApi {
protected final String baseUrl = "https://www.googleapis.com/civicinfo/us_v1/";
protected String apiKey = "AIzaSyBZIP5uY_fMF35SVVrytpKgHtppBbj8J0I";
public static final String DATE_FORMAT = "yyyy-MM-dd";
protected static HashMap<String, String> headers;
static {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
}
public String createUrl(String uri, HashMap<String, String> params) {
String url = baseUrl + uri + "?key=" + apiKey;
if (params != null) {
for (String hashKey: params.keySet()) {
url += hashKey + "=" + params.get(hashKey) + "&";
}
url = url.substring(0, url.length());
}
return url;
}
}
package com.hatterassoftware.voterguide.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hatterassoftware.restapi.GetTask;
import com.hatterassoftware.restapi.HttpReturn;
import com.hatterassoftware.restapi.RestCallback;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.models.Election;
public class ElectionsQuery extends GoogleCivicApi implements RestCallback {
GetTask getTask;
ElectionCallback callback;
final String TAG = "ElectionQuery";
public ElectionsQuery(ElectionCallback callback) {
String url = this.createUrl("elections", null);
this.callback = callback;
Log.d(TAG, "Creating and executing task for: " + url);
getTask = new GetTask(url, this, null, null, null);
getTask.execute();
}
#Override
public void onPostSuccess() {
Log.d(TAG, "onPostSuccess entered");
}
#Override
public void onTaskComplete(HttpReturn httpReturn) {
Log.d(TAG, "onTaskComplete entered");
Log.d(TAG, "httpReturn.status = " + httpReturn.status);
if (httpReturn.content != null) Log.d(TAG, httpReturn.content);
if (httpReturn.restException != null) Log.d(TAG, "Exception in httpReturn", httpReturn.restException);
JsonParser parser = new JsonParser();
JsonElement electionArrayJson = ((JsonObject)parser.parse(httpReturn.content)).get("elections");
Log.d(TAG, electionArrayJson.toString());
Gson gson = new GsonBuilder().setDateFormat(GoogleCivicApi.DATE_FORMAT).create();
Election[] elections = gson.fromJson(electionArrayJson.toString(), Election[].class);
callback.retrievedElection(elections);
}
}
package com.hatterassoftware.voterguide;
import java.util.Calendar;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hatterassoftware.voterguide.api.ElectionsQuery;
import com.hatterassoftware.voterguide.api.VoterInfoQuery;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.callbacks.VoterInfoCallback;
import com.hatterassoftware.voterguide.api.models.Election;
import com.hatterassoftware.voterguide.api.models.VoterInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity implements ElectionCallback, VoterInfoCallback {
private ProgressBar mProgressBar;
public Button submit;
public Spinner state;
public Spinner election;
public EditText address;
public EditText city;
public EditText zip;
private int count=0;
private Object lock = new Object();
private static final String TAG = "MainActivity";
public static final String VOTER_INFO = "com.hatterassoftware.voterguide.VOTER_INFO";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.home_progressBar);
Resources res = getResources();
SharedPreferences mPrefs = getApplicationSharedPreferences();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
try {
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled(Context.LOCATION_SERVICE)) {
gpsButton.setClickable(false);
}
} catch(Exception e) {
Log.d(TAG, e.getMessage(), e);
gpsButton.setClickable(false);
gpsButton.setEnabled(false);
}
submit = (Button) findViewById(R.id.submit);
submit.setClickable(false);
submit.setEnabled(false);
state = (Spinner) findViewById(R.id.state);
election = (Spinner) findViewById(R.id.election);
address = (EditText) findViewById(R.id.streetAdress);
city = (EditText) findViewById(R.id.city);
zip = (EditText) findViewById(R.id.zip);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doSubmit();
}
});
gpsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLocate();
}
});
// Let's check for network connectivity before we get down to business.
if (Utils.isNetworkAvailable(this, true)) {
// Show the disclaimer on first run.
if(mPrefs.getBoolean("firstRun", true)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setCancelable(false);
alert.setTitle(res.getString(R.string.welcome));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView alertContents = (TextView) layout.findViewById(R.id.custom_dialog_text);
alertContents.setMovementMethod(LinkMovementMethod.getInstance());
alertContents.setText(Html.fromHtml(res.getString(R.string.welcome_dialog_text)));
alert.setView(alertContents);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences mPrefs = getApplicationSharedPreferences();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("firstRun", false);
editor.commit();
dialog.dismiss();
retrieveElections();
}
});
alert.show();
} else {
retrieveElections();
}
}
}
#Override
public void onResume() {
super.onResume();
// Let's check for network connectivity before we get down to business.
Utils.isNetworkAvailable(this, true);
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {
Toast.makeText(this, "GPS is not available", 2).show();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
gpsButton.setClickable(false);
}
}
public SharedPreferences getApplicationSharedPreferences() {
Context mContext = this.getApplicationContext();
return mContext.getSharedPreferences("com.hatterassoftware.voterguide", MODE_PRIVATE);
}
private void showSpinner() {
synchronized(lock) {
count++;
mProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideSpinner() {
synchronized(lock) {
count--;
if(count < 0) { // Somehow we're trying to hide it more times than we've shown it.
count=0;
}
if (count == 0) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
public void retrieveElections() {
Log.d(TAG, "Retrieving the elections");
showSpinner();
ElectionsQuery query = new ElectionsQuery(this);
}
#Override
public void retrievedElection(Election... elections) {
Log.d(TAG, "Retrieved the elections");
hideSpinner();
for (int i=0; i<elections.length; i++) {
Log.d(TAG, elections[i].toString());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, elections);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) this.findViewById(R.id.election);
spinner.setAdapter(arrayAdapter);
}
}
When press button first sound active. Then press that button again it will stop and second sound active My code is OK?
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt=(TextView)findViewById(R.id.txt);
bt1 = (Button)findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while(showRandom){
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp.setLooping(true);
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
mp2.setLooping(true);
mp2.start();
}catch(Exception ex){
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Add the line:
mp.setLooping(true);
Then set false when you want to stop it looping.
Your code has several errors. Typos, cases,
ex.: Medaiplayer should be MediaPlayer
This alone would be enough to cause the error. Also, declaring your variables outside the method is a good idea.