Hello, I have my new game which will be released at the end of february. But now, I have just the signed version installed on phone and the app is not published yet. And hen I try to submit my score to leaderboard, it simply won't and I don't know why. I am using the instance on GoogleApiClient because I need to unlock Achievements in several different Activities. So, here is my code:
Code:
public class GameOverActivity extends GoogleBaseGameActivity {
int coins2;
int score;
int coins;
String type;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_over_layout);
SharedPreferences shop = getSharedPreferences("Shop", Context.MODE_PRIVATE);
coins2 = shop.getInt("money", 0);
score = getIntent().getExtras().getInt("score");
coins = getIntent().getExtras().getInt("coins");
type = getIntent().getExtras().getString("GameType");
TextView money = (TextView) findViewById(R.id.coins);
money.setText("Coins:" + String.valueOf(coins2) + "+" + String.valueOf(coins));
SharedPreferences.Editor editor = shop.edit();
editor.putInt("money", coins + coins2);
editor.commit();
GoogleApiClient mGoogleApiClient = getApiClient();
mGoogleApiClient.connect();
TextView score1 = (TextView) findViewById(R.id.score);
score1.setText("Score:" + String.valueOf(score));
Button mainMenu = (Button) findViewById(R.id.MainMenu);
if (mGoogleApiClient.isConnected()) {
Games.Achievements.unlockImmediate(mGoogleApiClient, getString(R.string.achievement_newbie_player));
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_casual_player), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_addicted_player), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_mrms_addicted), 1);
Games.Achievements.incrementImmediate(mGoogleApiClient, getString(R.string.achievement_mrms_maniac), 1);
switch (type) {
case "normal":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_normal_mode),
score);
case "hard":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_hard_mode),
score);
case "reversed":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_reversed_mode),
score);
if(score==69){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_reversed_reversed));
}
case "revHard":
Games.Leaderboards.submitScore(getApiClient(),
getString(R.string.leaderboard_reversed_hard_mode),
score);
}
}
mainMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GameOverActivity.this, MainMenuActivity.class);
startActivity(intent);
}
});
Button replay = (Button) findViewById(R.id.replay);
replay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (type.equals("normal")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTap.class);
startActivity(intent);
} else if (type.equals("hard")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapHardMode.class);
startActivity(intent);
} else if (type.equals("reversed")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapReversedMode.class);
startActivity(intent);
} else if (type.equals("revHard")) {
Intent intent = new Intent(GameOverActivity.this, MonsterTapReversedHardMode.class);
startActivity(intent);
} else {
Intent intent = new Intent(GameOverActivity.this, MainMenuActivity.class);
startActivity(intent);
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK)
return false;
return false;
}
@Override
public void onSignInFailed() {
}
@Override
public void onSignInSucceeded() {
}
}
How to make it working ?
The problem is that I can open up the screen with the achievements/leaderboards but can't update them.
Related
Can someone tell me how can i use something like a timer to start a video recording interval process for a period of time (eg: 5mins) then restarts to record another set of 5min video until the user intervene to stop the process..
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingStatus;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
private static final String TAG = "Exception";
public boolean startRecording(){
try {
encodingStatus = Tab1Activity.encodingPref;
videoResolution = Tab1Activity.videoResPref;
fileFormat = Tab1Activity.fileFormatPref;
audioStatus = Tab2Activity.audioPref;
timeInterval = Tab2Activity.timeIntervalPref;
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(timeInterval);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(encodingStatus);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
separatedRes[0];
separatedRes[1];
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
}
someone please help...
Thread
you are writing a service, right? typically this service should also implement a thread. inside this thread you could implement your timer feature.
-didi
But the thing is i don't know how to even implement or even write the timer codes into my serviceRecording.java file... Can you help me on this?
i recently did this with a widget. i used an AlarmManager to set repeating alarms that would broadcast an intent that could be caught by a broadcastReciever and then do something... im at work now but when i get home i can try to give you some sample code.
you sure this needs to be a service? a service is something that is doing work but not at the forefront of the ui. its unseen. do you want your recording to be done in the background? i only ask because i did some research on services and found that they cannot be a BroadCastReciever and thus cannot use the AlarmManager that i said would work.
as far as a timer i have not looked into that particular class...
sorry i was no help. but if you decide to use the AlarmManager i could help
Someone recently recommended using these code to implement the sort of interval recording i wanted with this code below but i don't seems to know how to implement these codes into my current code could someone lend me a hand how how can can i implement the appropriate codes into my code to make my code work? Or is there simpler way to achieve "dynamic" (with Preferences) interval recording?
Code:
final ServiceRecording recording = ....
final AtomicBoolean started = new AtomicBoolean(false);
ScheduledExecutorService executor = Executors.newScheduledExecutor(1);
executor.scheduleAtFixedRate(new Runnable() { public void run() { //only stop if we have started if(started.get()) { recording.stop(); } else { started.set(true); } recording.start(); }}, 5, 5, TimeUnit.MINUTES);
My serviceRecording
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
{
startRecording();
//new Timer().scheduleAtFixedRate(task, after, interval);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingType;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
//timeInterval = Integer.parseInt(Tab2Activity.timeIntervalPref);
private static final String TAG = "Exception";
public boolean startRecording(){
try {
SharedPreferences prefs_tab1 = getSharedPreferences("tab1", Context.MODE_PRIVATE);
SharedPreferences prefs_tab2 = getSharedPreferences("tab2", Context.MODE_PRIVATE);
encodingType = Integer.parseInt(prefs_tab1.getString("EncodingPref", "1"));
//******************************************************************************
String stringRes = CameraTest.resParams;
String[] entriesValues = stringRes.split(",");
String rawResolution = entriesValues[0];
videoResolution = prefs_tab1.getString("ResolutionPref", rawResolution);
//******************************************************************************
fileFormat = prefs_tab1.getString("FileFormatPref", ".mp4");
//******************************************************************************
audioStatus = prefs_tab2.getBoolean("AudioPref", true); //false
//******************************************************************************
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
if(!audioStatus)
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
if(!audioStatus)
{
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
}
mediaRecorder.setVideoEncoder(encodingType);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
mediaRecorder.setVideoSize(Integer.parseInt(separatedRes[0]),Integer.parseInt(separatedRes[1]));
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
Any progress on this? I was thinking you coukd have a private inner class in your service class that handles the timing with an AlarmManager
Im on my phone right now but something along these lines...
Private Class MyTimer extends BroadcastReciever {
//Implement onRecieve
Public void onRecieve(Context c, Intent i) {
//if intent matches 5min alarm
//start recording
}
Then in your service you can make a recurring alarm using the AlarmManager class to signal your inner class to start or even stop the recording based on what intent you pass it
When i get home ill right a bit more code as an example
From something awesome
i wrote a bit of code. its incomplete. and you will have to maybe mess with making the AlarmServicer class either static, public, private or something to make it work. basicly your service creates a five minute alarm directed at the AlarmServicer that it catches in the onRecieve() method and then starts your recording again and then creates another alarm directed at itself. you can use some if/then logic to change wether or not the alarm will be created again based on if the user wants it to stop or not. and then to get it going again the service would invoke the setOneTimeAlarm method again.
Code:
public class ServiceRecording extends Service {
// NEW CONSTANT
public static final String FIVE_MIN_ALARM = "FIVE_MIN_ALARM";
public static final int FIVE_MINUTES = 300;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
//set the first alarm
AlarmServicer.setOneTimeAlarm(AlarmServicer.class, this, ServiceRecording.FIVE_MINUTES , ServiceRecording.FIVE_MIN_ALARM);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { }
public boolean startRecording() {}
public void stopRecording() {}
// NEW CODE
private static class AlarmServicer extends BroadcastReciever {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ServiceRecording.FIVE_MIN_ALARM)) {
ServiceRecording.startRecording();
//set another five min alarm
setOneTimeAlarm(AlarmServicer.class, this, ServiceRecording.FIVE_MINUTES, ServiceRecording.FIVE_MIN_ALARM;
}
}
private static void setOneTimeAlarm(java.lang.Class<?> cls, Context context, int seconds, String action) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (seconds * 1000), pendingIntent);
}
}
}
and i believe that you need to register the inner class as a broadcastreciever in the android manifest.
**
** this most likely wont work....
**
Not that anyone will actually reply but I'm about to go insane to be honest, ALL i want to do is play a video from a list view using media store and a custom video player (Not stock player!) but so far all my attempts have failed.
So i need some professional help!
My MediaStore code:
Code:
public class VideoManager {
public VideoManager() {
}
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getPlayList(Context c) {
/*use content provider to get beginning of database query that queries for all audio by display name, path
and mimtype which i dont use but got it incase you want to scan for mp3 files only you can compare with RFC mimetype for mp3's
*/
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA}, null, null,
"UPPER(" + MediaStore.Video.Media.TITLE + ") ASC");
String videoTitle = "";
String videoPath = "";
/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {
videoTitle = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
videoPath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
HashMap<String, String> video = new HashMap<String, String>();
video.put("videoTitle", videoTitle);
video.put("videoPath", videoPath);
videoList.add(video);
} while (mCursor.moveToNext());
}
mCursor.close(); //cursor has been consumed so close it
return videoList;
}
public ArrayList<HashMap<String, String>> getPlayList() {
// TODO Auto-generated method stub
return null;
}
}
The list code along with an OnItemClick method and Intent:
Code:
public class VideoActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
ListView videolist;
Cursor mCursor;
int videoTitle;
int count;
int videoPath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos);
ArrayList<HashMap<String, String>> videoListData = new ArrayList<HashMap<String, String>>();
VideoManager plm = new VideoManager();
// get all songs from sdcard
this.videoList = plm.getPlayList(this);
// looping through playlist
for (int i = 0; i < videoList.size(); i++) {
// creating new HashMap
HashMap<String, String> video = videoList.get(i);
// adding HashList to ArrayList
videoListData.add(video);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, videoListData,
R.layout.video_item, new String[] { "videoTitle" }, new int[] {
R.id.videoTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int videoIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
VideoPlayerActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("videoPath", videoIndex);
startActivity(in);
// Closing PlayListView
finish();
}
});
}
}
And lastly, the players code:
Code:
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private VideoManager videoManager;
private int currentvideoIndex = 0;
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList(this);
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 0){
currentvideoIndex = data.getExtras().getInt("videoPath");
// play selected song
playVideo(currentvideoIndex);
}
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
return false;
}
@Override
public void toggleFullScreen() {
}
}
Right now PLEASE HELP ME!! :crying:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
EmptinessFiller said:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
Click to expand...
Click to collapse
Hi, thanks for the reply but unfortunately it didn't work.
I assume the code i entered is correct..
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
playVideo(getIntent().getExtras().getInt("videoPath"));
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList();
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am currently working on an App Switcher with the ability to also add custom apps in the app switcher. So, I already got the recent apps loader built. This is the code for this part of the app:
Code:
public class Corners_RecentApps extends Activity {
private ArrayList<PanelItemDetail> rowItems = null;
private ListView listView;
private ArrayList<String> packageName = null;
private ArrayList<String> className = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
if(rightpanel){
overridePendingTransition(R.anim.left_slide_in_fast, 0);
setContentView(R.layout.right_side_panel);
}
else
{
overridePendingTransition(R.anim.right_slide_in_fast, 0);
setContentView(R.layout.activity_left_side_panel);
}
ImageView imgbtn = (ImageView) findViewById(R.id.transparentbackground);
ImageView panelbg = (ImageView) findViewById(R.id.panelbackground);
listView = (ListView)findViewById(R.id.panelcontents);
packageName = new ArrayList<String>();
className = new ArrayList<String>();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = am.getRecentTasks(30, 0);
rowItems = new ArrayList<PanelItemDetail>();
PackageManager pacMgr = getPackageManager();
for (ActivityManager.RecentTaskInfo recentTask : tasks) {
try {
rowItems.add(new PanelItemDetail(pacMgr.getApplicationIcon(recentTask.origActivity.getPackageName())));
packageName.add(recentTask.origActivity.getPackageName());
className.add(recentTask.origActivity.getClassName());
Log.d("#@#", "getPackageName = " + recentTask.origActivity.getPackageName());
Log.d("#@#", "getClassName = " + recentTask.origActivity.getClassName());
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String itembg = myPreference.getString("itembg_list", "");
if(itembg.equals("defaults"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_default, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("dark"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_dark, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("light"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_light, rowItems);
listView.setAdapter(adapter);
}
else
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_none, rowItems);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
try{
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
Intent taskintent = getPackageManager().getLaunchIntentForPackage(packageName.get(postion).toString());
startActivity(taskintent);
if(rightpanel){
overridePendingTransition(R.anim.right_slide_in, R.anim.zoom_out);
}
else
{
overridePendingTransition(R.anim.left_slide_in, R.anim.zoom_out);
}
finish();
}
catch (NullPointerException fail) {
Toast.makeText(getApplicationContext(), "!", Toast.LENGTH_SHORT).show();
}
}
});
SharedPreferences panelbgpref = PreferenceManager.getDefaultSharedPreferences(this);
String panelbgset = panelbgpref.getString("panelbg_list", "");
if(panelbgset.equals("light"))
{
panelbg.setImageResource(R.drawable.panelbg_light);
}
else
{
panelbg.setImageResource(R.drawable.panelbg);
}
imgbtn.setOnClickListener(new View.OnClickListener(){
[user=439709]@override[/user]
public void onClick(View v) {
if(v.getId() ==R.id.transparentbackground){
moveTaskToBack(true);
finish();
}
}
});
}
Now I want to let the users define in the app settings up to 3 own apps that should be shown on every moment.
How should I do that?
Thank you
Hi,
I want to get body of SMS when I click on one. I have tried an approach simmilar to contact picker. Here is my code :
public class Decrypt extends Fragment {
Button loadButton;
EditText smsDisplay;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.decrypt, null);
// Button loadButton=(Button)v.findViewById(R.id.)
loadButton=(Button)v.findViewById(R.id.buttonLoad);
smsDisplay=(EditText)v.findViewById(R.id.editTextLoad);
loadButton.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
//sendIntent.setType(Sm)
//sendIntent.putExtra("sms_body","");
startActivityForResult(sendIntent,2);
}
});
return v;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
// if (resultCode == Activity.RESULT_OK) {
Uri ur = data.getData();
Cursor c = getActivity().getContentResolver().query(ur, null, null, null, null);
if (c.moveToFirst()) {
String s = c.getString(c.getColumnIndex("body"));
System.out.println(s);
Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
smsDisplay.setText(s);
}
}catch(Exception e){
e.printStackTrace();
}
// }
}
}
It opens a Inbox like when I open original sms app in anroid, but when I click on one message it doesnt copy body of that sms in my edittext. Please couul you look at my code and find mistake?
Thanks a lot for your time
I used the BluetoothLeGatt example code to write an app that automatically connects to a bonded BLE peripheral upon launching the app. Now i am trying to display the data from one of the peripheral's characteristic in a textView. The BluetoothLeGatt example code only demonstrates this using ExpandableListView.OnChildClickListener, my app should require no user input and simply get he data from the characteristic. This is what i have so far:
Code:
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
mConnectionState.setTextColor(Color.parseColor("#FF17AA00"));
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
*edit*
UUID chara = UUID.fromString("c97433f0-be8f-4dc8-b6f0-5343e6100eb4");
List<BluetoothGattService> servs = mBluetoothLeService.getSupportedGattServices();
for (int i = 0; servs.size() > i; i++) {
List<BluetoothGattCharacteristic> charac = servs.get(i).getCharacteristics();
for (int j = 0; charac.size() > i; i++) {
BluetoothGattCharacteristic ch = charac.get(i);
if (ch.getUuid() == chara) {
mBluetoothLeService.readCharacteristic(ch);
mBluetoothLeService.setCharacteristicNotification(ch, true);
}
}
}
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_control);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
I've successfully connected to an already bonded device, but now im trying to get the data from a characteristic using its uuid and display it in a textView. The BluetoothLeGatt example shows how a characteristic is selected by a user using an expandable list view onclick listener displaying the supported characteristics. I want to bypass all that and just get the data from the characteristic with the known uuid.
-EDIT-
figured it out