Server connection:
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
Log.i("Test",binder.getService().toString());
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
Where I get an error:
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
Log.d("Item clicked","Song picked"+Integer.parseInt(view.getTag().toString()));
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
MusicService.java
package com.musicplayer;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.IBinder;
import java.util.ArrayList;
import android.content.ContentUris;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.PowerManager;
import android.util.Log;
import java.util.Random;
import android.app.Notification;
import android.app.PendingIntent;
import com.lyricscloud.R;
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
private String songTitle="";
private static final int NOTIFY_ID=1;
private final IBinder musicBind = new MusicBinder();
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
public void initMusicPlayer(){
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void onCreate(){
super.onCreate();
//initialize position
songPosn=0;
//create Player
player = new MediaPlayer();
initMusicPlayer();
}
#Override
public void onDestroy() {
stopForeground(true);
}
public void playSong(){
player.reset();
Song playSong = songs.get(songPosn);
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
public void onCompletion(MediaPlayer mp) {
if(player.getCurrentPosition() <= 0){
mp.reset();
playNext();
}
}
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return player.getDuration();
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
public void playPrev(){
songPosn--;
if(songPosn <= 0) songPosn=songs.size()-1;
playSong();
}
public void playNext(){
songPosn++;
if(songPosn >= songs.size()) songPosn=0;
playSong();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
public void setSong(int songIndex){
songPosn=songIndex;
Log.d("Service", ""+songIndex);
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
Intent notIntent = new Intent(this, MusicPlayer_Songs.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing");
builder.setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
}
The error
08-04 22:50:31.796 23825-23825/com.lyricscloud.dev E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lyricscloud.dev, PID: 23825
java.lang.NullPointerException
at com.musicplayer.MusicPlayer_Songs.songPicked(MusicPlayer_Songs.java:47)
at com.musicplayer.MusicPlayer_Songs$3.onItemClick(MusicPlayer_Songs.java:117)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1478)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3480)
at android.widget.AbsListView$3.run(AbsListView.java:4823)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
I'm not sure whats causing it, I need help please, the app is a musicplayer and whenever I click a list item it gives me that error
onStart() callback:
public void onStart() {
super.onStart();
if(playIntent==null){
Log.i("Play Intent","Is null");
playIntent = new Intent(c, MusicService.class);
//c is rootView.getContext() from onCreateView()
c.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
c.startService(playIntent);
}
}
Related
I am trying to run a service that once started records audio for 5 seconds using Speech Recognizer. However, whenever I start the service it calls the onError method in the speech recognizer class, and once I stop the service it gives me the error :
Service has leaked ServiceConnection
android.speech.SpeechRecognizer$Connection#2e1ecaf that was originally
bound here
I have tried everything and looked everywhere but cannot seem to find a solution. Please help.
Here's my service code, it is started and stopped using buttons in the mainActivity.
MicrophoneService.java
package com.example.daisymicrophone;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import static com.example.daisymicrophone.App.CHANNEL_ID;
public class MicrophoneService extends Service {
protected static SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
Context c;
public static final String TAG = "MicrophoneService";
#Override
public void onCreate() {
super.onCreate();
c = getApplicationContext();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Daisy App")
.setContentText("Daisy is listening to you")
.setSmallIcon(R.drawable.ic_mic)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
Toast.makeText(this,"start Service.", Toast.LENGTH_SHORT).show();
//if condition is met then do this
SpeechRecognitionListener h = new SpeechRecognitionListener();
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(h);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
Log.d("avail", " " + mSpeechRecognizer.isRecognitionAvailable(this));
if (mSpeechRecognizer.isRecognitionAvailable(this))
Log.d("created", "onBeginingOfSpeech");
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mSpeechRecognizer.stopListening();
}
}, 5 * 1000);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
class SpeechRecognitionListener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.d("onReady", "service");
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
Log.d("ERROR","ERROR");
}
#Override
public void onResults(Bundle resultsBundle) {
Log.d("Results", "onResults: " + resultsBundle.toString());
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
}
}
Error log
2020-05-09 00:13:00.199 19488-19488/com.example.daisymicrophone D/MicrophoneService: startMicService:
2020-05-09 00:13:00.202 19488-19488/com.example.daisymicrophone V/ActivityThread: SVC-Creating service CreateServiceData{token=android.os.BinderProxy#331f924 className=com.example.daisymicrophone.MicrophoneService packageName=com.example.daisymicrophone intent=null}
2020-05-09 00:13:00.211 19488-19488/com.example.daisymicrophone D/ActivityThread: SVC-Calling onStartCommand: com.example.daisymicrophone.MicrophoneService#c083c8d, flags=0, startId=1
2020-05-09 00:13:00.238 19488-19488/com.example.daisymicrophone D/avail: true
2020-05-09 00:13:00.243 19488-19488/com.example.daisymicrophone D/created: onBeginingOfSpeech
2020-05-09 00:13:00.402 19488-19488/com.example.daisymicrophone D/onReady: service
2020-05-09 00:13:00.547 19488-19488/com.example.daisymicrophone D/ERROR: ERROR
2020-05-09 00:13:02.982 19488-19488/com.example.daisymicrophone D/MicrophoneService: stopMicService:
2020-05-09 00:13:02.984 19488-19488/com.example.daisymicrophone V/ActivityThread: SVC-Destroying service com.example.daisymicrophone.MicrophoneService#c083c8d
2020-05-09 00:13:02.993 19488-19488/com.example.daisymicrophone E/ActivityThread: Service com.example.daisymicrophone.MicrophoneService has leaked ServiceConnection android.speech.SpeechRecognizer$Connection#2e1ecaf that was originally bound here
android.app.ServiceConnectionLeaked: Service com.example.daisymicrophone.MicrophoneService has leaked ServiceConnection android.speech.SpeechRecognizer$Connection#2e1ecaf that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1376)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1271)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1465)
at android.app.ContextImpl.bindService(ContextImpl.java:1437)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.speech.SpeechRecognizer.startListening(SpeechRecognizer.java:287)
at com.example.daisymicrophone.MicrophoneService.onStartCommand(MicrophoneService.java:66)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3394)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1632)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6259)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
You should destroy the speech recognizer when stopping the service.
#Override
public void onDestroy() {
mSpeechRecognizer.destroy();
super.onDestroy();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an Android app. This app has 12 activities, the first activity is the Splash Screen and sec activity is the intropage and 3rd activity is main and etc When I run the app, it doesn't enter the main activity and the app closes. The error is as follows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at com.github.hujiaweibujidao.wava.BaseViewAnimator.reset(BaseViewAnimator.java:78)
at com.github.hujiaweibujidao.wava.BaseViewAnimator.start(BaseViewAnimator.java:55)
at com.github.hujiaweibujidao.wava.YoYo$Builder.start(YoYo.java:128)
at com.github.hujiaweibujidao.wava.YoYo$Builder.playOn(YoYo.java:115)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:108)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Thank you for your answers, but the solutions you gave me did not help. I checked, but it still gave me the same error. I put three-activated codes for you. Can you help me, please?
this my main activity java code:
package com.example.myapplication;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.akshay.library.CurveBottomBar;
import com.github.hujiaweibujidao.wava.Techniques;
import com.github.hujiaweibujidao.wava.YoYo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.mxn.soul.flowingdrawer_core.ElasticDrawer;
import com.mxn.soul.flowingdrawer_core.FlowingDrawer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;
public class MainActivity extends AppCompatActivity {
CurveBottomBar cbb;
FlowingDrawer mDrawer;
ImageView img_icon,imgtest,img_music,img_night,img_main,img_setting;
TextView txt;
String patch;
boolean read=false,music=true,night_mode;
Button btn_fehrest,btn_last_story,btn_fav;
SharedPreferences sharedP;
LinearLayout lin_main;
Toast exit;
boolean show_intropage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbb = findViewById(R.id.cbb);
mDrawer = findViewById(R.id.drawerlayout);
img_icon = findViewById(R.id.img_icon);
imgtest = findViewById(R.id.imgtest);
txt = findViewById(R.id.txt);
btn_fehrest = findViewById(R.id.btn_fehrest);
img_music = findViewById(R.id.img_music);
lin_main = findViewById(R.id.lin_main);
img_night = findViewById(R.id.img_night);
img_main = findViewById(R.id.img_main);
btn_last_story = findViewById(R.id.btn_last_story);
btn_fav = findViewById(R.id.btn_fav);
img_setting = findViewById(R.id.img_setting);
cbb.inflateMenu(R.menu.menu_scrolling);
sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
show_intropage = sharedP.getBoolean(Items.INTROPAGE,true);
cbb.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.img_setting:
// kary ke mikhaym anjam bedim
break;
case R.id.img_music:
//
break;
}
return false;
}
});
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fehrest);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_last_story);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fav);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_music);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_setting);
get_night();
permission();
//createFile();
if (show_intropage){
taptarget();
}
img_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawer.openMenu(true);
}
});
mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
mDrawer.setBackgroundColor(Color.WHITE);
mDrawer.setOnDrawerStateChangeListener(new ElasticDrawer.OnDrawerStateChangeListener() {
#Override
public void onDrawerStateChange(int oldState, int newState) {
if (newState == ElasticDrawer.STATE_CLOSED) {
Log.i("MainActivity", "Drawer STATE_CLOSED");
}
}
#Override
public void onDrawerSlide(float openRatio, int offsetPixels) {
Log.i("MainActivity", "openRatio=" + openRatio + " ,offsetPixels=" + offsetPixels);
}
});
}
public void createFile(){
try {
patch = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mbook/";
File mfile = new File(patch);
if (!mfile.exists()) {
mfile.mkdir();
mfile.createNewFile();
CopyDB(getBaseContext().getAssets().open("Mbook.db"), new FileOutputStream(patch+"/Mbook.db"));
//Toast.makeText(this, patch+"", Toast.LENGTH_LONG).show();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void CopyDB (InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int file_length;
while ((file_length = inputStream.read(buffer))>0){
outputStream.write(buffer,0,file_length);
}
inputStream.close();
outputStream.close();
}
public void fehrest_intent(View view) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(800).playOn(btn_fehrest);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fehrest");
startActivity(intent);
}
},1500);
}
private void permission(){
Dexter.withContext(MainActivity.this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
createFile();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response !=null && response.isPermanentlyDenied()){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
}
Toast.makeText(MainActivity.this, "جهت استفاده از برنامه دادن اجازه دسترسی ضروریست", Toast.LENGTH_SHORT).show();
alert();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, final PermissionToken token) {
alert();
}
}).check();
}
public void alert(){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setTitle("توجه");
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست لطفا درقسمت تنظیمات اجازه دسترسی را فعال کنید");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
Hoshdar.create().show();
}
public void fav_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_fav);
mDrawer.closeMenu(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fav");
intent.putExtra("activity","main");
startActivity(intent);
}
},1500);
}
public void text_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_last_story);
if (read){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent_movies = new Intent(getBaseContext(), Text_activity.class);
intent_movies.putExtra("activity","main");
startActivity(intent_movies);
}
},1500);
}else {
Toast.makeText(this, "هنوز هیچ داستانی مطالعه نکردید!", Toast.LENGTH_SHORT).show();
}
}
public void setting_intent(MenuItem item) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(600).playOn(img_setting);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,Setting.class));
}
},1500);
}
public void set_music(MenuItem item) {
YoYo.with(Techniques.Pulse).duration(600).playOn(img_music);
if (music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
music=false;
sharedP.edit().putBoolean(Items.MUSIC, false).apply();
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
music=true;
sharedP.edit().putBoolean(Items.MUSIC, true).apply();
}
}
public void get_night(){
music = sharedP.getBoolean(Items.MUSIC,true);
night_mode = sharedP.getBoolean(Items.NIGHT_MODE,false);
read = sharedP.getBoolean(Items.READ,false);
if (night_mode){
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
}else {
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
}
if (!music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
}
}
public void set_night(View view){
YoYo.with(Techniques.RotateIn).duration(800).playOn(img_night);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (night_mode){
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
sharedP.edit().putBoolean(Items.NIGHT_MODE, false).apply();
night_mode=false;
}else {
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
sharedP.edit().putBoolean(Items.NIGHT_MODE, true).apply();
night_mode=true;
}
}
},800);
}
#Override
protected void onResume() {
super.onResume();
get_night();
}
#Override
protected void onDestroy() {
stopService(new Intent(MainActivity.this,PlayMusic.class));
super.onDestroy();
}
public void finish(View view) {
mDrawer.closeMenu(true);
finish();
}
#SuppressLint("ResourceAsColor")
private void taptarget(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_night)
.setPrimaryText("فعال کردن حالت شب")
.setSecondaryText("با زدن این دکمه میتوانید حالت مطالعه در شب را فعال یا غیر فعال کنید")
//.setPrimaryTextColour(Color.parseColor("#13dc74"))
// .setSecondaryTextColour(Color.parseColor("#13dc74"))
.setFocalColour(R.color.mycolorGray)
.setBackButtonDismissEnabled(false)
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED|| state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "اولی", Toast.LENGTH_SHORT).show();
txt_target();
}
}
})
.show();
}
private void txt_target(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_icon)
.setFocalColour(R.color.mycolorGray)
.setPrimaryText("منوی کشویی")
.setSecondaryText("با زدن این دکمه منوی کشویی برنامه باز خواهد شد که شامل آیتم های مختلفی می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target3();
}
}
})
.show();
}
private void target3(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_music)
.setPrimaryText("فعال/غیرفعال موزیک")
.setSecondaryText("با زدن این دکمه میتوانید موزیک پس زمینه حین مطالعه را پخش یا قطع کنید")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target4();
}
}
})
.show();
}
private void target4(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_setting)
.setPrimaryText("تنظیمات")
.setSecondaryText("با زدن این دکمه بخش تنظیمات باز خواهد شد که شامل تغییر فونت متن ، سایز متن و ... می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
sharedP.edit().putBoolean(Items.INTROPAGE, false).apply();
}
}
})
.show();
}
#Override
public void onBackPressed() {
if (!(exit ==null)){
super.onBackPressed();
//MainActivity.this.finish();
}else {
exit = Toast.makeText(this,"برای خروج دوباره بزنید",Toast.LENGTH_LONG);
exit.show();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit= null;
}
},3000);
}
}
this my main activity xml code:
Splash Screen Activity Run enters Intro Page. After clicking the reject or complete button, the program will not enter the activity menu and the program will close.
Please follow the below options. Hope your problem will be solved.
1) Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"
<activity
android:name=".MainActivity" >
</activity>
2) Clean and rebuilt the project and Hope it will work.
You forgot find view btn_last_story add it to onCreate
btn_last_story = findViewById(R.id.btn_last_story);
This is such a basic issue that I am not sure what I could possibly be doing wrong. Sinch is not starting for me and I don't know why. I don't have enough experience with Sinch to diagnose why a basic command is not doing what it is supposed to do. Here's what I have:
I am trying to start and making the call from the Calling.java class. The code is as follows:
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.sinch.android.rtc.calling.Call;
import com.squareup.picasso.Picasso;
import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
public class Calling extends CallActivity {
private String calleeID;
private TextView serviceName;
Bundle callDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
callDetails = getIntent().getBundleExtra("callDetails");
//Setup end button
Button endCallButton = findViewById(R.id.endcall);
endCallButton.setOnClickListener(v -> endCall());
}
private void endCall() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finishActivity(FLAG_ACTIVITY_PREVIOUS_IS_TOP);
finish();
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
//Setup Calling Screen
ImageView avatar = findViewById(R.id.dialingAvatar);
Picasso.get().load(callDetails.getString("Logo")).into(avatar);
TextView midScreenName = findViewById(R.id.memberName);
midScreenName.setText(callDetails.getString("Name"));
serviceName = findViewById(R.id.serviceName);
serviceName.setText(callDetails.getString("Service"));
TextView ratings = findViewById(R.id.rating);
ratings.setText(callDetails.getString("Rating") + " ★");
//Get CallerID and CalleeID
calleeID = callDetails.getString("CalleeID");
//Start sinch Service
if(!getSinchServiceInterface().isStarted()){
getSinchServiceInterface().startClient(callDetails.getString("CallerID"));
Call call = getSinchServiceInterface().callUserVideo(calleeID);
Intent callServiceScreen = new Intent(this, ServiceCallActivity.class);
callDetails.putString(SinchService.CALL_ID, call.getCallId());
callServiceScreen.putExtra("Call Details", callDetails);
startActivity(callServiceScreen);
}
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
}
I am coming to Calling.java from Precall.java the code for that is:
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.sinch.android.rtc.SinchError;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class precall extends CallActivity implements SinchService.StartFailedListener {
private Bundle memberDetails;
private String url;
private Button cancel;
private Button call;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_precall);
//url
url = apiCallPoints.userInfo;
//Set Member Text
memberDetails = getIntent().getBundleExtra("Member");
//Populate screen
ImageView avatar = findViewById(R.id.avatar);
Picasso.get().load(memberDetails.getString("Logo")).into(avatar);
TextView memberName = findViewById(R.id.membername);
memberName.setText(memberDetails.getString("Name"));
TextView rating = findViewById(R.id.rating);
rating.setText(memberDetails.getString("Rating") + " ★");
TextView serviceName = findViewById(R.id.servicename);
serviceName.setText(memberDetails.getString("Service"));
TextView overview = findViewById(R.id.overview);
overview.setText(memberDetails.getString("Overview"));
//Add button clicks
cancel = findViewById(R.id.cancel_button);
cancel.setOnClickListener(view -> finish());
cancel.setEnabled(false);
call = findViewById(R.id.yes_button);
call.setOnClickListener(view -> {
goToCalling();
});
call.setEnabled(false);
setHomeBar();
}
//this method is invoked when the connection is established with the SinchService
#Override
protected void onServiceConnected() {
call.setEnabled(true);
cancel.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
}
//Invoked when just after the service is connected with Sinch
#Override
public void onStarted() {
}
private void goToCalling() {
//Async search
CallBackendSync callBackendSync = new CallBackendSync();
Object [] params = {url, memberDetails};
callBackendSync.execute(params);
}
private void setHomeBar() {
final Button home = findViewById(R.id.home_button);
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, SecondActivity.class));
}
});
final Button favourites = findViewById(R.id.star_button);
favourites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, Favourite_Page.class));
}
});
final Button profile_page = findViewById(R.id.person_button);
profile_page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(getApplicationContext(), Profile.class));
}
});
final Button notifications = findViewById(R.id.notification_button);
notifications.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, Notification_Page.class));
}
});
final Button service = findViewById(R.id.service_button);
service.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, services.class));
}
});
}
class CallBackendSync extends AsyncTask {
OkHttpClient client = new OkHttpClient();
#Override
protected Object doInBackground(Object [] objects) {
String url = (String) objects[0];
Bundle memberDetails = (Bundle) objects[1];
//Get access token from shared preference
isLoggedIn loggedIn = new isLoggedIn(getApplicationContext());
String token = loggedIn.getToken();
if(token != null){
//Create request
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + token)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
JSONObject results = new JSONObject(response.body().string());
String UserID = results.getString("UserId");
memberDetails.putString("CallerID", UserID);
Intent callIntent = new Intent(precall.this, Calling.class);
callIntent.putExtra("callDetails", memberDetails);
startActivity(callIntent);
return results;
}catch (Exception e){
e.printStackTrace();
}
} else {
startActivity(new Intent(precall.this, Login_page.class));
}
return null;
}
protected void onPostExecute(String s){
super.onPostExecute(s);
}
}
}
The failure is happening in SinchService.java
import com.sinch.android.rtc.AudioController;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.video.VideoController;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class SinchService extends Service {
private static final String APP_KEY = "is correct";
private static final String APP_SECRET = "is correct";
//private static final String ENVIRONMENT = "clientapi.sinch.com";
private static final String ENVIRONMENT = "sandbox.sinch.com";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient = null;
private String mUserId = "";
private StartFailedListener mListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
if(mSinchClient != null){
mSinchClient.terminate();
}
super.onDestroy();
}
private void start(String userName) {
mUserId = userName;
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext())
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.userId(userName)
.enableVideoCalls(true)
.build();
mSinchClient.setSupportCalling(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.checkManifest();
mSinchClient.start();
System.out.println("Is started: " + mSinchClient.isStarted());
}
private void stop() {
if(mSinchClient != null){
mSinchClient.terminate();
}
}
private boolean isStarted() {
if(mSinchClient != null){
return mSinchClient.isStarted();
} else {
return false;
}
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public Call callUserVideo(String userId) {
return mSinchClient.getCallClient().callUserVideo(userId);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
public VideoController getVideoController() {
return mSinchClient.getVideoController();
}
public AudioController getAudioController() {
return mSinchClient.getAudioController();
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
Intent intent = new Intent(SinchService.this, Calling.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SinchService.this.startActivity(intent);
}
}
}
And the base activity is CallActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.sinch.android.rtc.calling.Call;
import com.squareup.picasso.Picasso;
import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
public class Calling extends CallActivity {
private String calleeID;
private TextView serviceName;
Bundle callDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
callDetails = getIntent().getBundleExtra("callDetails");
//Setup end button
Button endCallButton = findViewById(R.id.endcall);
endCallButton.setOnClickListener(v -> endCall());
}
private void endCall() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finishActivity(FLAG_ACTIVITY_PREVIOUS_IS_TOP);
finish();
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
//Setup Calling Screen
ImageView avatar = findViewById(R.id.dialingAvatar);
Picasso.get().load(callDetails.getString("Logo")).into(avatar);
TextView midScreenName = findViewById(R.id.memberName);
midScreenName.setText(callDetails.getString("Name"));
serviceName = findViewById(R.id.serviceName);
serviceName.setText(callDetails.getString("Service"));
TextView ratings = findViewById(R.id.rating);
ratings.setText(callDetails.getString("Rating") + " ★");
//Get CallerID and CalleeID
calleeID = callDetails.getString("CalleeID");
//Start sinch Service
if(!getSinchServiceInterface().isStarted()){
getSinchServiceInterface().startClient(callDetails.getString("CallerID"));
Call call = getSinchServiceInterface().callUserVideo(calleeID);
Intent callServiceScreen = new Intent(this, ServiceCallActivity.class);
callDetails.putString(SinchService.CALL_ID, call.getCallId());
callServiceScreen.putExtra("Call Details", callDetails);
startActivity(callServiceScreen);
}
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
}
I have been banging my head against this but I cannot figure out what's wrong. I sure it's something stupid and obvious that I can't see because I am too close to the code. But any ideas you guys have would be very helpful!
It looks like you are not waiting for it to start before you try to make a call. We recommend to start the service when the app starts. If you dont do that you need to wait or the onStarted event in the service for fire
Please help!!!
I am creating a screen capture application and the problem is that after clicking the PRO button and after the purchase, the ads and the button do not hide.
I am trying to remove a button and ads using layout changes:
setContentView (R.layout.main_pro)
the code:
IabHelper.OnIabPurchaseFinishedListener () {
#Override
public void onIabPurchaseFinished (IabResult result, purchase purchase) {
if (result.isFailure ()) {
Log.d (TAG, "Purchase Error:" result);
return;
}
even if (purchase.getSku (). equals (SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView (R.layout.main_pro);
remove ads ();
Toast.makeText (MainActivity.this, “The purchase was successful,” Toast.LENGTH_LONG) .show ();
}
}
};
}
Full code:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.icu.text.SimpleDateFormat;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ViewFlipper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.davidgrigoryan.screenrecorder.util.Constants;
import com.davidgrigoryan.screenrecorder.util.IabHelper;
import com.davidgrigoryan.screenrecorder.util.IabResult;
import com.davidgrigoryan.screenrecorder.util.Inventory;
import com.davidgrigoryan.screenrecorder.util.Purchase;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 1000;
private int mScreenDensity;
File file;
private Context context;
private ShareActionProvider mShareActionProvider;
private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
static final String SKU_REMOVE_ADS = "android.test.purchased";
static final int RC_REQUEST = 10111;
private MediaProjectionCallback mMediaProjectionCallback;
private MediaRecorder mMediaRecorder;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int REQUEST_PERMISSION_KEY = 1;
boolean isRecording = false;
private FloatingActionButton rec;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Intent intent;
private Activity activity;
private boolean URL_TO_SHARE;
private ImageView wm;
private NotificationManagerCompat notificationManager;
private String title;
private String message;
private InterstitialAd mInterstitialAd;
private String testDeviceId;
AdRequest adRequest;
private AdView adView;
IabHelper mHelper;
String base64EncodedPublicKey = "PublicKey";
Boolean isAdsDisabled = false;
String payload = "Upgrade PRO";
private Inventory i;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
private static boolean isWidget = false;
private static Context appContext;
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView pro = (ImageView) findViewById(R.id.buy);
final SharedPreferences prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
pro.setVisibility(prefs.getBoolean("isPurchase", true) ? View.VISIBLE : View.INVISIBLE);
pro.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
purchaseRemoveAds();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Handler handler = new Handler();
final Timer timer = new Timer();
final TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 120000);
adView = (AdView) findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-9842509861911521/3646081879");
AdRequest adRequestInterstitial = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = new AdSize(320, 50);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-9842509861911521/3646081879");
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-9842509861911521/1961271598");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
if (!Service.hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
}
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mMediaRecorder = new MediaRecorder();
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
rec = (FloatingActionButton) findViewById(R.id.rec);
rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onToggleScreenShare();
}
});
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(false);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#Override
public void onIabSetupFinished(IabResult result, IabHelper.QueryInventoryFinishedListener mGotInventoryListener) throws IabHelper.IabAsyncInProgressException {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
return;
}
if (mHelper == null)
return;
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
queryPurchased();
IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView(R.layout.main_pro);
removeAds();
Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
}
}
};
}
private void queryPurchased() {
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else{
// does the user have the premium upgrade?
isAdsDisabled = inventory.hasPurchase(SKU_REMOVE_ADS);
// update UI accordingly
}
}
};
}
public void purchaseRemoveAds() {
try {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, 9, mPurchaseFinishedListener, "SECURITYSTRING");
} catch (Exception e) {
e.printStackTrace();
mHelper.flagEndAsync();
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.error)
.setMessage(R.string.error_play_store)
.setPositiveButton("OK", null)
.show();
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase finished: " + result + ", purchase: "
+ purchase);
if (mHelper == null)
return;
if (result.isFailure()) {
return;
}
if (!verifyDeveloperPayload(purchase)) {
return;
}
if (isAdsDisabled == true){
setContentView(R.layout.main_pro);
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
removeAds();
}
}
};
}
private void removeAds() {
adView.setEnabled(false);
adView.setVisibility(View.INVISIBLE);
}
public void onToggleScreenShare() {
if (!isRecording) {
Toast.makeText(getApplicationContext(), R.string.start_rec, Toast.LENGTH_LONG).show();
startService();
initRecorder();
shareScreen();
} else {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ads not loaded!");
}
Toast.makeText(getApplicationContext(), R.string.stop_rec, Toast.LENGTH_LONG).show();
stopService();
mMediaRecorder.stop();
mMediaRecorder.reset();
stopScreenSharing();
}
}
private void shareScreen() {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
private VirtualDisplay createVirtualDisplay() {
return mMediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
}
private void initRecorder() {
try {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //THREE_GPP
mMediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(16); // 30
mMediaRecorder.setVideoEncodingBitRate(3000000);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
private File initFile() {
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator + "ScreenRecorder");
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG,
R.string.error_folder
+ dir.getAbsolutePath());
file = null;
} else {
file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"'VIDEO-'yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return file;
}
private void stopScreenSharing() {
if (mVirtualDisplay == null) {
return;
}
mVirtualDisplay.release();
destroyMediaProjection();
isRecording = false;
}
private void destroyMediaProjection() {
if (mMediaProjection != null) {
mMediaProjection.unregisterCallback(mMediaProjectionCallback);
mMediaProjection.stop();
mMediaProjection = null;
}
Log.i(TAG, "MediaProjection Stopped");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_CODE) {
Log.e(TAG, "Unknown request code: " + requestCode);
return;
}
if (resultCode != RESULT_OK) {
Toast.makeText(this, R.string.denied, Toast.LENGTH_SHORT).show();
isRecording = false;
return;
}
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
} else
Log.d(TAG, "onActivityResult handled by IABUtil.");
mMediaProjectionCallback = new MediaProjectionCallback();
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
mMediaProjection.registerCallback(mMediaProjectionCallback, null);
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_KEY: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
onToggleScreenShare();
} else {
isRecording = false;
Snackbar.make(findViewById(android.R.id.content), R.string.message,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.enable,
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
private class MediaProjectionCallback extends MediaProjection.Callback {
#Override
public void onStop() {
if (isRecording) {
isRecording = false;
mMediaRecorder.stop();
mMediaRecorder.reset();
}
mMediaProjection = null;
stopScreenSharing();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onDestroy() {
if (mHelper != null)
try {
mHelper.dispose();
mHelper = null;
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
if (adView != null) {
adView.destroy();
}
super.onDestroy();
destroyMediaProjection();
}
private void about() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(R.string.about);
builder1.setMessage(R.string.description);
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#SuppressLint("ResourceType")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
about();
return true;
case R.id.share:
shareApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void shareApp() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
#SuppressLint({"StringFormatInvalid", "LocalSuppress"})
String extraText = getString(R.string.share_desc, getString(R.string.link));
intent.putExtra(Intent.EXTRA_TEXT, extraText);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
public void startService() {
Intent serviceIntent = new Intent(this, Background.class);
serviceIntent.putExtra("inputExtra", "Notification");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, Background.class);
stopService(serviceIntent);
}
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
return true;
}
}
And it looks like this:
What am I doing wrong? How can I fix this?
Thanks for any help!
after understanding life cycle and try code onDestroy() to the app it still the same problem that app starting by itself , if i try to close the app in any way exp by multi-tasking it starting again by it self i want to make it don't start again after closing it that code for
MainActivity.java
package com.webcraftbd.radio;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
static String radioTitle = "Radio 16Bar";
static String radioStreamURL = "http://s9.voscast.com:8724";
Button playButton;
Button pauseButton;
Button stopButton;
TextView statusTextView, bufferValueTextView;
NotificationCompat.Builder notifyBuilder;
private RadioUpdateReceiver radioUpdateReceiver;
private RadioService radioServiceBinder;
//Notification
private static final int NOTIFY_ME_ID=12345;
private NotificationManager notifyMgr=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView titleTextView = (TextView) this.findViewById(R.id.titleTextView);
titleTextView.setText(radioTitle);
playButton = (Button) this.findViewById(R.id.PlayButton);
pauseButton = (Button) this.findViewById(R.id.PauseButton);
stopButton = (Button) this.findViewById(R.id.StopButton);
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
pauseButton.setVisibility(View.INVISIBLE);
statusTextView = (TextView) this.findViewById(R.id.StatusDisplayTextView);
notifyMgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
// Bind to the service
Intent bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, RadioService.class));
}
public void onClickPlayButton(View view) {
radioServiceBinder.play();
}
public void onClickPauseButton(View view) {
radioServiceBinder.pause();
}
public void onClickStopButton(View view) {
radioServiceBinder.stop();
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
}
#Override
protected void onResume() {
super.onResume();
/* Register for receiving broadcast messages */
if (radioUpdateReceiver == null) radioUpdateReceiver = new RadioUpdateReceiver();
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_CREATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_DESTROYED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STARTED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PREPARED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PLAYING));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PAUSED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STOPPED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_COMPLETED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_ERROR));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_START));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_END));
}
/* Receive Broadcast Messages from RadioService */
private class RadioUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RadioService.MODE_CREATED)) {
showNotification();
}
else if (intent.getAction().equals(RadioService.MODE_DESTROYED)) {
clearNotification();
}
else if (intent.getAction().equals(RadioService.MODE_STARTED)) {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Buffering...");
}
else if (intent.getAction().equals(RadioService.MODE_PREPARED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Rady");
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_START)) {
updateStatus("Buffering...");
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_END)) {
updateStatus("Playing");
}
else if (intent.getAction().equals(RadioService.MODE_PLAYING)) {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
playButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
showNotification();
updateStatus("Playing");
}
else if(intent.getAction().equals(RadioService.MODE_PAUSED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Paused");
}
else if(intent.getAction().equals(RadioService.MODE_STOPPED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
clearNotification();
}
else if(intent.getAction().equals(RadioService.MODE_COMPLETED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
}
else if(intent.getAction().equals(RadioService.MODE_ERROR)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Error");
}
}
}
public void updateStatus(String status) {
try {
if(notifyBuilder!=null && notifyMgr!=null) {
notifyBuilder.setContentText(status).setWhen(0);
notifyMgr.notify(NOTIFY_ME_ID,notifyBuilder.build());
}
statusTextView.setText(status);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void showNotification() {
notifyBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(radioTitle).setContentText("");
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notifyBuilder.setContentIntent(resultPendingIntent);
notifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(NOTIFY_ME_ID, notifyBuilder.build());
}
public void clearNotification() {
notifyMgr.cancel(NOTIFY_ME_ID);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
// Handles the connection between the service and activity
private ServiceConnection radioConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
radioServiceBinder = ((RadioService.RadioBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
radioServiceBinder = null;
}
};
}